View.java revision e3f23a36d86fedf6c8c6503378cd6d2190c5ab23
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.Build;
44import android.os.Bundle;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Parcel;
48import android.os.Parcelable;
49import android.os.RemoteException;
50import android.os.SystemClock;
51import android.os.SystemProperties;
52import android.text.TextUtils;
53import android.util.AttributeSet;
54import android.util.FloatProperty;
55import android.util.Log;
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.widget.ScrollBarDrawable;
77
78import static android.os.Build.VERSION_CODES.*;
79import static java.lang.Math.max;
80
81import com.android.internal.R;
82import com.android.internal.util.Predicate;
83import com.android.internal.view.menu.MenuBuilder;
84import com.google.android.collect.Lists;
85import com.google.android.collect.Maps;
86
87import java.lang.ref.WeakReference;
88import java.lang.reflect.Field;
89import java.lang.reflect.InvocationTargetException;
90import java.lang.reflect.Method;
91import java.lang.reflect.Modifier;
92import java.util.ArrayList;
93import java.util.Arrays;
94import java.util.Collections;
95import java.util.HashMap;
96import java.util.Locale;
97import java.util.concurrent.CopyOnWriteArrayList;
98import java.util.concurrent.atomic.AtomicInteger;
99
100/**
101 * <p>
102 * This class represents the basic building block for user interface components. A View
103 * occupies a rectangular area on the screen and is responsible for drawing and
104 * event handling. View is the base class for <em>widgets</em>, which are
105 * used to create interactive UI components (buttons, text fields, etc.). The
106 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
107 * are invisible containers that hold other Views (or other ViewGroups) and define
108 * their layout properties.
109 * </p>
110 *
111 * <div class="special reference">
112 * <h3>Developer Guides</h3>
113 * <p>For information about using this class to develop your application's user interface,
114 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
115 * </div>
116 *
117 * <a name="Using"></a>
118 * <h3>Using Views</h3>
119 * <p>
120 * All of the views in a window are arranged in a single tree. You can add views
121 * either from code or by specifying a tree of views in one or more XML layout
122 * files. There are many specialized subclasses of views that act as controls or
123 * are capable of displaying text, images, or other content.
124 * </p>
125 * <p>
126 * Once you have created a tree of views, there are typically a few types of
127 * common operations you may wish to perform:
128 * <ul>
129 * <li><strong>Set properties:</strong> for example setting the text of a
130 * {@link android.widget.TextView}. The available properties and the methods
131 * that set them will vary among the different subclasses of views. Note that
132 * properties that are known at build time can be set in the XML layout
133 * files.</li>
134 * <li><strong>Set focus:</strong> The framework will handled moving focus in
135 * response to user input. To force focus to a specific view, call
136 * {@link #requestFocus}.</li>
137 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
138 * that will be notified when something interesting happens to the view. For
139 * example, all views will let you set a listener to be notified when the view
140 * gains or loses focus. You can register such a listener using
141 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
142 * Other view subclasses offer more specialized listeners. For example, a Button
143 * exposes a listener to notify clients when the button is clicked.</li>
144 * <li><strong>Set visibility:</strong> You can hide or show views using
145 * {@link #setVisibility(int)}.</li>
146 * </ul>
147 * </p>
148 * <p><em>
149 * Note: The Android framework is responsible for measuring, laying out and
150 * drawing views. You should not call methods that perform these actions on
151 * views yourself unless you are actually implementing a
152 * {@link android.view.ViewGroup}.
153 * </em></p>
154 *
155 * <a name="Lifecycle"></a>
156 * <h3>Implementing a Custom View</h3>
157 *
158 * <p>
159 * To implement a custom view, you will usually begin by providing overrides for
160 * some of the standard methods that the framework calls on all views. You do
161 * not need to override all of these methods. In fact, you can start by just
162 * overriding {@link #onDraw(android.graphics.Canvas)}.
163 * <table border="2" width="85%" align="center" cellpadding="5">
164 *     <thead>
165 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
166 *     </thead>
167 *
168 *     <tbody>
169 *     <tr>
170 *         <td rowspan="2">Creation</td>
171 *         <td>Constructors</td>
172 *         <td>There is a form of the constructor that are called when the view
173 *         is created from code and a form that is called when the view is
174 *         inflated from a layout file. The second form should parse and apply
175 *         any attributes defined in the layout file.
176 *         </td>
177 *     </tr>
178 *     <tr>
179 *         <td><code>{@link #onFinishInflate()}</code></td>
180 *         <td>Called after a view and all of its children has been inflated
181 *         from XML.</td>
182 *     </tr>
183 *
184 *     <tr>
185 *         <td rowspan="3">Layout</td>
186 *         <td><code>{@link #onMeasure(int, int)}</code></td>
187 *         <td>Called to determine the size requirements for this view and all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
193 *         <td>Called when this view should assign a size and position to all
194 *         of its children.
195 *         </td>
196 *     </tr>
197 *     <tr>
198 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
199 *         <td>Called when the size of this view has changed.
200 *         </td>
201 *     </tr>
202 *
203 *     <tr>
204 *         <td>Drawing</td>
205 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
206 *         <td>Called when the view should render its content.
207 *         </td>
208 *     </tr>
209 *
210 *     <tr>
211 *         <td rowspan="4">Event processing</td>
212 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
213 *         <td>Called when a new hardware key event occurs.
214 *         </td>
215 *     </tr>
216 *     <tr>
217 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
218 *         <td>Called when a hardware key up event occurs.
219 *         </td>
220 *     </tr>
221 *     <tr>
222 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
223 *         <td>Called when a trackball motion event occurs.
224 *         </td>
225 *     </tr>
226 *     <tr>
227 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
228 *         <td>Called when a touch screen motion event occurs.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td rowspan="2">Focus</td>
234 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
235 *         <td>Called when the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
241 *         <td>Called when the window containing the view gains or loses focus.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td rowspan="3">Attaching</td>
247 *         <td><code>{@link #onAttachedToWindow()}</code></td>
248 *         <td>Called when the view is attached to a window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onDetachedFromWindow}</code></td>
254 *         <td>Called when the view is detached from its window.
255 *         </td>
256 *     </tr>
257 *
258 *     <tr>
259 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
260 *         <td>Called when the visibility of the window containing the view
261 *         has changed.
262 *         </td>
263 *     </tr>
264 *     </tbody>
265 *
266 * </table>
267 * </p>
268 *
269 * <a name="IDs"></a>
270 * <h3>IDs</h3>
271 * Views may have an integer id associated with them. These ids are typically
272 * assigned in the layout XML files, and are used to find specific views within
273 * the view tree. A common pattern is to:
274 * <ul>
275 * <li>Define a Button in the layout file and assign it a unique ID.
276 * <pre>
277 * &lt;Button
278 *     android:id="@+id/my_button"
279 *     android:layout_width="wrap_content"
280 *     android:layout_height="wrap_content"
281 *     android:text="@string/my_button_text"/&gt;
282 * </pre></li>
283 * <li>From the onCreate method of an Activity, find the Button
284 * <pre class="prettyprint">
285 *      Button myButton = (Button) findViewById(R.id.my_button);
286 * </pre></li>
287 * </ul>
288 * <p>
289 * View IDs need not be unique throughout the tree, but it is good practice to
290 * ensure that they are at least unique within the part of the tree you are
291 * searching.
292 * </p>
293 *
294 * <a name="Position"></a>
295 * <h3>Position</h3>
296 * <p>
297 * The geometry of a view is that of a rectangle. A view has a location,
298 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
299 * two dimensions, expressed as a width and a height. The unit for location
300 * and dimensions is the pixel.
301 * </p>
302 *
303 * <p>
304 * It is possible to retrieve the location of a view by invoking the methods
305 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
306 * coordinate of the rectangle representing the view. The latter returns the
307 * top, or Y, coordinate of the rectangle representing the view. These methods
308 * both return the location of the view relative to its parent. For instance,
309 * when getLeft() returns 20, that means the view is located 20 pixels to the
310 * right of the left edge of its direct parent.
311 * </p>
312 *
313 * <p>
314 * In addition, several convenience methods are offered to avoid unnecessary
315 * computations, namely {@link #getRight()} and {@link #getBottom()}.
316 * These methods return the coordinates of the right and bottom edges of the
317 * rectangle representing the view. For instance, calling {@link #getRight()}
318 * is similar to the following computation: <code>getLeft() + getWidth()</code>
319 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
320 * </p>
321 *
322 * <a name="SizePaddingMargins"></a>
323 * <h3>Size, padding and margins</h3>
324 * <p>
325 * The size of a view is expressed with a width and a height. A view actually
326 * possess two pairs of width and height values.
327 * </p>
328 *
329 * <p>
330 * The first pair is known as <em>measured width</em> and
331 * <em>measured height</em>. These dimensions define how big a view wants to be
332 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
333 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
334 * and {@link #getMeasuredHeight()}.
335 * </p>
336 *
337 * <p>
338 * The second pair is simply known as <em>width</em> and <em>height</em>, or
339 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
340 * dimensions define the actual size of the view on screen, at drawing time and
341 * after layout. These values may, but do not have to, be different from the
342 * measured width and height. The width and height can be obtained by calling
343 * {@link #getWidth()} and {@link #getHeight()}.
344 * </p>
345 *
346 * <p>
347 * To measure its dimensions, a view takes into account its padding. The padding
348 * is expressed in pixels for the left, top, right and bottom parts of the view.
349 * Padding can be used to offset the content of the view by a specific amount of
350 * pixels. For instance, a left padding of 2 will push the view's content by
351 * 2 pixels to the right of the left edge. Padding can be set using the
352 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
353 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
354 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
355 * {@link #getPaddingEnd()}.
356 * </p>
357 *
358 * <p>
359 * Even though a view can define a padding, it does not provide any support for
360 * margins. However, view groups provide such a support. Refer to
361 * {@link android.view.ViewGroup} and
362 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
363 * </p>
364 *
365 * <a name="Layout"></a>
366 * <h3>Layout</h3>
367 * <p>
368 * Layout is a two pass process: a measure pass and a layout pass. The measuring
369 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
370 * of the view tree. Each view pushes dimension specifications down the tree
371 * during the recursion. At the end of the measure pass, every view has stored
372 * its measurements. The second pass happens in
373 * {@link #layout(int,int,int,int)} and is also top-down. During
374 * this pass each parent is responsible for positioning all of its children
375 * using the sizes computed in the measure pass.
376 * </p>
377 *
378 * <p>
379 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
380 * {@link #getMeasuredHeight()} values must be set, along with those for all of
381 * that view's descendants. A view's measured width and measured height values
382 * must respect the constraints imposed by the view's parents. This guarantees
383 * that at the end of the measure pass, all parents accept all of their
384 * children's measurements. A parent view may call measure() more than once on
385 * its children. For example, the parent may measure each child once with
386 * unspecified dimensions to find out how big they want to be, then call
387 * measure() on them again with actual numbers if the sum of all the children's
388 * unconstrained sizes is too big or too small.
389 * </p>
390 *
391 * <p>
392 * The measure pass uses two classes to communicate dimensions. The
393 * {@link MeasureSpec} class is used by views to tell their parents how they
394 * want to be measured and positioned. The base LayoutParams class just
395 * describes how big the view wants to be for both width and height. For each
396 * dimension, it can specify one of:
397 * <ul>
398 * <li> an exact number
399 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
400 * (minus padding)
401 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
402 * enclose its content (plus padding).
403 * </ul>
404 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
405 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
406 * an X and Y value.
407 * </p>
408 *
409 * <p>
410 * MeasureSpecs are used to push requirements down the tree from parent to
411 * child. A MeasureSpec can be in one of three modes:
412 * <ul>
413 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
414 * of a child view. For example, a LinearLayout may call measure() on its child
415 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
416 * tall the child view wants to be given a width of 240 pixels.
417 * <li>EXACTLY: This is used by the parent to impose an exact size on the
418 * child. The child must use this size, and guarantee that all of its
419 * descendants will fit within this size.
420 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
421 * child. The child must gurantee that it and all of its descendants will fit
422 * within this size.
423 * </ul>
424 * </p>
425 *
426 * <p>
427 * To intiate a layout, call {@link #requestLayout}. This method is typically
428 * called by a view on itself when it believes that is can no longer fit within
429 * its current bounds.
430 * </p>
431 *
432 * <a name="Drawing"></a>
433 * <h3>Drawing</h3>
434 * <p>
435 * Drawing is handled by walking the tree and rendering each view that
436 * intersects the invalid region. Because the tree is traversed in-order,
437 * this means that parents will draw before (i.e., behind) their children, with
438 * siblings drawn in the order they appear in the tree.
439 * If you set a background drawable for a View, then the View will draw it for you
440 * before calling back to its <code>onDraw()</code> method.
441 * </p>
442 *
443 * <p>
444 * Note that the framework will not draw views that are not in the invalid region.
445 * </p>
446 *
447 * <p>
448 * To force a view to draw, call {@link #invalidate()}.
449 * </p>
450 *
451 * <a name="EventHandlingThreading"></a>
452 * <h3>Event Handling and Threading</h3>
453 * <p>
454 * The basic cycle of a view is as follows:
455 * <ol>
456 * <li>An event comes in and is dispatched to the appropriate view. The view
457 * handles the event and notifies any listeners.</li>
458 * <li>If in the course of processing the event, the view's bounds may need
459 * to be changed, the view will call {@link #requestLayout()}.</li>
460 * <li>Similarly, if in the course of processing the event the view's appearance
461 * may need to be changed, the view will call {@link #invalidate()}.</li>
462 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
463 * the framework will take care of measuring, laying out, and drawing the tree
464 * as appropriate.</li>
465 * </ol>
466 * </p>
467 *
468 * <p><em>Note: The entire view tree is single threaded. You must always be on
469 * the UI thread when calling any method on any view.</em>
470 * If you are doing work on other threads and want to update the state of a view
471 * from that thread, you should use a {@link Handler}.
472 * </p>
473 *
474 * <a name="FocusHandling"></a>
475 * <h3>Focus Handling</h3>
476 * <p>
477 * The framework will handle routine focus movement in response to user input.
478 * This includes changing the focus as views are removed or hidden, or as new
479 * views become available. Views indicate their willingness to take focus
480 * through the {@link #isFocusable} method. To change whether a view can take
481 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
482 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
483 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
484 * </p>
485 * <p>
486 * Focus movement is based on an algorithm which finds the nearest neighbor in a
487 * given direction. In rare cases, the default algorithm may not match the
488 * intended behavior of the developer. In these situations, you can provide
489 * explicit overrides by using these XML attributes in the layout file:
490 * <pre>
491 * nextFocusDown
492 * nextFocusLeft
493 * nextFocusRight
494 * nextFocusUp
495 * </pre>
496 * </p>
497 *
498 *
499 * <p>
500 * To get a particular view to take focus, call {@link #requestFocus()}.
501 * </p>
502 *
503 * <a name="TouchMode"></a>
504 * <h3>Touch Mode</h3>
505 * <p>
506 * When a user is navigating a user interface via directional keys such as a D-pad, it is
507 * necessary to give focus to actionable items such as buttons so the user can see
508 * what will take input.  If the device has touch capabilities, however, and the user
509 * begins interacting with the interface by touching it, it is no longer necessary to
510 * always highlight, or give focus to, a particular view.  This motivates a mode
511 * for interaction named 'touch mode'.
512 * </p>
513 * <p>
514 * For a touch capable device, once the user touches the screen, the device
515 * will enter touch mode.  From this point onward, only views for which
516 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
517 * Other views that are touchable, like buttons, will not take focus when touched; they will
518 * only fire the on click listeners.
519 * </p>
520 * <p>
521 * Any time a user hits a directional key, such as a D-pad direction, the view device will
522 * exit touch mode, and find a view to take focus, so that the user may resume interacting
523 * with the user interface without touching the screen again.
524 * </p>
525 * <p>
526 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
527 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
528 * </p>
529 *
530 * <a name="Scrolling"></a>
531 * <h3>Scrolling</h3>
532 * <p>
533 * The framework provides basic support for views that wish to internally
534 * scroll their content. This includes keeping track of the X and Y scroll
535 * offset as well as mechanisms for drawing scrollbars. See
536 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
537 * {@link #awakenScrollBars()} for more details.
538 * </p>
539 *
540 * <a name="Tags"></a>
541 * <h3>Tags</h3>
542 * <p>
543 * Unlike IDs, tags are not used to identify views. Tags are essentially an
544 * extra piece of information that can be associated with a view. They are most
545 * often used as a convenience to store data related to views in the views
546 * themselves rather than by putting them in a separate structure.
547 * </p>
548 *
549 * <a name="Properties"></a>
550 * <h3>Properties</h3>
551 * <p>
552 * The View class exposes an {@link #ALPHA} property, as well as several transform-related
553 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are
554 * available both in the {@link Property} form as well as in similarly-named setter/getter
555 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can
556 * be used to set persistent state associated with these rendering-related properties on the view.
557 * The properties and methods can also be used in conjunction with
558 * {@link android.animation.Animator Animator}-based animations, described more in the
559 * <a href="#Animation">Animation</a> section.
560 * </p>
561 *
562 * <a name="Animation"></a>
563 * <h3>Animation</h3>
564 * <p>
565 * Starting with Android 3.0, the preferred way of animating views is to use the
566 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based
567 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and
568 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0
569 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only
570 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class
571 * makes animating these View properties particularly easy and efficient.
572 * </p>
573 * <p>
574 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered.
575 * You can attach an {@link Animation} object to a view using
576 * {@link #setAnimation(Animation)} or
577 * {@link #startAnimation(Animation)}. The animation can alter the scale,
578 * rotation, translation and alpha of a view over time. If the animation is
579 * attached to a view that has children, the animation will affect the entire
580 * subtree rooted by that node. When an animation is started, the framework will
581 * take care of redrawing the appropriate views until the animation completes.
582 * </p>
583 *
584 * <a name="Security"></a>
585 * <h3>Security</h3>
586 * <p>
587 * Sometimes it is essential that an application be able to verify that an action
588 * is being performed with the full knowledge and consent of the user, such as
589 * granting a permission request, making a purchase or clicking on an advertisement.
590 * Unfortunately, a malicious application could try to spoof the user into
591 * performing these actions, unaware, by concealing the intended purpose of the view.
592 * As a remedy, the framework offers a touch filtering mechanism that can be used to
593 * improve the security of views that provide access to sensitive functionality.
594 * </p><p>
595 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
596 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
597 * will discard touches that are received whenever the view's window is obscured by
598 * another visible window.  As a result, the view will not receive touches whenever a
599 * toast, dialog or other window appears above the view's window.
600 * </p><p>
601 * For more fine-grained control over security, consider overriding the
602 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
603 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
604 * </p>
605 *
606 * @attr ref android.R.styleable#View_alpha
607 * @attr ref android.R.styleable#View_background
608 * @attr ref android.R.styleable#View_clickable
609 * @attr ref android.R.styleable#View_contentDescription
610 * @attr ref android.R.styleable#View_drawingCacheQuality
611 * @attr ref android.R.styleable#View_duplicateParentState
612 * @attr ref android.R.styleable#View_id
613 * @attr ref android.R.styleable#View_requiresFadingEdge
614 * @attr ref android.R.styleable#View_fadeScrollbars
615 * @attr ref android.R.styleable#View_fadingEdgeLength
616 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
617 * @attr ref android.R.styleable#View_fitsSystemWindows
618 * @attr ref android.R.styleable#View_isScrollContainer
619 * @attr ref android.R.styleable#View_focusable
620 * @attr ref android.R.styleable#View_focusableInTouchMode
621 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
622 * @attr ref android.R.styleable#View_keepScreenOn
623 * @attr ref android.R.styleable#View_layerType
624 * @attr ref android.R.styleable#View_layoutDirection
625 * @attr ref android.R.styleable#View_longClickable
626 * @attr ref android.R.styleable#View_minHeight
627 * @attr ref android.R.styleable#View_minWidth
628 * @attr ref android.R.styleable#View_nextFocusDown
629 * @attr ref android.R.styleable#View_nextFocusLeft
630 * @attr ref android.R.styleable#View_nextFocusRight
631 * @attr ref android.R.styleable#View_nextFocusUp
632 * @attr ref android.R.styleable#View_onClick
633 * @attr ref android.R.styleable#View_padding
634 * @attr ref android.R.styleable#View_paddingBottom
635 * @attr ref android.R.styleable#View_paddingLeft
636 * @attr ref android.R.styleable#View_paddingRight
637 * @attr ref android.R.styleable#View_paddingTop
638 * @attr ref android.R.styleable#View_paddingStart
639 * @attr ref android.R.styleable#View_paddingEnd
640 * @attr ref android.R.styleable#View_saveEnabled
641 * @attr ref android.R.styleable#View_rotation
642 * @attr ref android.R.styleable#View_rotationX
643 * @attr ref android.R.styleable#View_rotationY
644 * @attr ref android.R.styleable#View_scaleX
645 * @attr ref android.R.styleable#View_scaleY
646 * @attr ref android.R.styleable#View_scrollX
647 * @attr ref android.R.styleable#View_scrollY
648 * @attr ref android.R.styleable#View_scrollbarSize
649 * @attr ref android.R.styleable#View_scrollbarStyle
650 * @attr ref android.R.styleable#View_scrollbars
651 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
652 * @attr ref android.R.styleable#View_scrollbarFadeDuration
653 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
654 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
655 * @attr ref android.R.styleable#View_scrollbarThumbVertical
656 * @attr ref android.R.styleable#View_scrollbarTrackVertical
657 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
658 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
659 * @attr ref android.R.styleable#View_soundEffectsEnabled
660 * @attr ref android.R.styleable#View_tag
661 * @attr ref android.R.styleable#View_textAlignment
662 * @attr ref android.R.styleable#View_textDirection
663 * @attr ref android.R.styleable#View_transformPivotX
664 * @attr ref android.R.styleable#View_transformPivotY
665 * @attr ref android.R.styleable#View_translationX
666 * @attr ref android.R.styleable#View_translationY
667 * @attr ref android.R.styleable#View_visibility
668 *
669 * @see android.view.ViewGroup
670 */
671public class View implements Drawable.Callback, KeyEvent.Callback,
672        AccessibilityEventSource {
673    private static final boolean DBG = false;
674
675    /**
676     * The logging tag used by this class with android.util.Log.
677     */
678    protected static final String VIEW_LOG_TAG = "View";
679
680    /**
681     * When set to true, apps will draw debugging information about their layouts.
682     *
683     * @hide
684     */
685    public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout";
686
687    /**
688     * Used to mark a View that has no ID.
689     */
690    public static final int NO_ID = -1;
691
692    private static boolean sUseBrokenMakeMeasureSpec = false;
693
694    /**
695     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
696     * calling setFlags.
697     */
698    private static final int NOT_FOCUSABLE = 0x00000000;
699
700    /**
701     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
702     * setFlags.
703     */
704    private static final int FOCUSABLE = 0x00000001;
705
706    /**
707     * Mask for use with setFlags indicating bits used for focus.
708     */
709    private static final int FOCUSABLE_MASK = 0x00000001;
710
711    /**
712     * This view will adjust its padding to fit sytem windows (e.g. status bar)
713     */
714    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
715
716    /**
717     * This view is visible.
718     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
719     * android:visibility}.
720     */
721    public static final int VISIBLE = 0x00000000;
722
723    /**
724     * This view is invisible, but it still takes up space for layout purposes.
725     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
726     * android:visibility}.
727     */
728    public static final int INVISIBLE = 0x00000004;
729
730    /**
731     * This view is invisible, and it doesn't take any space for layout
732     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
733     * android:visibility}.
734     */
735    public static final int GONE = 0x00000008;
736
737    /**
738     * Mask for use with setFlags indicating bits used for visibility.
739     * {@hide}
740     */
741    static final int VISIBILITY_MASK = 0x0000000C;
742
743    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
744
745    /**
746     * This view is enabled. Interpretation varies by subclass.
747     * Use with ENABLED_MASK when calling setFlags.
748     * {@hide}
749     */
750    static final int ENABLED = 0x00000000;
751
752    /**
753     * This view is disabled. Interpretation varies by subclass.
754     * Use with ENABLED_MASK when calling setFlags.
755     * {@hide}
756     */
757    static final int DISABLED = 0x00000020;
758
759   /**
760    * Mask for use with setFlags indicating bits used for indicating whether
761    * this view is enabled
762    * {@hide}
763    */
764    static final int ENABLED_MASK = 0x00000020;
765
766    /**
767     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
768     * called and further optimizations will be performed. It is okay to have
769     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
770     * {@hide}
771     */
772    static final int WILL_NOT_DRAW = 0x00000080;
773
774    /**
775     * Mask for use with setFlags indicating bits used for indicating whether
776     * this view is will draw
777     * {@hide}
778     */
779    static final int DRAW_MASK = 0x00000080;
780
781    /**
782     * <p>This view doesn't show scrollbars.</p>
783     * {@hide}
784     */
785    static final int SCROLLBARS_NONE = 0x00000000;
786
787    /**
788     * <p>This view shows horizontal scrollbars.</p>
789     * {@hide}
790     */
791    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
792
793    /**
794     * <p>This view shows vertical scrollbars.</p>
795     * {@hide}
796     */
797    static final int SCROLLBARS_VERTICAL = 0x00000200;
798
799    /**
800     * <p>Mask for use with setFlags indicating bits used for indicating which
801     * scrollbars are enabled.</p>
802     * {@hide}
803     */
804    static final int SCROLLBARS_MASK = 0x00000300;
805
806    /**
807     * Indicates that the view should filter touches when its window is obscured.
808     * Refer to the class comments for more information about this security feature.
809     * {@hide}
810     */
811    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
812
813    /**
814     * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate
815     * that they are optional and should be skipped if the window has
816     * requested system UI flags that ignore those insets for layout.
817     */
818    static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800;
819
820    /**
821     * <p>This view doesn't show fading edges.</p>
822     * {@hide}
823     */
824    static final int FADING_EDGE_NONE = 0x00000000;
825
826    /**
827     * <p>This view shows horizontal fading edges.</p>
828     * {@hide}
829     */
830    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
831
832    /**
833     * <p>This view shows vertical fading edges.</p>
834     * {@hide}
835     */
836    static final int FADING_EDGE_VERTICAL = 0x00002000;
837
838    /**
839     * <p>Mask for use with setFlags indicating bits used for indicating which
840     * fading edges are enabled.</p>
841     * {@hide}
842     */
843    static final int FADING_EDGE_MASK = 0x00003000;
844
845    /**
846     * <p>Indicates this view can be clicked. When clickable, a View reacts
847     * to clicks by notifying the OnClickListener.<p>
848     * {@hide}
849     */
850    static final int CLICKABLE = 0x00004000;
851
852    /**
853     * <p>Indicates this view is caching its drawing into a bitmap.</p>
854     * {@hide}
855     */
856    static final int DRAWING_CACHE_ENABLED = 0x00008000;
857
858    /**
859     * <p>Indicates that no icicle should be saved for this view.<p>
860     * {@hide}
861     */
862    static final int SAVE_DISABLED = 0x000010000;
863
864    /**
865     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
866     * property.</p>
867     * {@hide}
868     */
869    static final int SAVE_DISABLED_MASK = 0x000010000;
870
871    /**
872     * <p>Indicates that no drawing cache should ever be created for this view.<p>
873     * {@hide}
874     */
875    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
876
877    /**
878     * <p>Indicates this view can take / keep focus when int touch mode.</p>
879     * {@hide}
880     */
881    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
882
883    /**
884     * <p>Enables low quality mode for the drawing cache.</p>
885     */
886    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
887
888    /**
889     * <p>Enables high quality mode for the drawing cache.</p>
890     */
891    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
892
893    /**
894     * <p>Enables automatic quality mode for the drawing cache.</p>
895     */
896    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
897
898    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
899            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
900    };
901
902    /**
903     * <p>Mask for use with setFlags indicating bits used for the cache
904     * quality property.</p>
905     * {@hide}
906     */
907    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
908
909    /**
910     * <p>
911     * Indicates this view can be long clicked. When long clickable, a View
912     * reacts to long clicks by notifying the OnLongClickListener or showing a
913     * context menu.
914     * </p>
915     * {@hide}
916     */
917    static final int LONG_CLICKABLE = 0x00200000;
918
919    /**
920     * <p>Indicates that this view gets its drawable states from its direct parent
921     * and ignores its original internal states.</p>
922     *
923     * @hide
924     */
925    static final int DUPLICATE_PARENT_STATE = 0x00400000;
926
927    /**
928     * The scrollbar style to display the scrollbars inside the content area,
929     * without increasing the padding. The scrollbars will be overlaid with
930     * translucency on the view's content.
931     */
932    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
933
934    /**
935     * The scrollbar style to display the scrollbars inside the padded area,
936     * increasing the padding of the view. The scrollbars will not overlap the
937     * content area of the view.
938     */
939    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
940
941    /**
942     * The scrollbar style to display the scrollbars at the edge of the view,
943     * without increasing the padding. The scrollbars will be overlaid with
944     * translucency.
945     */
946    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
947
948    /**
949     * The scrollbar style to display the scrollbars at the edge of the view,
950     * increasing the padding of the view. The scrollbars will only overlap the
951     * background, if any.
952     */
953    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
954
955    /**
956     * Mask to check if the scrollbar style is overlay or inset.
957     * {@hide}
958     */
959    static final int SCROLLBARS_INSET_MASK = 0x01000000;
960
961    /**
962     * Mask to check if the scrollbar style is inside or outside.
963     * {@hide}
964     */
965    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
966
967    /**
968     * Mask for scrollbar style.
969     * {@hide}
970     */
971    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
972
973    /**
974     * View flag indicating that the screen should remain on while the
975     * window containing this view is visible to the user.  This effectively
976     * takes care of automatically setting the WindowManager's
977     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
978     */
979    public static final int KEEP_SCREEN_ON = 0x04000000;
980
981    /**
982     * View flag indicating whether this view should have sound effects enabled
983     * for events such as clicking and touching.
984     */
985    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
986
987    /**
988     * View flag indicating whether this view should have haptic feedback
989     * enabled for events such as long presses.
990     */
991    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
992
993    /**
994     * <p>Indicates that the view hierarchy should stop saving state when
995     * it reaches this view.  If state saving is initiated immediately at
996     * the view, it will be allowed.
997     * {@hide}
998     */
999    static final int PARENT_SAVE_DISABLED = 0x20000000;
1000
1001    /**
1002     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
1003     * {@hide}
1004     */
1005    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
1006
1007    /**
1008     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1009     * should add all focusable Views regardless if they are focusable in touch mode.
1010     */
1011    public static final int FOCUSABLES_ALL = 0x00000000;
1012
1013    /**
1014     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1015     * should add only Views focusable in touch mode.
1016     */
1017    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1021     * item.
1022     */
1023    public static final int FOCUS_BACKWARD = 0x00000001;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1027     * item.
1028     */
1029    public static final int FOCUS_FORWARD = 0x00000002;
1030
1031    /**
1032     * Use with {@link #focusSearch(int)}. Move focus to the left.
1033     */
1034    public static final int FOCUS_LEFT = 0x00000011;
1035
1036    /**
1037     * Use with {@link #focusSearch(int)}. Move focus up.
1038     */
1039    public static final int FOCUS_UP = 0x00000021;
1040
1041    /**
1042     * Use with {@link #focusSearch(int)}. Move focus to the right.
1043     */
1044    public static final int FOCUS_RIGHT = 0x00000042;
1045
1046    /**
1047     * Use with {@link #focusSearch(int)}. Move focus down.
1048     */
1049    public static final int FOCUS_DOWN = 0x00000082;
1050
1051    /**
1052     * Bits of {@link #getMeasuredWidthAndState()} and
1053     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1054     */
1055    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1056
1057    /**
1058     * Bits of {@link #getMeasuredWidthAndState()} and
1059     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1060     */
1061    public static final int MEASURED_STATE_MASK = 0xff000000;
1062
1063    /**
1064     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1065     * for functions that combine both width and height into a single int,
1066     * such as {@link #getMeasuredState()} and the childState argument of
1067     * {@link #resolveSizeAndState(int, int, int)}.
1068     */
1069    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1070
1071    /**
1072     * Bit of {@link #getMeasuredWidthAndState()} and
1073     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1074     * is smaller that the space the view would like to have.
1075     */
1076    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1077
1078    /**
1079     * Base View state sets
1080     */
1081    // Singles
1082    /**
1083     * Indicates the view has no states set. States are used with
1084     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1085     * view depending on its state.
1086     *
1087     * @see android.graphics.drawable.Drawable
1088     * @see #getDrawableState()
1089     */
1090    protected static final int[] EMPTY_STATE_SET;
1091    /**
1092     * Indicates the view is enabled. States are used with
1093     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1094     * view depending on its state.
1095     *
1096     * @see android.graphics.drawable.Drawable
1097     * @see #getDrawableState()
1098     */
1099    protected static final int[] ENABLED_STATE_SET;
1100    /**
1101     * Indicates the view is focused. States are used with
1102     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1103     * view depending on its state.
1104     *
1105     * @see android.graphics.drawable.Drawable
1106     * @see #getDrawableState()
1107     */
1108    protected static final int[] FOCUSED_STATE_SET;
1109    /**
1110     * Indicates the view is selected. States are used with
1111     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1112     * view depending on its state.
1113     *
1114     * @see android.graphics.drawable.Drawable
1115     * @see #getDrawableState()
1116     */
1117    protected static final int[] SELECTED_STATE_SET;
1118    /**
1119     * Indicates the view is pressed. States are used with
1120     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1121     * view depending on its state.
1122     *
1123     * @see android.graphics.drawable.Drawable
1124     * @see #getDrawableState()
1125     * @hide
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    /**
1567     * The view's tag.
1568     * {@hide}
1569     *
1570     * @see #setTag(Object)
1571     * @see #getTag()
1572     */
1573    protected Object mTag;
1574
1575    // for mPrivateFlags:
1576    /** {@hide} */
1577    static final int PFLAG_WANTS_FOCUS                 = 0x00000001;
1578    /** {@hide} */
1579    static final int PFLAG_FOCUSED                     = 0x00000002;
1580    /** {@hide} */
1581    static final int PFLAG_SELECTED                    = 0x00000004;
1582    /** {@hide} */
1583    static final int PFLAG_IS_ROOT_NAMESPACE           = 0x00000008;
1584    /** {@hide} */
1585    static final int PFLAG_HAS_BOUNDS                  = 0x00000010;
1586    /** {@hide} */
1587    static final int PFLAG_DRAWN                       = 0x00000020;
1588    /**
1589     * When this flag is set, this view is running an animation on behalf of its
1590     * children and should therefore not cancel invalidate requests, even if they
1591     * lie outside of this view's bounds.
1592     *
1593     * {@hide}
1594     */
1595    static final int PFLAG_DRAW_ANIMATION              = 0x00000040;
1596    /** {@hide} */
1597    static final int PFLAG_SKIP_DRAW                   = 0x00000080;
1598    /** {@hide} */
1599    static final int PFLAG_ONLY_DRAWS_BACKGROUND       = 0x00000100;
1600    /** {@hide} */
1601    static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200;
1602    /** {@hide} */
1603    static final int PFLAG_DRAWABLE_STATE_DIRTY        = 0x00000400;
1604    /** {@hide} */
1605    static final int PFLAG_MEASURED_DIMENSION_SET      = 0x00000800;
1606    /** {@hide} */
1607    static final int PFLAG_FORCE_LAYOUT                = 0x00001000;
1608    /** {@hide} */
1609    static final int PFLAG_LAYOUT_REQUIRED             = 0x00002000;
1610
1611    private static final int PFLAG_PRESSED             = 0x00004000;
1612
1613    /** {@hide} */
1614    static final int PFLAG_DRAWING_CACHE_VALID         = 0x00008000;
1615    /**
1616     * Flag used to indicate that this view should be drawn once more (and only once
1617     * more) after its animation has completed.
1618     * {@hide}
1619     */
1620    static final int PFLAG_ANIMATION_STARTED           = 0x00010000;
1621
1622    private static final int PFLAG_SAVE_STATE_CALLED   = 0x00020000;
1623
1624    /**
1625     * Indicates that the View returned true when onSetAlpha() was called and that
1626     * the alpha must be restored.
1627     * {@hide}
1628     */
1629    static final int PFLAG_ALPHA_SET                   = 0x00040000;
1630
1631    /**
1632     * Set by {@link #setScrollContainer(boolean)}.
1633     */
1634    static final int PFLAG_SCROLL_CONTAINER            = 0x00080000;
1635
1636    /**
1637     * Set by {@link #setScrollContainer(boolean)}.
1638     */
1639    static final int PFLAG_SCROLL_CONTAINER_ADDED      = 0x00100000;
1640
1641    /**
1642     * View flag indicating whether this view was invalidated (fully or partially.)
1643     *
1644     * @hide
1645     */
1646    static final int PFLAG_DIRTY                       = 0x00200000;
1647
1648    /**
1649     * View flag indicating whether this view was invalidated by an opaque
1650     * invalidate request.
1651     *
1652     * @hide
1653     */
1654    static final int PFLAG_DIRTY_OPAQUE                = 0x00400000;
1655
1656    /**
1657     * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}.
1658     *
1659     * @hide
1660     */
1661    static final int PFLAG_DIRTY_MASK                  = 0x00600000;
1662
1663    /**
1664     * Indicates whether the background is opaque.
1665     *
1666     * @hide
1667     */
1668    static final int PFLAG_OPAQUE_BACKGROUND           = 0x00800000;
1669
1670    /**
1671     * Indicates whether the scrollbars are opaque.
1672     *
1673     * @hide
1674     */
1675    static final int PFLAG_OPAQUE_SCROLLBARS           = 0x01000000;
1676
1677    /**
1678     * Indicates whether the view is opaque.
1679     *
1680     * @hide
1681     */
1682    static final int PFLAG_OPAQUE_MASK                 = 0x01800000;
1683
1684    /**
1685     * Indicates a prepressed state;
1686     * the short time between ACTION_DOWN and recognizing
1687     * a 'real' press. Prepressed is used to recognize quick taps
1688     * even when they are shorter than ViewConfiguration.getTapTimeout().
1689     *
1690     * @hide
1691     */
1692    private static final int PFLAG_PREPRESSED          = 0x02000000;
1693
1694    /**
1695     * Indicates whether the view is temporarily detached.
1696     *
1697     * @hide
1698     */
1699    static final int PFLAG_CANCEL_NEXT_UP_EVENT        = 0x04000000;
1700
1701    /**
1702     * Indicates that we should awaken scroll bars once attached
1703     *
1704     * @hide
1705     */
1706    private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1707
1708    /**
1709     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1710     * @hide
1711     */
1712    private static final int PFLAG_HOVERED             = 0x10000000;
1713
1714    /**
1715     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1716     * for transform operations
1717     *
1718     * @hide
1719     */
1720    private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000;
1721
1722    /** {@hide} */
1723    static final int PFLAG_ACTIVATED                   = 0x40000000;
1724
1725    /**
1726     * Indicates that this view was specifically invalidated, not just dirtied because some
1727     * child view was invalidated. The flag is used to determine when we need to recreate
1728     * a view's display list (as opposed to just returning a reference to its existing
1729     * display list).
1730     *
1731     * @hide
1732     */
1733    static final int PFLAG_INVALIDATED                 = 0x80000000;
1734
1735    /**
1736     * Masks for mPrivateFlags2, as generated by dumpFlags():
1737     *
1738     * -------|-------|-------|-------|
1739     *                                  PFLAG2_TEXT_ALIGNMENT_FLAGS[0]
1740     *                                  PFLAG2_TEXT_DIRECTION_FLAGS[0]
1741     *                                1 PFLAG2_DRAG_CAN_ACCEPT
1742     *                               1  PFLAG2_DRAG_HOVERED
1743     *                               1  PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT
1744     *                              11  PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1745     *                             1 1  PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT
1746     *                             11   PFLAG2_LAYOUT_DIRECTION_MASK
1747     *                             11 1 PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
1748     *                            1     PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL
1749     *                            1   1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT
1750     *                            1 1   PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT
1751     *                           1      PFLAG2_LAYOUT_DIRECTION_RESOLVED
1752     *                           11     PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK
1753     *                          1       PFLAG2_TEXT_DIRECTION_FLAGS[1]
1754     *                         1        PFLAG2_TEXT_DIRECTION_FLAGS[2]
1755     *                         11       PFLAG2_TEXT_DIRECTION_FLAGS[3]
1756     *                        1         PFLAG2_TEXT_DIRECTION_FLAGS[4]
1757     *                        1 1       PFLAG2_TEXT_DIRECTION_FLAGS[5]
1758     *                        111       PFLAG2_TEXT_DIRECTION_MASK
1759     *                       1          PFLAG2_TEXT_DIRECTION_RESOLVED
1760     *                      1           PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT
1761     *                    111           PFLAG2_TEXT_DIRECTION_RESOLVED_MASK
1762     *                   1              PFLAG2_TEXT_ALIGNMENT_FLAGS[1]
1763     *                  1               PFLAG2_TEXT_ALIGNMENT_FLAGS[2]
1764     *                  11              PFLAG2_TEXT_ALIGNMENT_FLAGS[3]
1765     *                 1                PFLAG2_TEXT_ALIGNMENT_FLAGS[4]
1766     *                 1 1              PFLAG2_TEXT_ALIGNMENT_FLAGS[5]
1767     *                 11               PFLAG2_TEXT_ALIGNMENT_FLAGS[6]
1768     *                 111              PFLAG2_TEXT_ALIGNMENT_MASK
1769     *                1                 PFLAG2_TEXT_ALIGNMENT_RESOLVED
1770     *               1                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT
1771     *             111                  PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK
1772     *           11                     PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK
1773     *          1                       PFLAG2_HAS_TRANSIENT_STATE
1774     *      1                           PFLAG2_ACCESSIBILITY_FOCUSED
1775     *     1                            PFLAG2_ACCESSIBILITY_STATE_CHANGED
1776     *    1                             PFLAG2_VIEW_QUICK_REJECTED
1777     *   1                              PFLAG2_PADDING_RESOLVED
1778     * -------|-------|-------|-------|
1779     */
1780
1781    /**
1782     * Indicates that this view has reported that it can accept the current drag's content.
1783     * Cleared when the drag operation concludes.
1784     * @hide
1785     */
1786    static final int PFLAG2_DRAG_CAN_ACCEPT            = 0x00000001;
1787
1788    /**
1789     * Indicates that this view is currently directly under the drag location in a
1790     * drag-and-drop operation involving content that it can accept.  Cleared when
1791     * the drag exits the view, or when the drag operation concludes.
1792     * @hide
1793     */
1794    static final int PFLAG2_DRAG_HOVERED               = 0x00000002;
1795
1796    /**
1797     * Horizontal layout direction of this view is from Left to Right.
1798     * Use with {@link #setLayoutDirection}.
1799     */
1800    public static final int LAYOUT_DIRECTION_LTR = 0;
1801
1802    /**
1803     * Horizontal layout direction of this view is from Right to Left.
1804     * Use with {@link #setLayoutDirection}.
1805     */
1806    public static final int LAYOUT_DIRECTION_RTL = 1;
1807
1808    /**
1809     * Horizontal layout direction of this view is inherited from its parent.
1810     * Use with {@link #setLayoutDirection}.
1811     */
1812    public static final int LAYOUT_DIRECTION_INHERIT = 2;
1813
1814    /**
1815     * Horizontal layout direction of this view is from deduced from the default language
1816     * script for the locale. Use with {@link #setLayoutDirection}.
1817     */
1818    public static final int LAYOUT_DIRECTION_LOCALE = 3;
1819
1820    /**
1821     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1822     * @hide
1823     */
1824    static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2;
1825
1826    /**
1827     * Mask for use with private flags indicating bits used for horizontal layout direction.
1828     * @hide
1829     */
1830    static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1831
1832    /**
1833     * Indicates whether the view horizontal layout direction has been resolved and drawn to the
1834     * right-to-left direction.
1835     * @hide
1836     */
1837    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1838
1839    /**
1840     * Indicates whether the view horizontal layout direction has been resolved.
1841     * @hide
1842     */
1843    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1844
1845    /**
1846     * Mask for use with private flags indicating bits used for resolved horizontal layout direction.
1847     * @hide
1848     */
1849    static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C
1850            << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
1851
1852    /*
1853     * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct
1854     * flag value.
1855     * @hide
1856     */
1857    private static final int[] LAYOUT_DIRECTION_FLAGS = {
1858            LAYOUT_DIRECTION_LTR,
1859            LAYOUT_DIRECTION_RTL,
1860            LAYOUT_DIRECTION_INHERIT,
1861            LAYOUT_DIRECTION_LOCALE
1862    };
1863
1864    /**
1865     * Default horizontal layout direction.
1866     */
1867    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1868
1869    /**
1870     * Default horizontal layout direction.
1871     * @hide
1872     */
1873    static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR;
1874
1875    /**
1876     * Indicates that the view is tracking some sort of transient state
1877     * that the app should not need to be aware of, but that the framework
1878     * should take special care to preserve.
1879     *
1880     * @hide
1881     */
1882    static final int PFLAG2_HAS_TRANSIENT_STATE = 0x1 << 22;
1883
1884    /**
1885     * Text direction is inherited thru {@link ViewGroup}
1886     */
1887    public static final int TEXT_DIRECTION_INHERIT = 0;
1888
1889    /**
1890     * Text direction is using "first strong algorithm". The first strong directional character
1891     * determines the paragraph direction. If there is no strong directional character, the
1892     * paragraph direction is the view's resolved layout direction.
1893     */
1894    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
1895
1896    /**
1897     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
1898     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
1899     * If there are neither, the paragraph direction is the view's resolved layout direction.
1900     */
1901    public static final int TEXT_DIRECTION_ANY_RTL = 2;
1902
1903    /**
1904     * Text direction is forced to LTR.
1905     */
1906    public static final int TEXT_DIRECTION_LTR = 3;
1907
1908    /**
1909     * Text direction is forced to RTL.
1910     */
1911    public static final int TEXT_DIRECTION_RTL = 4;
1912
1913    /**
1914     * Text direction is coming from the system Locale.
1915     */
1916    public static final int TEXT_DIRECTION_LOCALE = 5;
1917
1918    /**
1919     * Default text direction is inherited
1920     */
1921    private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT;
1922
1923    /**
1924     * Default resolved text direction
1925     * @hide
1926     */
1927    static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG;
1928
1929    /**
1930     * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED)
1931     * @hide
1932     */
1933    static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6;
1934
1935    /**
1936     * Mask for use with private flags indicating bits used for text direction.
1937     * @hide
1938     */
1939    static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007
1940            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1941
1942    /**
1943     * Array of text direction flags for mapping attribute "textDirection" to correct
1944     * flag value.
1945     * @hide
1946     */
1947    private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = {
1948            TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1949            TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1950            TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1951            TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1952            TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT,
1953            TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT
1954    };
1955
1956    /**
1957     * Indicates whether the view text direction has been resolved.
1958     * @hide
1959     */
1960    static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008
1961            << PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
1962
1963    /**
1964     * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
1965     * @hide
1966     */
1967    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10;
1968
1969    /**
1970     * Mask for use with private flags indicating bits used for resolved text direction.
1971     * @hide
1972     */
1973    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007
1974            << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1975
1976    /**
1977     * Indicates whether the view text direction has been resolved to the "first strong" heuristic.
1978     * @hide
1979     */
1980    static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT =
1981            TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
1982
1983    /*
1984     * Default text alignment. The text alignment of this View is inherited from its parent.
1985     * Use with {@link #setTextAlignment(int)}
1986     */
1987    public static final int TEXT_ALIGNMENT_INHERIT = 0;
1988
1989    /**
1990     * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL,
1991     * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction.
1992     *
1993     * Use with {@link #setTextAlignment(int)}
1994     */
1995    public static final int TEXT_ALIGNMENT_GRAVITY = 1;
1996
1997    /**
1998     * Align to the start of the paragraph, e.g. ALIGN_NORMAL.
1999     *
2000     * Use with {@link #setTextAlignment(int)}
2001     */
2002    public static final int TEXT_ALIGNMENT_TEXT_START = 2;
2003
2004    /**
2005     * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE.
2006     *
2007     * Use with {@link #setTextAlignment(int)}
2008     */
2009    public static final int TEXT_ALIGNMENT_TEXT_END = 3;
2010
2011    /**
2012     * Center the paragraph, e.g. ALIGN_CENTER.
2013     *
2014     * Use with {@link #setTextAlignment(int)}
2015     */
2016    public static final int TEXT_ALIGNMENT_CENTER = 4;
2017
2018    /**
2019     * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved
2020     * layoutDirection is LTR, and ALIGN_RIGHT otherwise.
2021     *
2022     * Use with {@link #setTextAlignment(int)}
2023     */
2024    public static final int TEXT_ALIGNMENT_VIEW_START = 5;
2025
2026    /**
2027     * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved
2028     * layoutDirection is LTR, and ALIGN_LEFT otherwise.
2029     *
2030     * Use with {@link #setTextAlignment(int)}
2031     */
2032    public static final int TEXT_ALIGNMENT_VIEW_END = 6;
2033
2034    /**
2035     * Default text alignment is inherited
2036     */
2037    private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2038
2039    /**
2040     * Default resolved text alignment
2041     * @hide
2042     */
2043    static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY;
2044
2045    /**
2046      * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED)
2047      * @hide
2048      */
2049    static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13;
2050
2051    /**
2052      * Mask for use with private flags indicating bits used for text alignment.
2053      * @hide
2054      */
2055    static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2056
2057    /**
2058     * Array of text direction flags for mapping attribute "textAlignment" to correct
2059     * flag value.
2060     * @hide
2061     */
2062    private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = {
2063            TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2064            TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2065            TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2066            TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2067            TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2068            TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT,
2069            TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT
2070    };
2071
2072    /**
2073     * Indicates whether the view text alignment has been resolved.
2074     * @hide
2075     */
2076    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
2077
2078    /**
2079     * Bit shift to get the resolved text alignment.
2080     * @hide
2081     */
2082    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17;
2083
2084    /**
2085     * Mask for use with private flags indicating bits used for text alignment.
2086     * @hide
2087     */
2088    static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007
2089            << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2090
2091    /**
2092     * Indicates whether if the view text alignment has been resolved to gravity
2093     */
2094    private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT =
2095            TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
2096
2097    // Accessiblity constants for mPrivateFlags2
2098
2099    /**
2100     * Shift for the bits in {@link #mPrivateFlags2} related to the
2101     * "importantForAccessibility" attribute.
2102     */
2103    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20;
2104
2105    /**
2106     * Automatically determine whether a view is important for accessibility.
2107     */
2108    public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000;
2109
2110    /**
2111     * The view is important for accessibility.
2112     */
2113    public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001;
2114
2115    /**
2116     * The view is not important for accessibility.
2117     */
2118    public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002;
2119
2120    /**
2121     * The default whether the view is important for accessibility.
2122     */
2123    static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO;
2124
2125    /**
2126     * Mask for obtainig the bits which specify how to determine
2127     * whether a view is important for accessibility.
2128     */
2129    static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO
2130        | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO)
2131        << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2132
2133    /**
2134     * Flag indicating whether a view has accessibility focus.
2135     */
2136    static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x00000040 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2137
2138    /**
2139     * Flag indicating whether a view state for accessibility has changed.
2140     */
2141    static final int PFLAG2_ACCESSIBILITY_STATE_CHANGED = 0x00000080
2142            << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
2143
2144    /**
2145     * Flag indicating whether a view failed the quickReject() check in draw(). This condition
2146     * is used to check whether later changes to the view's transform should invalidate the
2147     * view to force the quickReject test to run again.
2148     */
2149    static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000;
2150
2151    /**
2152     * Flag indicating that start/end padding has been resolved into left/right padding
2153     * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()}
2154     * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved
2155     * during measurement. In some special cases this is required such as when an adapter-based
2156     * view measures prospective children without attaching them to a window.
2157     */
2158    static final int PFLAG2_PADDING_RESOLVED = 0x20000000;
2159
2160    /**
2161     * Flag indicating that the start/end drawables has been resolved into left/right ones.
2162     */
2163    static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000;
2164
2165    /**
2166     * Group of bits indicating that RTL properties resolution is done.
2167     */
2168    static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED |
2169            PFLAG2_TEXT_DIRECTION_RESOLVED |
2170            PFLAG2_TEXT_ALIGNMENT_RESOLVED |
2171            PFLAG2_PADDING_RESOLVED |
2172            PFLAG2_DRAWABLE_RESOLVED;
2173
2174    // There are a couple of flags left in mPrivateFlags2
2175
2176    /* End of masks for mPrivateFlags2 */
2177
2178    /* Masks for mPrivateFlags3 */
2179
2180    /**
2181     * Flag indicating that view has a transform animation set on it. This is used to track whether
2182     * an animation is cleared between successive frames, in order to tell the associated
2183     * DisplayList to clear its animation matrix.
2184     */
2185    static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1;
2186
2187    /**
2188     * Flag indicating that view has an alpha animation set on it. This is used to track whether an
2189     * animation is cleared between successive frames, in order to tell the associated
2190     * DisplayList to restore its alpha value.
2191     */
2192    static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2;
2193
2194
2195    /* End of masks for mPrivateFlags3 */
2196
2197    static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED;
2198
2199    /**
2200     * Always allow a user to over-scroll this view, provided it is a
2201     * view that can scroll.
2202     *
2203     * @see #getOverScrollMode()
2204     * @see #setOverScrollMode(int)
2205     */
2206    public static final int OVER_SCROLL_ALWAYS = 0;
2207
2208    /**
2209     * Allow a user to over-scroll this view only if the content is large
2210     * enough to meaningfully scroll, provided it is a view that can scroll.
2211     *
2212     * @see #getOverScrollMode()
2213     * @see #setOverScrollMode(int)
2214     */
2215    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
2216
2217    /**
2218     * Never allow a user to over-scroll this view.
2219     *
2220     * @see #getOverScrollMode()
2221     * @see #setOverScrollMode(int)
2222     */
2223    public static final int OVER_SCROLL_NEVER = 2;
2224
2225    /**
2226     * Special constant for {@link #setSystemUiVisibility(int)}: View has
2227     * requested the system UI (status bar) to be visible (the default).
2228     *
2229     * @see #setSystemUiVisibility(int)
2230     */
2231    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
2232
2233    /**
2234     * Flag for {@link #setSystemUiVisibility(int)}: View has requested the
2235     * system UI to enter an unobtrusive "low profile" mode.
2236     *
2237     * <p>This is for use in games, book readers, video players, or any other
2238     * "immersive" application where the usual system chrome is deemed too distracting.
2239     *
2240     * <p>In low profile mode, the status bar and/or navigation icons may dim.
2241     *
2242     * @see #setSystemUiVisibility(int)
2243     */
2244    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
2245
2246    /**
2247     * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the
2248     * system navigation be temporarily hidden.
2249     *
2250     * <p>This is an even less obtrusive state than that called for by
2251     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
2252     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
2253     * those to disappear. This is useful (in conjunction with the
2254     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
2255     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
2256     * window flags) for displaying content using every last pixel on the display.
2257     *
2258     * <p>There is a limitation: because navigation controls are so important, the least user
2259     * interaction will cause them to reappear immediately.  When this happens, both
2260     * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically,
2261     * so that both elements reappear at the same time.
2262     *
2263     * @see #setSystemUiVisibility(int)
2264     */
2265    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
2266
2267    /**
2268     * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go
2269     * into the normal fullscreen mode so that its content can take over the screen
2270     * while still allowing the user to interact with the application.
2271     *
2272     * <p>This has the same visual effect as
2273     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN
2274     * WindowManager.LayoutParams.FLAG_FULLSCREEN},
2275     * meaning that non-critical screen decorations (such as the status bar) will be
2276     * hidden while the user is in the View's window, focusing the experience on
2277     * that content.  Unlike the window flag, if you are using ActionBar in
2278     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2279     * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also
2280     * hide the action bar.
2281     *
2282     * <p>This approach to going fullscreen is best used over the window flag when
2283     * it is a transient state -- that is, the application does this at certain
2284     * points in its user interaction where it wants to allow the user to focus
2285     * on content, but not as a continuous state.  For situations where the application
2286     * would like to simply stay full screen the entire time (such as a game that
2287     * wants to take over the screen), the
2288     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag}
2289     * is usually a better approach.  The state set here will be removed by the system
2290     * in various situations (such as the user moving to another application) like
2291     * the other system UI states.
2292     *
2293     * <p>When using this flag, the application should provide some easy facility
2294     * for the user to go out of it.  A common example would be in an e-book
2295     * reader, where tapping on the screen brings back whatever screen and UI
2296     * decorations that had been hidden while the user was immersed in reading
2297     * the book.
2298     *
2299     * @see #setSystemUiVisibility(int)
2300     */
2301    public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004;
2302
2303    /**
2304     * Flag for {@link #setSystemUiVisibility(int)}: When using other layout
2305     * flags, we would like a stable view of the content insets given to
2306     * {@link #fitSystemWindows(Rect)}.  This means that the insets seen there
2307     * will always represent the worst case that the application can expect
2308     * as a continuous state.  In the stock Android UI this is the space for
2309     * the system bar, nav bar, and status bar, but not more transient elements
2310     * such as an input method.
2311     *
2312     * The stable layout your UI sees is based on the system UI modes you can
2313     * switch to.  That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
2314     * then you will get a stable layout for changes of the
2315     * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify
2316     * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and
2317     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition
2318     * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}
2319     * with a stable layout.  (Note that you should avoid using
2320     * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.)
2321     *
2322     * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN}
2323     * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}),
2324     * then a hidden status bar will be considered a "stable" state for purposes
2325     * here.  This allows your UI to continually hide the status bar, while still
2326     * using the system UI flags to hide the action bar while still retaining
2327     * a stable layout.  Note that changing the window fullscreen flag will never
2328     * provide a stable layout for a clean transition.
2329     *
2330     * <p>If you are using ActionBar in
2331     * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY
2332     * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the
2333     * insets it adds to those given to the application.
2334     */
2335    public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100;
2336
2337    /**
2338     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2339     * to be layed out as if it has requested
2340     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't.  This
2341     * allows it to avoid artifacts when switching in and out of that mode, at
2342     * the expense that some of its user interface may be covered by screen
2343     * decorations when they are shown.  You can perform layout of your inner
2344     * UI elements to account for the navagation system UI through the
2345     * {@link #fitSystemWindows(Rect)} method.
2346     */
2347    public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200;
2348
2349    /**
2350     * Flag for {@link #setSystemUiVisibility(int)}: View would like its window
2351     * to be layed out as if it has requested
2352     * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't.  This
2353     * allows it to avoid artifacts when switching in and out of that mode, at
2354     * the expense that some of its user interface may be covered by screen
2355     * decorations when they are shown.  You can perform layout of your inner
2356     * UI elements to account for non-fullscreen system UI through the
2357     * {@link #fitSystemWindows(Rect)} method.
2358     */
2359    public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400;
2360
2361    /**
2362     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
2363     */
2364    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
2365
2366    /**
2367     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
2368     */
2369    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
2370
2371    /**
2372     * @hide
2373     *
2374     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2375     * out of the public fields to keep the undefined bits out of the developer's way.
2376     *
2377     * Flag to make the status bar not expandable.  Unless you also
2378     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
2379     */
2380    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
2381
2382    /**
2383     * @hide
2384     *
2385     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2386     * out of the public fields to keep the undefined bits out of the developer's way.
2387     *
2388     * Flag to hide notification icons and scrolling ticker text.
2389     */
2390    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
2391
2392    /**
2393     * @hide
2394     *
2395     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2396     * out of the public fields to keep the undefined bits out of the developer's way.
2397     *
2398     * Flag to disable incoming notification alerts.  This will not block
2399     * icons, but it will block sound, vibrating and other visual or aural notifications.
2400     */
2401    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
2402
2403    /**
2404     * @hide
2405     *
2406     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2407     * out of the public fields to keep the undefined bits out of the developer's way.
2408     *
2409     * Flag to hide only the scrolling ticker.  Note that
2410     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
2411     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
2412     */
2413    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
2414
2415    /**
2416     * @hide
2417     *
2418     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2419     * out of the public fields to keep the undefined bits out of the developer's way.
2420     *
2421     * Flag to hide the center system info area.
2422     */
2423    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
2424
2425    /**
2426     * @hide
2427     *
2428     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2429     * out of the public fields to keep the undefined bits out of the developer's way.
2430     *
2431     * Flag to hide only the home button.  Don't use this
2432     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2433     */
2434    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
2435
2436    /**
2437     * @hide
2438     *
2439     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2440     * out of the public fields to keep the undefined bits out of the developer's way.
2441     *
2442     * Flag to hide only the back button. Don't use this
2443     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2444     */
2445    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
2446
2447    /**
2448     * @hide
2449     *
2450     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2451     * out of the public fields to keep the undefined bits out of the developer's way.
2452     *
2453     * Flag to hide only the clock.  You might use this if your activity has
2454     * its own clock making the status bar's clock redundant.
2455     */
2456    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
2457
2458    /**
2459     * @hide
2460     *
2461     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2462     * out of the public fields to keep the undefined bits out of the developer's way.
2463     *
2464     * Flag to hide only the recent apps button. Don't use this
2465     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2466     */
2467    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
2468
2469    /**
2470     * @hide
2471     *
2472     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
2473     * out of the public fields to keep the undefined bits out of the developer's way.
2474     *
2475     * Flag to disable the global search gesture. Don't use this
2476     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
2477     */
2478    public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000;
2479
2480    /**
2481     * @hide
2482     */
2483    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
2484
2485    /**
2486     * These are the system UI flags that can be cleared by events outside
2487     * of an application.  Currently this is just the ability to tap on the
2488     * screen while hiding the navigation bar to have it return.
2489     * @hide
2490     */
2491    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
2492            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION
2493            | SYSTEM_UI_FLAG_FULLSCREEN;
2494
2495    /**
2496     * Flags that can impact the layout in relation to system UI.
2497     */
2498    public static final int SYSTEM_UI_LAYOUT_FLAGS =
2499            SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
2500            | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
2501
2502    /**
2503     * Find views that render the specified text.
2504     *
2505     * @see #findViewsWithText(ArrayList, CharSequence, int)
2506     */
2507    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
2508
2509    /**
2510     * Find find views that contain the specified content description.
2511     *
2512     * @see #findViewsWithText(ArrayList, CharSequence, int)
2513     */
2514    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
2515
2516    /**
2517     * Find views that contain {@link AccessibilityNodeProvider}. Such
2518     * a View is a root of virtual view hierarchy and may contain the searched
2519     * text. If this flag is set Views with providers are automatically
2520     * added and it is a responsibility of the client to call the APIs of
2521     * the provider to determine whether the virtual tree rooted at this View
2522     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
2523     * represeting the virtual views with this text.
2524     *
2525     * @see #findViewsWithText(ArrayList, CharSequence, int)
2526     *
2527     * @hide
2528     */
2529    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2530
2531    /**
2532     * The undefined cursor position.
2533     *
2534     * @hide
2535     */
2536    public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1;
2537
2538    /**
2539     * Indicates that the screen has changed state and is now off.
2540     *
2541     * @see #onScreenStateChanged(int)
2542     */
2543    public static final int SCREEN_STATE_OFF = 0x0;
2544
2545    /**
2546     * Indicates that the screen has changed state and is now on.
2547     *
2548     * @see #onScreenStateChanged(int)
2549     */
2550    public static final int SCREEN_STATE_ON = 0x1;
2551
2552    /**
2553     * Controls the over-scroll mode for this view.
2554     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2555     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2556     * and {@link #OVER_SCROLL_NEVER}.
2557     */
2558    private int mOverScrollMode;
2559
2560    /**
2561     * The parent this view is attached to.
2562     * {@hide}
2563     *
2564     * @see #getParent()
2565     */
2566    protected ViewParent mParent;
2567
2568    /**
2569     * {@hide}
2570     */
2571    AttachInfo mAttachInfo;
2572
2573    /**
2574     * {@hide}
2575     */
2576    @ViewDebug.ExportedProperty(flagMapping = {
2577        @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT,
2578                name = "FORCE_LAYOUT"),
2579        @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED,
2580                name = "LAYOUT_REQUIRED"),
2581        @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID,
2582            name = "DRAWING_CACHE_INVALID", outputIf = false),
2583        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true),
2584        @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false),
2585        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2586        @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY")
2587    })
2588    int mPrivateFlags;
2589    int mPrivateFlags2;
2590    int mPrivateFlags3;
2591
2592    /**
2593     * This view's request for the visibility of the status bar.
2594     * @hide
2595     */
2596    @ViewDebug.ExportedProperty(flagMapping = {
2597        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2598                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2599                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2600        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2601                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2602                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2603        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2604                                equals = SYSTEM_UI_FLAG_VISIBLE,
2605                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2606    })
2607    int mSystemUiVisibility;
2608
2609    /**
2610     * Reference count for transient state.
2611     * @see #setHasTransientState(boolean)
2612     */
2613    int mTransientStateCount = 0;
2614
2615    /**
2616     * Count of how many windows this view has been attached to.
2617     */
2618    int mWindowAttachCount;
2619
2620    /**
2621     * The layout parameters associated with this view and used by the parent
2622     * {@link android.view.ViewGroup} to determine how this view should be
2623     * laid out.
2624     * {@hide}
2625     */
2626    protected ViewGroup.LayoutParams mLayoutParams;
2627
2628    /**
2629     * The view flags hold various views states.
2630     * {@hide}
2631     */
2632    @ViewDebug.ExportedProperty
2633    int mViewFlags;
2634
2635    static class TransformationInfo {
2636        /**
2637         * The transform matrix for the View. This transform is calculated internally
2638         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2639         * is used by default. Do *not* use this variable directly; instead call
2640         * getMatrix(), which will automatically recalculate the matrix if necessary
2641         * to get the correct matrix based on the latest rotation and scale properties.
2642         */
2643        private final Matrix mMatrix = new Matrix();
2644
2645        /**
2646         * The transform matrix for the View. This transform is calculated internally
2647         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2648         * is used by default. Do *not* use this variable directly; instead call
2649         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2650         * to get the correct matrix based on the latest rotation and scale properties.
2651         */
2652        private Matrix mInverseMatrix;
2653
2654        /**
2655         * An internal variable that tracks whether we need to recalculate the
2656         * transform matrix, based on whether the rotation or scaleX/Y properties
2657         * have changed since the matrix was last calculated.
2658         */
2659        boolean mMatrixDirty = false;
2660
2661        /**
2662         * An internal variable that tracks whether we need to recalculate the
2663         * transform matrix, based on whether the rotation or scaleX/Y properties
2664         * have changed since the matrix was last calculated.
2665         */
2666        private boolean mInverseMatrixDirty = true;
2667
2668        /**
2669         * A variable that tracks whether we need to recalculate the
2670         * transform matrix, based on whether the rotation or scaleX/Y properties
2671         * have changed since the matrix was last calculated. This variable
2672         * is only valid after a call to updateMatrix() or to a function that
2673         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2674         */
2675        private boolean mMatrixIsIdentity = true;
2676
2677        /**
2678         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2679         */
2680        private Camera mCamera = null;
2681
2682        /**
2683         * This matrix is used when computing the matrix for 3D rotations.
2684         */
2685        private Matrix matrix3D = null;
2686
2687        /**
2688         * These prev values are used to recalculate a centered pivot point when necessary. The
2689         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2690         * set), so thes values are only used then as well.
2691         */
2692        private int mPrevWidth = -1;
2693        private int mPrevHeight = -1;
2694
2695        /**
2696         * The degrees rotation around the vertical axis through the pivot point.
2697         */
2698        @ViewDebug.ExportedProperty
2699        float mRotationY = 0f;
2700
2701        /**
2702         * The degrees rotation around the horizontal axis through the pivot point.
2703         */
2704        @ViewDebug.ExportedProperty
2705        float mRotationX = 0f;
2706
2707        /**
2708         * The degrees rotation around the pivot point.
2709         */
2710        @ViewDebug.ExportedProperty
2711        float mRotation = 0f;
2712
2713        /**
2714         * The amount of translation of the object away from its left property (post-layout).
2715         */
2716        @ViewDebug.ExportedProperty
2717        float mTranslationX = 0f;
2718
2719        /**
2720         * The amount of translation of the object away from its top property (post-layout).
2721         */
2722        @ViewDebug.ExportedProperty
2723        float mTranslationY = 0f;
2724
2725        /**
2726         * The amount of scale in the x direction around the pivot point. A
2727         * value of 1 means no scaling is applied.
2728         */
2729        @ViewDebug.ExportedProperty
2730        float mScaleX = 1f;
2731
2732        /**
2733         * The amount of scale in the y direction around the pivot point. A
2734         * value of 1 means no scaling is applied.
2735         */
2736        @ViewDebug.ExportedProperty
2737        float mScaleY = 1f;
2738
2739        /**
2740         * The x location of the point around which the view is rotated and scaled.
2741         */
2742        @ViewDebug.ExportedProperty
2743        float mPivotX = 0f;
2744
2745        /**
2746         * The y location of the point around which the view is rotated and scaled.
2747         */
2748        @ViewDebug.ExportedProperty
2749        float mPivotY = 0f;
2750
2751        /**
2752         * The opacity of the View. This is a value from 0 to 1, where 0 means
2753         * completely transparent and 1 means completely opaque.
2754         */
2755        @ViewDebug.ExportedProperty
2756        float mAlpha = 1f;
2757    }
2758
2759    TransformationInfo mTransformationInfo;
2760
2761    private boolean mLastIsOpaque;
2762
2763    /**
2764     * Convenience value to check for float values that are close enough to zero to be considered
2765     * zero.
2766     */
2767    private static final float NONZERO_EPSILON = .001f;
2768
2769    /**
2770     * The distance in pixels from the left edge of this view's parent
2771     * to the left edge of this view.
2772     * {@hide}
2773     */
2774    @ViewDebug.ExportedProperty(category = "layout")
2775    protected int mLeft;
2776    /**
2777     * The distance in pixels from the left edge of this view's parent
2778     * to the right edge of this view.
2779     * {@hide}
2780     */
2781    @ViewDebug.ExportedProperty(category = "layout")
2782    protected int mRight;
2783    /**
2784     * The distance in pixels from the top edge of this view's parent
2785     * to the top edge of this view.
2786     * {@hide}
2787     */
2788    @ViewDebug.ExportedProperty(category = "layout")
2789    protected int mTop;
2790    /**
2791     * The distance in pixels from the top edge of this view's parent
2792     * to the bottom edge of this view.
2793     * {@hide}
2794     */
2795    @ViewDebug.ExportedProperty(category = "layout")
2796    protected int mBottom;
2797
2798    /**
2799     * The offset, in pixels, by which the content of this view is scrolled
2800     * horizontally.
2801     * {@hide}
2802     */
2803    @ViewDebug.ExportedProperty(category = "scrolling")
2804    protected int mScrollX;
2805    /**
2806     * The offset, in pixels, by which the content of this view is scrolled
2807     * vertically.
2808     * {@hide}
2809     */
2810    @ViewDebug.ExportedProperty(category = "scrolling")
2811    protected int mScrollY;
2812
2813    /**
2814     * The left padding in pixels, that is the distance in pixels between the
2815     * left edge of this view and the left edge of its content.
2816     * {@hide}
2817     */
2818    @ViewDebug.ExportedProperty(category = "padding")
2819    protected int mPaddingLeft = 0;
2820    /**
2821     * The right padding in pixels, that is the distance in pixels between the
2822     * right edge of this view and the right edge of its content.
2823     * {@hide}
2824     */
2825    @ViewDebug.ExportedProperty(category = "padding")
2826    protected int mPaddingRight = 0;
2827    /**
2828     * The top padding in pixels, that is the distance in pixels between the
2829     * top edge of this view and the top edge of its content.
2830     * {@hide}
2831     */
2832    @ViewDebug.ExportedProperty(category = "padding")
2833    protected int mPaddingTop;
2834    /**
2835     * The bottom padding in pixels, that is the distance in pixels between the
2836     * bottom edge of this view and the bottom edge of its content.
2837     * {@hide}
2838     */
2839    @ViewDebug.ExportedProperty(category = "padding")
2840    protected int mPaddingBottom;
2841
2842    /**
2843     * The layout insets in pixels, that is the distance in pixels between the
2844     * visible edges of this view its bounds.
2845     */
2846    private Insets mLayoutInsets;
2847
2848    /**
2849     * Briefly describes the view and is primarily used for accessibility support.
2850     */
2851    private CharSequence mContentDescription;
2852
2853    /**
2854     * Specifies the id of a view for which this view serves as a label for
2855     * accessibility purposes.
2856     */
2857    private int mLabelForId = View.NO_ID;
2858
2859    /**
2860     * Predicate for matching labeled view id with its label for
2861     * accessibility purposes.
2862     */
2863    private MatchLabelForPredicate mMatchLabelForPredicate;
2864
2865    /**
2866     * Predicate for matching a view by its id.
2867     */
2868    private MatchIdPredicate mMatchIdPredicate;
2869
2870    /**
2871     * Cache the paddingRight set by the user to append to the scrollbar's size.
2872     *
2873     * @hide
2874     */
2875    @ViewDebug.ExportedProperty(category = "padding")
2876    protected int mUserPaddingRight;
2877
2878    /**
2879     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2880     *
2881     * @hide
2882     */
2883    @ViewDebug.ExportedProperty(category = "padding")
2884    protected int mUserPaddingBottom;
2885
2886    /**
2887     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2888     *
2889     * @hide
2890     */
2891    @ViewDebug.ExportedProperty(category = "padding")
2892    protected int mUserPaddingLeft;
2893
2894    /**
2895     * Cache the paddingStart set by the user to append to the scrollbar's size.
2896     *
2897     */
2898    @ViewDebug.ExportedProperty(category = "padding")
2899    int mUserPaddingStart;
2900
2901    /**
2902     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2903     *
2904     */
2905    @ViewDebug.ExportedProperty(category = "padding")
2906    int mUserPaddingEnd;
2907
2908    /**
2909     * Cache initial left padding.
2910     *
2911     * @hide
2912     */
2913    int mUserPaddingLeftInitial = 0;
2914
2915    /**
2916     * Cache initial right padding.
2917     *
2918     * @hide
2919     */
2920    int mUserPaddingRightInitial = 0;
2921
2922    /**
2923     * Default undefined padding
2924     */
2925    private static final int UNDEFINED_PADDING = Integer.MIN_VALUE;
2926
2927    /**
2928     * @hide
2929     */
2930    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2931    /**
2932     * @hide
2933     */
2934    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2935
2936    @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_")
2937    private Drawable mBackground;
2938
2939    private int mBackgroundResource;
2940    private boolean mBackgroundSizeChanged;
2941
2942    static class ListenerInfo {
2943        /**
2944         * Listener used to dispatch focus change events.
2945         * This field should be made private, so it is hidden from the SDK.
2946         * {@hide}
2947         */
2948        protected OnFocusChangeListener mOnFocusChangeListener;
2949
2950        /**
2951         * Listeners for layout change events.
2952         */
2953        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2954
2955        /**
2956         * Listeners for attach events.
2957         */
2958        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2959
2960        /**
2961         * Listener used to dispatch click events.
2962         * This field should be made private, so it is hidden from the SDK.
2963         * {@hide}
2964         */
2965        public OnClickListener mOnClickListener;
2966
2967        /**
2968         * Listener used to dispatch long click events.
2969         * This field should be made private, so it is hidden from the SDK.
2970         * {@hide}
2971         */
2972        protected OnLongClickListener mOnLongClickListener;
2973
2974        /**
2975         * Listener used to build the context menu.
2976         * This field should be made private, so it is hidden from the SDK.
2977         * {@hide}
2978         */
2979        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2980
2981        private OnKeyListener mOnKeyListener;
2982
2983        private OnTouchListener mOnTouchListener;
2984
2985        private OnHoverListener mOnHoverListener;
2986
2987        private OnGenericMotionListener mOnGenericMotionListener;
2988
2989        private OnDragListener mOnDragListener;
2990
2991        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2992    }
2993
2994    ListenerInfo mListenerInfo;
2995
2996    /**
2997     * The application environment this view lives in.
2998     * This field should be made private, so it is hidden from the SDK.
2999     * {@hide}
3000     */
3001    protected Context mContext;
3002
3003    private final Resources mResources;
3004
3005    private ScrollabilityCache mScrollCache;
3006
3007    private int[] mDrawableState = null;
3008
3009    /**
3010     * Set to true when drawing cache is enabled and cannot be created.
3011     *
3012     * @hide
3013     */
3014    public boolean mCachingFailed;
3015
3016    private Bitmap mDrawingCache;
3017    private Bitmap mUnscaledDrawingCache;
3018    private HardwareLayer mHardwareLayer;
3019    DisplayList mDisplayList;
3020
3021    /**
3022     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
3023     * the user may specify which view to go to next.
3024     */
3025    private int mNextFocusLeftId = View.NO_ID;
3026
3027    /**
3028     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
3029     * the user may specify which view to go to next.
3030     */
3031    private int mNextFocusRightId = View.NO_ID;
3032
3033    /**
3034     * When this view has focus and the next focus is {@link #FOCUS_UP},
3035     * the user may specify which view to go to next.
3036     */
3037    private int mNextFocusUpId = View.NO_ID;
3038
3039    /**
3040     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
3041     * the user may specify which view to go to next.
3042     */
3043    private int mNextFocusDownId = View.NO_ID;
3044
3045    /**
3046     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
3047     * the user may specify which view to go to next.
3048     */
3049    int mNextFocusForwardId = View.NO_ID;
3050
3051    private CheckForLongPress mPendingCheckForLongPress;
3052    private CheckForTap mPendingCheckForTap = null;
3053    private PerformClick mPerformClick;
3054    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
3055
3056    private UnsetPressedState mUnsetPressedState;
3057
3058    /**
3059     * Whether the long press's action has been invoked.  The tap's action is invoked on the
3060     * up event while a long press is invoked as soon as the long press duration is reached, so
3061     * a long press could be performed before the tap is checked, in which case the tap's action
3062     * should not be invoked.
3063     */
3064    private boolean mHasPerformedLongPress;
3065
3066    /**
3067     * The minimum height of the view. We'll try our best to have the height
3068     * of this view to at least this amount.
3069     */
3070    @ViewDebug.ExportedProperty(category = "measurement")
3071    private int mMinHeight;
3072
3073    /**
3074     * The minimum width of the view. We'll try our best to have the width
3075     * of this view to at least this amount.
3076     */
3077    @ViewDebug.ExportedProperty(category = "measurement")
3078    private int mMinWidth;
3079
3080    /**
3081     * The delegate to handle touch events that are physically in this view
3082     * but should be handled by another view.
3083     */
3084    private TouchDelegate mTouchDelegate = null;
3085
3086    /**
3087     * Solid color to use as a background when creating the drawing cache. Enables
3088     * the cache to use 16 bit bitmaps instead of 32 bit.
3089     */
3090    private int mDrawingCacheBackgroundColor = 0;
3091
3092    /**
3093     * Special tree observer used when mAttachInfo is null.
3094     */
3095    private ViewTreeObserver mFloatingTreeObserver;
3096
3097    /**
3098     * Cache the touch slop from the context that created the view.
3099     */
3100    private int mTouchSlop;
3101
3102    /**
3103     * Object that handles automatic animation of view properties.
3104     */
3105    private ViewPropertyAnimator mAnimator = null;
3106
3107    /**
3108     * Flag indicating that a drag can cross window boundaries.  When
3109     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
3110     * with this flag set, all visible applications will be able to participate
3111     * in the drag operation and receive the dragged content.
3112     *
3113     * @hide
3114     */
3115    public static final int DRAG_FLAG_GLOBAL = 1;
3116
3117    /**
3118     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
3119     */
3120    private float mVerticalScrollFactor;
3121
3122    /**
3123     * Position of the vertical scroll bar.
3124     */
3125    private int mVerticalScrollbarPosition;
3126
3127    /**
3128     * Position the scroll bar at the default position as determined by the system.
3129     */
3130    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
3131
3132    /**
3133     * Position the scroll bar along the left edge.
3134     */
3135    public static final int SCROLLBAR_POSITION_LEFT = 1;
3136
3137    /**
3138     * Position the scroll bar along the right edge.
3139     */
3140    public static final int SCROLLBAR_POSITION_RIGHT = 2;
3141
3142    /**
3143     * Indicates that the view does not have a layer.
3144     *
3145     * @see #getLayerType()
3146     * @see #setLayerType(int, android.graphics.Paint)
3147     * @see #LAYER_TYPE_SOFTWARE
3148     * @see #LAYER_TYPE_HARDWARE
3149     */
3150    public static final int LAYER_TYPE_NONE = 0;
3151
3152    /**
3153     * <p>Indicates that the view has a software layer. A software layer is backed
3154     * by a bitmap and causes the view to be rendered using Android's software
3155     * rendering pipeline, even if hardware acceleration is enabled.</p>
3156     *
3157     * <p>Software layers have various usages:</p>
3158     * <p>When the application is not using hardware acceleration, a software layer
3159     * is useful to apply a specific color filter and/or blending mode and/or
3160     * translucency to a view and all its children.</p>
3161     * <p>When the application is using hardware acceleration, a software layer
3162     * is useful to render drawing primitives not supported by the hardware
3163     * accelerated pipeline. It can also be used to cache a complex view tree
3164     * into a texture and reduce the complexity of drawing operations. For instance,
3165     * when animating a complex view tree with a translation, a software layer can
3166     * be used to render the view tree only once.</p>
3167     * <p>Software layers should be avoided when the affected view tree updates
3168     * often. Every update will require to re-render the software layer, which can
3169     * potentially be slow (particularly when hardware acceleration is turned on
3170     * since the layer will have to be uploaded into a hardware texture after every
3171     * update.)</p>
3172     *
3173     * @see #getLayerType()
3174     * @see #setLayerType(int, android.graphics.Paint)
3175     * @see #LAYER_TYPE_NONE
3176     * @see #LAYER_TYPE_HARDWARE
3177     */
3178    public static final int LAYER_TYPE_SOFTWARE = 1;
3179
3180    /**
3181     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
3182     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
3183     * OpenGL hardware) and causes the view to be rendered using Android's hardware
3184     * rendering pipeline, but only if hardware acceleration is turned on for the
3185     * view hierarchy. When hardware acceleration is turned off, hardware layers
3186     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
3187     *
3188     * <p>A hardware layer is useful to apply a specific color filter and/or
3189     * blending mode and/or translucency to a view and all its children.</p>
3190     * <p>A hardware layer can be used to cache a complex view tree into a
3191     * texture and reduce the complexity of drawing operations. For instance,
3192     * when animating a complex view tree with a translation, a hardware layer can
3193     * be used to render the view tree only once.</p>
3194     * <p>A hardware layer can also be used to increase the rendering quality when
3195     * rotation transformations are applied on a view. It can also be used to
3196     * prevent potential clipping issues when applying 3D transforms on a view.</p>
3197     *
3198     * @see #getLayerType()
3199     * @see #setLayerType(int, android.graphics.Paint)
3200     * @see #LAYER_TYPE_NONE
3201     * @see #LAYER_TYPE_SOFTWARE
3202     */
3203    public static final int LAYER_TYPE_HARDWARE = 2;
3204
3205    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3206            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
3207            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
3208            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
3209    })
3210    int mLayerType = LAYER_TYPE_NONE;
3211    Paint mLayerPaint;
3212    Rect mLocalDirtyRect;
3213
3214    /**
3215     * Set to true when the view is sending hover accessibility events because it
3216     * is the innermost hovered view.
3217     */
3218    private boolean mSendingHoverAccessibilityEvents;
3219
3220    /**
3221     * Delegate for injecting accessibility functionality.
3222     */
3223    AccessibilityDelegate mAccessibilityDelegate;
3224
3225    /**
3226     * Consistency verifier for debugging purposes.
3227     * @hide
3228     */
3229    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
3230            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
3231                    new InputEventConsistencyVerifier(this, 0) : null;
3232
3233    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
3234
3235    /**
3236     * Simple constructor to use when creating a view from code.
3237     *
3238     * @param context The Context the view is running in, through which it can
3239     *        access the current theme, resources, etc.
3240     */
3241    public View(Context context) {
3242        mContext = context;
3243        mResources = context != null ? context.getResources() : null;
3244        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
3245        // Set some flags defaults
3246        mPrivateFlags2 =
3247                (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) |
3248                (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) |
3249                (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) |
3250                (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) |
3251                (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) |
3252                (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT);
3253        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
3254        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
3255        mUserPaddingStart = UNDEFINED_PADDING;
3256        mUserPaddingEnd = UNDEFINED_PADDING;
3257
3258        if (!sUseBrokenMakeMeasureSpec && context.getApplicationInfo().targetSdkVersion <=
3259                Build.VERSION_CODES.JELLY_BEAN_MR1 ) {
3260            // Older apps may need this compatibility hack for measurement.
3261            sUseBrokenMakeMeasureSpec = true;
3262        }
3263    }
3264
3265    /**
3266     * Constructor that is called when inflating a view from XML. This is called
3267     * when a view is being constructed from an XML file, supplying attributes
3268     * that were specified in the XML file. This version uses a default style of
3269     * 0, so the only attribute values applied are those in the Context's Theme
3270     * and the given AttributeSet.
3271     *
3272     * <p>
3273     * The method onFinishInflate() will be called after all children have been
3274     * added.
3275     *
3276     * @param context The Context the view is running in, through which it can
3277     *        access the current theme, resources, etc.
3278     * @param attrs The attributes of the XML tag that is inflating the view.
3279     * @see #View(Context, AttributeSet, int)
3280     */
3281    public View(Context context, AttributeSet attrs) {
3282        this(context, attrs, 0);
3283    }
3284
3285    /**
3286     * Perform inflation from XML and apply a class-specific base style. This
3287     * constructor of View allows subclasses to use their own base style when
3288     * they are inflating. For example, a Button class's constructor would call
3289     * this version of the super class constructor and supply
3290     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
3291     * the theme's button style to modify all of the base view attributes (in
3292     * particular its background) as well as the Button class's attributes.
3293     *
3294     * @param context The Context the view is running in, through which it can
3295     *        access the current theme, resources, etc.
3296     * @param attrs The attributes of the XML tag that is inflating the view.
3297     * @param defStyle The default style to apply to this view. If 0, no style
3298     *        will be applied (beyond what is included in the theme). This may
3299     *        either be an attribute resource, whose value will be retrieved
3300     *        from the current theme, or an explicit style resource.
3301     * @see #View(Context, AttributeSet)
3302     */
3303    public View(Context context, AttributeSet attrs, int defStyle) {
3304        this(context);
3305
3306        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
3307                defStyle, 0);
3308
3309        Drawable background = null;
3310
3311        int leftPadding = -1;
3312        int topPadding = -1;
3313        int rightPadding = -1;
3314        int bottomPadding = -1;
3315        int startPadding = UNDEFINED_PADDING;
3316        int endPadding = UNDEFINED_PADDING;
3317
3318        int padding = -1;
3319
3320        int viewFlagValues = 0;
3321        int viewFlagMasks = 0;
3322
3323        boolean setScrollContainer = false;
3324
3325        int x = 0;
3326        int y = 0;
3327
3328        float tx = 0;
3329        float ty = 0;
3330        float rotation = 0;
3331        float rotationX = 0;
3332        float rotationY = 0;
3333        float sx = 1f;
3334        float sy = 1f;
3335        boolean transformSet = false;
3336
3337        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
3338        int overScrollMode = mOverScrollMode;
3339        boolean initializeScrollbars = false;
3340
3341        boolean leftPaddingDefined = false;
3342        boolean rightPaddingDefined = false;
3343        boolean startPaddingDefined = false;
3344        boolean endPaddingDefined = false;
3345
3346        final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
3347
3348        final int N = a.getIndexCount();
3349        for (int i = 0; i < N; i++) {
3350            int attr = a.getIndex(i);
3351            switch (attr) {
3352                case com.android.internal.R.styleable.View_background:
3353                    background = a.getDrawable(attr);
3354                    break;
3355                case com.android.internal.R.styleable.View_padding:
3356                    padding = a.getDimensionPixelSize(attr, -1);
3357                    mUserPaddingLeftInitial = padding;
3358                    mUserPaddingRightInitial = padding;
3359                    leftPaddingDefined = true;
3360                    rightPaddingDefined = true;
3361                    break;
3362                 case com.android.internal.R.styleable.View_paddingLeft:
3363                    leftPadding = a.getDimensionPixelSize(attr, -1);
3364                    mUserPaddingLeftInitial = leftPadding;
3365                    leftPaddingDefined = true;
3366                    break;
3367                case com.android.internal.R.styleable.View_paddingTop:
3368                    topPadding = a.getDimensionPixelSize(attr, -1);
3369                    break;
3370                case com.android.internal.R.styleable.View_paddingRight:
3371                    rightPadding = a.getDimensionPixelSize(attr, -1);
3372                    mUserPaddingRightInitial = rightPadding;
3373                    rightPaddingDefined = true;
3374                    break;
3375                case com.android.internal.R.styleable.View_paddingBottom:
3376                    bottomPadding = a.getDimensionPixelSize(attr, -1);
3377                    break;
3378                case com.android.internal.R.styleable.View_paddingStart:
3379                    startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3380                    startPaddingDefined = true;
3381                    break;
3382                case com.android.internal.R.styleable.View_paddingEnd:
3383                    endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
3384                    endPaddingDefined = true;
3385                    break;
3386                case com.android.internal.R.styleable.View_scrollX:
3387                    x = a.getDimensionPixelOffset(attr, 0);
3388                    break;
3389                case com.android.internal.R.styleable.View_scrollY:
3390                    y = a.getDimensionPixelOffset(attr, 0);
3391                    break;
3392                case com.android.internal.R.styleable.View_alpha:
3393                    setAlpha(a.getFloat(attr, 1f));
3394                    break;
3395                case com.android.internal.R.styleable.View_transformPivotX:
3396                    setPivotX(a.getDimensionPixelOffset(attr, 0));
3397                    break;
3398                case com.android.internal.R.styleable.View_transformPivotY:
3399                    setPivotY(a.getDimensionPixelOffset(attr, 0));
3400                    break;
3401                case com.android.internal.R.styleable.View_translationX:
3402                    tx = a.getDimensionPixelOffset(attr, 0);
3403                    transformSet = true;
3404                    break;
3405                case com.android.internal.R.styleable.View_translationY:
3406                    ty = a.getDimensionPixelOffset(attr, 0);
3407                    transformSet = true;
3408                    break;
3409                case com.android.internal.R.styleable.View_rotation:
3410                    rotation = a.getFloat(attr, 0);
3411                    transformSet = true;
3412                    break;
3413                case com.android.internal.R.styleable.View_rotationX:
3414                    rotationX = a.getFloat(attr, 0);
3415                    transformSet = true;
3416                    break;
3417                case com.android.internal.R.styleable.View_rotationY:
3418                    rotationY = a.getFloat(attr, 0);
3419                    transformSet = true;
3420                    break;
3421                case com.android.internal.R.styleable.View_scaleX:
3422                    sx = a.getFloat(attr, 1f);
3423                    transformSet = true;
3424                    break;
3425                case com.android.internal.R.styleable.View_scaleY:
3426                    sy = a.getFloat(attr, 1f);
3427                    transformSet = true;
3428                    break;
3429                case com.android.internal.R.styleable.View_id:
3430                    mID = a.getResourceId(attr, NO_ID);
3431                    break;
3432                case com.android.internal.R.styleable.View_tag:
3433                    mTag = a.getText(attr);
3434                    break;
3435                case com.android.internal.R.styleable.View_fitsSystemWindows:
3436                    if (a.getBoolean(attr, false)) {
3437                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
3438                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
3439                    }
3440                    break;
3441                case com.android.internal.R.styleable.View_focusable:
3442                    if (a.getBoolean(attr, false)) {
3443                        viewFlagValues |= FOCUSABLE;
3444                        viewFlagMasks |= FOCUSABLE_MASK;
3445                    }
3446                    break;
3447                case com.android.internal.R.styleable.View_focusableInTouchMode:
3448                    if (a.getBoolean(attr, false)) {
3449                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
3450                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
3451                    }
3452                    break;
3453                case com.android.internal.R.styleable.View_clickable:
3454                    if (a.getBoolean(attr, false)) {
3455                        viewFlagValues |= CLICKABLE;
3456                        viewFlagMasks |= CLICKABLE;
3457                    }
3458                    break;
3459                case com.android.internal.R.styleable.View_longClickable:
3460                    if (a.getBoolean(attr, false)) {
3461                        viewFlagValues |= LONG_CLICKABLE;
3462                        viewFlagMasks |= LONG_CLICKABLE;
3463                    }
3464                    break;
3465                case com.android.internal.R.styleable.View_saveEnabled:
3466                    if (!a.getBoolean(attr, true)) {
3467                        viewFlagValues |= SAVE_DISABLED;
3468                        viewFlagMasks |= SAVE_DISABLED_MASK;
3469                    }
3470                    break;
3471                case com.android.internal.R.styleable.View_duplicateParentState:
3472                    if (a.getBoolean(attr, false)) {
3473                        viewFlagValues |= DUPLICATE_PARENT_STATE;
3474                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
3475                    }
3476                    break;
3477                case com.android.internal.R.styleable.View_visibility:
3478                    final int visibility = a.getInt(attr, 0);
3479                    if (visibility != 0) {
3480                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
3481                        viewFlagMasks |= VISIBILITY_MASK;
3482                    }
3483                    break;
3484                case com.android.internal.R.styleable.View_layoutDirection:
3485                    // Clear any layout direction flags (included resolved bits) already set
3486                    mPrivateFlags2 &=
3487                            ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
3488                    // Set the layout direction flags depending on the value of the attribute
3489                    final int layoutDirection = a.getInt(attr, -1);
3490                    final int value = (layoutDirection != -1) ?
3491                            LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
3492                    mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
3493                    break;
3494                case com.android.internal.R.styleable.View_drawingCacheQuality:
3495                    final int cacheQuality = a.getInt(attr, 0);
3496                    if (cacheQuality != 0) {
3497                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
3498                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
3499                    }
3500                    break;
3501                case com.android.internal.R.styleable.View_contentDescription:
3502                    setContentDescription(a.getString(attr));
3503                    break;
3504                case com.android.internal.R.styleable.View_labelFor:
3505                    setLabelFor(a.getResourceId(attr, NO_ID));
3506                    break;
3507                case com.android.internal.R.styleable.View_soundEffectsEnabled:
3508                    if (!a.getBoolean(attr, true)) {
3509                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
3510                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
3511                    }
3512                    break;
3513                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
3514                    if (!a.getBoolean(attr, true)) {
3515                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
3516                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
3517                    }
3518                    break;
3519                case R.styleable.View_scrollbars:
3520                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
3521                    if (scrollbars != SCROLLBARS_NONE) {
3522                        viewFlagValues |= scrollbars;
3523                        viewFlagMasks |= SCROLLBARS_MASK;
3524                        initializeScrollbars = true;
3525                    }
3526                    break;
3527                //noinspection deprecation
3528                case R.styleable.View_fadingEdge:
3529                    if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
3530                        // Ignore the attribute starting with ICS
3531                        break;
3532                    }
3533                    // With builds < ICS, fall through and apply fading edges
3534                case R.styleable.View_requiresFadingEdge:
3535                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3536                    if (fadingEdge != FADING_EDGE_NONE) {
3537                        viewFlagValues |= fadingEdge;
3538                        viewFlagMasks |= FADING_EDGE_MASK;
3539                        initializeFadingEdge(a);
3540                    }
3541                    break;
3542                case R.styleable.View_scrollbarStyle:
3543                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3544                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3545                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3546                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3547                    }
3548                    break;
3549                case R.styleable.View_isScrollContainer:
3550                    setScrollContainer = true;
3551                    if (a.getBoolean(attr, false)) {
3552                        setScrollContainer(true);
3553                    }
3554                    break;
3555                case com.android.internal.R.styleable.View_keepScreenOn:
3556                    if (a.getBoolean(attr, false)) {
3557                        viewFlagValues |= KEEP_SCREEN_ON;
3558                        viewFlagMasks |= KEEP_SCREEN_ON;
3559                    }
3560                    break;
3561                case R.styleable.View_filterTouchesWhenObscured:
3562                    if (a.getBoolean(attr, false)) {
3563                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3564                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3565                    }
3566                    break;
3567                case R.styleable.View_nextFocusLeft:
3568                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3569                    break;
3570                case R.styleable.View_nextFocusRight:
3571                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3572                    break;
3573                case R.styleable.View_nextFocusUp:
3574                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3575                    break;
3576                case R.styleable.View_nextFocusDown:
3577                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3578                    break;
3579                case R.styleable.View_nextFocusForward:
3580                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3581                    break;
3582                case R.styleable.View_minWidth:
3583                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3584                    break;
3585                case R.styleable.View_minHeight:
3586                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3587                    break;
3588                case R.styleable.View_onClick:
3589                    if (context.isRestricted()) {
3590                        throw new IllegalStateException("The android:onClick attribute cannot "
3591                                + "be used within a restricted context");
3592                    }
3593
3594                    final String handlerName = a.getString(attr);
3595                    if (handlerName != null) {
3596                        setOnClickListener(new OnClickListener() {
3597                            private Method mHandler;
3598
3599                            public void onClick(View v) {
3600                                if (mHandler == null) {
3601                                    try {
3602                                        mHandler = getContext().getClass().getMethod(handlerName,
3603                                                View.class);
3604                                    } catch (NoSuchMethodException e) {
3605                                        int id = getId();
3606                                        String idText = id == NO_ID ? "" : " with id '"
3607                                                + getContext().getResources().getResourceEntryName(
3608                                                    id) + "'";
3609                                        throw new IllegalStateException("Could not find a method " +
3610                                                handlerName + "(View) in the activity "
3611                                                + getContext().getClass() + " for onClick handler"
3612                                                + " on view " + View.this.getClass() + idText, e);
3613                                    }
3614                                }
3615
3616                                try {
3617                                    mHandler.invoke(getContext(), View.this);
3618                                } catch (IllegalAccessException e) {
3619                                    throw new IllegalStateException("Could not execute non "
3620                                            + "public method of the activity", e);
3621                                } catch (InvocationTargetException e) {
3622                                    throw new IllegalStateException("Could not execute "
3623                                            + "method of the activity", e);
3624                                }
3625                            }
3626                        });
3627                    }
3628                    break;
3629                case R.styleable.View_overScrollMode:
3630                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3631                    break;
3632                case R.styleable.View_verticalScrollbarPosition:
3633                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3634                    break;
3635                case R.styleable.View_layerType:
3636                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3637                    break;
3638                case R.styleable.View_textDirection:
3639                    // Clear any text direction flag already set
3640                    mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
3641                    // Set the text direction flags depending on the value of the attribute
3642                    final int textDirection = a.getInt(attr, -1);
3643                    if (textDirection != -1) {
3644                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
3645                    }
3646                    break;
3647                case R.styleable.View_textAlignment:
3648                    // Clear any text alignment flag already set
3649                    mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
3650                    // Set the text alignment flag depending on the value of the attribute
3651                    final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
3652                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
3653                    break;
3654                case R.styleable.View_importantForAccessibility:
3655                    setImportantForAccessibility(a.getInt(attr,
3656                            IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
3657                    break;
3658            }
3659        }
3660
3661        setOverScrollMode(overScrollMode);
3662
3663        // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
3664        // the resolved layout direction). Those cached values will be used later during padding
3665        // resolution.
3666        mUserPaddingStart = startPadding;
3667        mUserPaddingEnd = endPadding;
3668
3669        if (background != null) {
3670            setBackground(background);
3671        }
3672
3673        if (padding >= 0) {
3674            leftPadding = padding;
3675            topPadding = padding;
3676            rightPadding = padding;
3677            bottomPadding = padding;
3678            mUserPaddingLeftInitial = padding;
3679            mUserPaddingRightInitial = padding;
3680        }
3681
3682        if (isRtlCompatibilityMode()) {
3683            // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
3684            // left / right padding are used if defined (meaning here nothing to do). If they are not
3685            // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
3686            // start / end and resolve them as left / right (layout direction is not taken into account).
3687            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3688            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3689            // defined.
3690            if (!leftPaddingDefined && startPaddingDefined) {
3691                leftPadding = startPadding;
3692            }
3693            mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
3694            if (!rightPaddingDefined && endPaddingDefined) {
3695                rightPadding = endPadding;
3696            }
3697            mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
3698        } else {
3699            // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
3700            // values defined. Otherwise, left /right values are used.
3701            // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
3702            // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
3703            // defined.
3704            if (leftPaddingDefined) {
3705                mUserPaddingLeftInitial = leftPadding;
3706            }
3707            if (rightPaddingDefined) {
3708                mUserPaddingRightInitial = rightPadding;
3709            }
3710        }
3711
3712        internalSetPadding(
3713                mUserPaddingLeftInitial,
3714                topPadding >= 0 ? topPadding : mPaddingTop,
3715                mUserPaddingRightInitial,
3716                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3717
3718        if (viewFlagMasks != 0) {
3719            setFlags(viewFlagValues, viewFlagMasks);
3720        }
3721
3722        if (initializeScrollbars) {
3723            initializeScrollbars(a);
3724        }
3725
3726        a.recycle();
3727
3728        // Needs to be called after mViewFlags is set
3729        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3730            recomputePadding();
3731        }
3732
3733        if (x != 0 || y != 0) {
3734            scrollTo(x, y);
3735        }
3736
3737        if (transformSet) {
3738            setTranslationX(tx);
3739            setTranslationY(ty);
3740            setRotation(rotation);
3741            setRotationX(rotationX);
3742            setRotationY(rotationY);
3743            setScaleX(sx);
3744            setScaleY(sy);
3745        }
3746
3747        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3748            setScrollContainer(true);
3749        }
3750
3751        computeOpaqueFlags();
3752    }
3753
3754    /**
3755     * Non-public constructor for use in testing
3756     */
3757    View() {
3758        mResources = null;
3759    }
3760
3761    public String toString() {
3762        StringBuilder out = new StringBuilder(128);
3763        out.append(getClass().getName());
3764        out.append('{');
3765        out.append(Integer.toHexString(System.identityHashCode(this)));
3766        out.append(' ');
3767        switch (mViewFlags&VISIBILITY_MASK) {
3768            case VISIBLE: out.append('V'); break;
3769            case INVISIBLE: out.append('I'); break;
3770            case GONE: out.append('G'); break;
3771            default: out.append('.'); break;
3772        }
3773        out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.');
3774        out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.');
3775        out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D');
3776        out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.');
3777        out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
3778        out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
3779        out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
3780        out.append(' ');
3781        out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
3782        out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
3783        out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.');
3784        if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) {
3785            out.append('p');
3786        } else {
3787            out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.');
3788        }
3789        out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.');
3790        out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.');
3791        out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.');
3792        out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.');
3793        out.append(' ');
3794        out.append(mLeft);
3795        out.append(',');
3796        out.append(mTop);
3797        out.append('-');
3798        out.append(mRight);
3799        out.append(',');
3800        out.append(mBottom);
3801        final int id = getId();
3802        if (id != NO_ID) {
3803            out.append(" #");
3804            out.append(Integer.toHexString(id));
3805            final Resources r = mResources;
3806            if (id != 0 && r != null) {
3807                try {
3808                    String pkgname;
3809                    switch (id&0xff000000) {
3810                        case 0x7f000000:
3811                            pkgname="app";
3812                            break;
3813                        case 0x01000000:
3814                            pkgname="android";
3815                            break;
3816                        default:
3817                            pkgname = r.getResourcePackageName(id);
3818                            break;
3819                    }
3820                    String typename = r.getResourceTypeName(id);
3821                    String entryname = r.getResourceEntryName(id);
3822                    out.append(" ");
3823                    out.append(pkgname);
3824                    out.append(":");
3825                    out.append(typename);
3826                    out.append("/");
3827                    out.append(entryname);
3828                } catch (Resources.NotFoundException e) {
3829                }
3830            }
3831        }
3832        out.append("}");
3833        return out.toString();
3834    }
3835
3836    /**
3837     * <p>
3838     * Initializes the fading edges from a given set of styled attributes. This
3839     * method should be called by subclasses that need fading edges and when an
3840     * instance of these subclasses is created programmatically rather than
3841     * being inflated from XML. This method is automatically called when the XML
3842     * is inflated.
3843     * </p>
3844     *
3845     * @param a the styled attributes set to initialize the fading edges from
3846     */
3847    protected void initializeFadingEdge(TypedArray a) {
3848        initScrollCache();
3849
3850        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3851                R.styleable.View_fadingEdgeLength,
3852                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3853    }
3854
3855    /**
3856     * Returns the size of the vertical faded edges used to indicate that more
3857     * content in this view is visible.
3858     *
3859     * @return The size in pixels of the vertical faded edge or 0 if vertical
3860     *         faded edges are not enabled for this view.
3861     * @attr ref android.R.styleable#View_fadingEdgeLength
3862     */
3863    public int getVerticalFadingEdgeLength() {
3864        if (isVerticalFadingEdgeEnabled()) {
3865            ScrollabilityCache cache = mScrollCache;
3866            if (cache != null) {
3867                return cache.fadingEdgeLength;
3868            }
3869        }
3870        return 0;
3871    }
3872
3873    /**
3874     * Set the size of the faded edge used to indicate that more content in this
3875     * view is available.  Will not change whether the fading edge is enabled; use
3876     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3877     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3878     * for the vertical or horizontal fading edges.
3879     *
3880     * @param length The size in pixels of the faded edge used to indicate that more
3881     *        content in this view is visible.
3882     */
3883    public void setFadingEdgeLength(int length) {
3884        initScrollCache();
3885        mScrollCache.fadingEdgeLength = length;
3886    }
3887
3888    /**
3889     * Returns the size of the horizontal faded edges used to indicate that more
3890     * content in this view is visible.
3891     *
3892     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3893     *         faded edges are not enabled for this view.
3894     * @attr ref android.R.styleable#View_fadingEdgeLength
3895     */
3896    public int getHorizontalFadingEdgeLength() {
3897        if (isHorizontalFadingEdgeEnabled()) {
3898            ScrollabilityCache cache = mScrollCache;
3899            if (cache != null) {
3900                return cache.fadingEdgeLength;
3901            }
3902        }
3903        return 0;
3904    }
3905
3906    /**
3907     * Returns the width of the vertical scrollbar.
3908     *
3909     * @return The width in pixels of the vertical scrollbar or 0 if there
3910     *         is no vertical scrollbar.
3911     */
3912    public int getVerticalScrollbarWidth() {
3913        ScrollabilityCache cache = mScrollCache;
3914        if (cache != null) {
3915            ScrollBarDrawable scrollBar = cache.scrollBar;
3916            if (scrollBar != null) {
3917                int size = scrollBar.getSize(true);
3918                if (size <= 0) {
3919                    size = cache.scrollBarSize;
3920                }
3921                return size;
3922            }
3923            return 0;
3924        }
3925        return 0;
3926    }
3927
3928    /**
3929     * Returns the height of the horizontal scrollbar.
3930     *
3931     * @return The height in pixels of the horizontal scrollbar or 0 if
3932     *         there is no horizontal scrollbar.
3933     */
3934    protected int getHorizontalScrollbarHeight() {
3935        ScrollabilityCache cache = mScrollCache;
3936        if (cache != null) {
3937            ScrollBarDrawable scrollBar = cache.scrollBar;
3938            if (scrollBar != null) {
3939                int size = scrollBar.getSize(false);
3940                if (size <= 0) {
3941                    size = cache.scrollBarSize;
3942                }
3943                return size;
3944            }
3945            return 0;
3946        }
3947        return 0;
3948    }
3949
3950    /**
3951     * <p>
3952     * Initializes the scrollbars from a given set of styled attributes. This
3953     * method should be called by subclasses that need scrollbars and when an
3954     * instance of these subclasses is created programmatically rather than
3955     * being inflated from XML. This method is automatically called when the XML
3956     * is inflated.
3957     * </p>
3958     *
3959     * @param a the styled attributes set to initialize the scrollbars from
3960     */
3961    protected void initializeScrollbars(TypedArray a) {
3962        initScrollCache();
3963
3964        final ScrollabilityCache scrollabilityCache = mScrollCache;
3965
3966        if (scrollabilityCache.scrollBar == null) {
3967            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3968        }
3969
3970        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3971
3972        if (!fadeScrollbars) {
3973            scrollabilityCache.state = ScrollabilityCache.ON;
3974        }
3975        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3976
3977
3978        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3979                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3980                        .getScrollBarFadeDuration());
3981        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3982                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3983                ViewConfiguration.getScrollDefaultDelay());
3984
3985
3986        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3987                com.android.internal.R.styleable.View_scrollbarSize,
3988                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3989
3990        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3991        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3992
3993        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3994        if (thumb != null) {
3995            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3996        }
3997
3998        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3999                false);
4000        if (alwaysDraw) {
4001            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
4002        }
4003
4004        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
4005        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
4006
4007        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
4008        if (thumb != null) {
4009            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
4010        }
4011
4012        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
4013                false);
4014        if (alwaysDraw) {
4015            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
4016        }
4017
4018        // Apply layout direction to the new Drawables if needed
4019        final int layoutDirection = getLayoutDirection();
4020        if (track != null) {
4021            track.setLayoutDirection(layoutDirection);
4022        }
4023        if (thumb != null) {
4024            thumb.setLayoutDirection(layoutDirection);
4025        }
4026
4027        // Re-apply user/background padding so that scrollbar(s) get added
4028        resolvePadding();
4029    }
4030
4031    /**
4032     * <p>
4033     * Initalizes the scrollability cache if necessary.
4034     * </p>
4035     */
4036    private void initScrollCache() {
4037        if (mScrollCache == null) {
4038            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
4039        }
4040    }
4041
4042    private ScrollabilityCache getScrollCache() {
4043        initScrollCache();
4044        return mScrollCache;
4045    }
4046
4047    /**
4048     * Set the position of the vertical scroll bar. Should be one of
4049     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
4050     * {@link #SCROLLBAR_POSITION_RIGHT}.
4051     *
4052     * @param position Where the vertical scroll bar should be positioned.
4053     */
4054    public void setVerticalScrollbarPosition(int position) {
4055        if (mVerticalScrollbarPosition != position) {
4056            mVerticalScrollbarPosition = position;
4057            computeOpaqueFlags();
4058            resolvePadding();
4059        }
4060    }
4061
4062    /**
4063     * @return The position where the vertical scroll bar will show, if applicable.
4064     * @see #setVerticalScrollbarPosition(int)
4065     */
4066    public int getVerticalScrollbarPosition() {
4067        return mVerticalScrollbarPosition;
4068    }
4069
4070    ListenerInfo getListenerInfo() {
4071        if (mListenerInfo != null) {
4072            return mListenerInfo;
4073        }
4074        mListenerInfo = new ListenerInfo();
4075        return mListenerInfo;
4076    }
4077
4078    /**
4079     * Register a callback to be invoked when focus of this view changed.
4080     *
4081     * @param l The callback that will run.
4082     */
4083    public void setOnFocusChangeListener(OnFocusChangeListener l) {
4084        getListenerInfo().mOnFocusChangeListener = l;
4085    }
4086
4087    /**
4088     * Add a listener that will be called when the bounds of the view change due to
4089     * layout processing.
4090     *
4091     * @param listener The listener that will be called when layout bounds change.
4092     */
4093    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
4094        ListenerInfo li = getListenerInfo();
4095        if (li.mOnLayoutChangeListeners == null) {
4096            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
4097        }
4098        if (!li.mOnLayoutChangeListeners.contains(listener)) {
4099            li.mOnLayoutChangeListeners.add(listener);
4100        }
4101    }
4102
4103    /**
4104     * Remove a listener for layout changes.
4105     *
4106     * @param listener The listener for layout bounds change.
4107     */
4108    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
4109        ListenerInfo li = mListenerInfo;
4110        if (li == null || li.mOnLayoutChangeListeners == null) {
4111            return;
4112        }
4113        li.mOnLayoutChangeListeners.remove(listener);
4114    }
4115
4116    /**
4117     * Add a listener for attach state changes.
4118     *
4119     * This listener will be called whenever this view is attached or detached
4120     * from a window. Remove the listener using
4121     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
4122     *
4123     * @param listener Listener to attach
4124     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
4125     */
4126    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4127        ListenerInfo li = getListenerInfo();
4128        if (li.mOnAttachStateChangeListeners == null) {
4129            li.mOnAttachStateChangeListeners
4130                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
4131        }
4132        li.mOnAttachStateChangeListeners.add(listener);
4133    }
4134
4135    /**
4136     * Remove a listener for attach state changes. The listener will receive no further
4137     * notification of window attach/detach events.
4138     *
4139     * @param listener Listener to remove
4140     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
4141     */
4142    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
4143        ListenerInfo li = mListenerInfo;
4144        if (li == null || li.mOnAttachStateChangeListeners == null) {
4145            return;
4146        }
4147        li.mOnAttachStateChangeListeners.remove(listener);
4148    }
4149
4150    /**
4151     * Returns the focus-change callback registered for this view.
4152     *
4153     * @return The callback, or null if one is not registered.
4154     */
4155    public OnFocusChangeListener getOnFocusChangeListener() {
4156        ListenerInfo li = mListenerInfo;
4157        return li != null ? li.mOnFocusChangeListener : null;
4158    }
4159
4160    /**
4161     * Register a callback to be invoked when this view is clicked. If this view is not
4162     * clickable, it becomes clickable.
4163     *
4164     * @param l The callback that will run
4165     *
4166     * @see #setClickable(boolean)
4167     */
4168    public void setOnClickListener(OnClickListener l) {
4169        if (!isClickable()) {
4170            setClickable(true);
4171        }
4172        getListenerInfo().mOnClickListener = l;
4173    }
4174
4175    /**
4176     * Return whether this view has an attached OnClickListener.  Returns
4177     * true if there is a listener, false if there is none.
4178     */
4179    public boolean hasOnClickListeners() {
4180        ListenerInfo li = mListenerInfo;
4181        return (li != null && li.mOnClickListener != null);
4182    }
4183
4184    /**
4185     * Register a callback to be invoked when this view is clicked and held. If this view is not
4186     * long clickable, it becomes long clickable.
4187     *
4188     * @param l The callback that will run
4189     *
4190     * @see #setLongClickable(boolean)
4191     */
4192    public void setOnLongClickListener(OnLongClickListener l) {
4193        if (!isLongClickable()) {
4194            setLongClickable(true);
4195        }
4196        getListenerInfo().mOnLongClickListener = l;
4197    }
4198
4199    /**
4200     * Register a callback to be invoked when the context menu for this view is
4201     * being built. If this view is not long clickable, it becomes long clickable.
4202     *
4203     * @param l The callback that will run
4204     *
4205     */
4206    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
4207        if (!isLongClickable()) {
4208            setLongClickable(true);
4209        }
4210        getListenerInfo().mOnCreateContextMenuListener = l;
4211    }
4212
4213    /**
4214     * Call this view's OnClickListener, if it is defined.  Performs all normal
4215     * actions associated with clicking: reporting accessibility event, playing
4216     * a sound, etc.
4217     *
4218     * @return True there was an assigned OnClickListener that was called, false
4219     *         otherwise is returned.
4220     */
4221    public boolean performClick() {
4222        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
4223
4224        ListenerInfo li = mListenerInfo;
4225        if (li != null && li.mOnClickListener != null) {
4226            playSoundEffect(SoundEffectConstants.CLICK);
4227            li.mOnClickListener.onClick(this);
4228            return true;
4229        }
4230
4231        return false;
4232    }
4233
4234    /**
4235     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
4236     * this only calls the listener, and does not do any associated clicking
4237     * actions like reporting an accessibility event.
4238     *
4239     * @return True there was an assigned OnClickListener that was called, false
4240     *         otherwise is returned.
4241     */
4242    public boolean callOnClick() {
4243        ListenerInfo li = mListenerInfo;
4244        if (li != null && li.mOnClickListener != null) {
4245            li.mOnClickListener.onClick(this);
4246            return true;
4247        }
4248        return false;
4249    }
4250
4251    /**
4252     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
4253     * OnLongClickListener did not consume the event.
4254     *
4255     * @return True if one of the above receivers consumed the event, false otherwise.
4256     */
4257    public boolean performLongClick() {
4258        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
4259
4260        boolean handled = false;
4261        ListenerInfo li = mListenerInfo;
4262        if (li != null && li.mOnLongClickListener != null) {
4263            handled = li.mOnLongClickListener.onLongClick(View.this);
4264        }
4265        if (!handled) {
4266            handled = showContextMenu();
4267        }
4268        if (handled) {
4269            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
4270        }
4271        return handled;
4272    }
4273
4274    /**
4275     * Performs button-related actions during a touch down event.
4276     *
4277     * @param event The event.
4278     * @return True if the down was consumed.
4279     *
4280     * @hide
4281     */
4282    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
4283        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
4284            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
4285                return true;
4286            }
4287        }
4288        return false;
4289    }
4290
4291    /**
4292     * Bring up the context menu for this view.
4293     *
4294     * @return Whether a context menu was displayed.
4295     */
4296    public boolean showContextMenu() {
4297        return getParent().showContextMenuForChild(this);
4298    }
4299
4300    /**
4301     * Bring up the context menu for this view, referring to the item under the specified point.
4302     *
4303     * @param x The referenced x coordinate.
4304     * @param y The referenced y coordinate.
4305     * @param metaState The keyboard modifiers that were pressed.
4306     * @return Whether a context menu was displayed.
4307     *
4308     * @hide
4309     */
4310    public boolean showContextMenu(float x, float y, int metaState) {
4311        return showContextMenu();
4312    }
4313
4314    /**
4315     * Start an action mode.
4316     *
4317     * @param callback Callback that will control the lifecycle of the action mode
4318     * @return The new action mode if it is started, null otherwise
4319     *
4320     * @see ActionMode
4321     */
4322    public ActionMode startActionMode(ActionMode.Callback callback) {
4323        ViewParent parent = getParent();
4324        if (parent == null) return null;
4325        return parent.startActionModeForChild(this, callback);
4326    }
4327
4328    /**
4329     * Register a callback to be invoked when a hardware key is pressed in this view.
4330     * Key presses in software input methods will generally not trigger the methods of
4331     * this listener.
4332     * @param l the key listener to attach to this view
4333     */
4334    public void setOnKeyListener(OnKeyListener l) {
4335        getListenerInfo().mOnKeyListener = l;
4336    }
4337
4338    /**
4339     * Register a callback to be invoked when a touch event is sent to this view.
4340     * @param l the touch listener to attach to this view
4341     */
4342    public void setOnTouchListener(OnTouchListener l) {
4343        getListenerInfo().mOnTouchListener = l;
4344    }
4345
4346    /**
4347     * Register a callback to be invoked when a generic motion event is sent to this view.
4348     * @param l the generic motion listener to attach to this view
4349     */
4350    public void setOnGenericMotionListener(OnGenericMotionListener l) {
4351        getListenerInfo().mOnGenericMotionListener = l;
4352    }
4353
4354    /**
4355     * Register a callback to be invoked when a hover event is sent to this view.
4356     * @param l the hover listener to attach to this view
4357     */
4358    public void setOnHoverListener(OnHoverListener l) {
4359        getListenerInfo().mOnHoverListener = l;
4360    }
4361
4362    /**
4363     * Register a drag event listener callback object for this View. The parameter is
4364     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
4365     * View, the system calls the
4366     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
4367     * @param l An implementation of {@link android.view.View.OnDragListener}.
4368     */
4369    public void setOnDragListener(OnDragListener l) {
4370        getListenerInfo().mOnDragListener = l;
4371    }
4372
4373    /**
4374     * Give this view focus. This will cause
4375     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
4376     *
4377     * Note: this does not check whether this {@link View} should get focus, it just
4378     * gives it focus no matter what.  It should only be called internally by framework
4379     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
4380     *
4381     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
4382     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
4383     *        focus moved when requestFocus() is called. It may not always
4384     *        apply, in which case use the default View.FOCUS_DOWN.
4385     * @param previouslyFocusedRect The rectangle of the view that had focus
4386     *        prior in this View's coordinate system.
4387     */
4388    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
4389        if (DBG) {
4390            System.out.println(this + " requestFocus()");
4391        }
4392
4393        if ((mPrivateFlags & PFLAG_FOCUSED) == 0) {
4394            mPrivateFlags |= PFLAG_FOCUSED;
4395
4396            View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null;
4397
4398            if (mParent != null) {
4399                mParent.requestChildFocus(this, this);
4400            }
4401
4402            if (mAttachInfo != null) {
4403                mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this);
4404            }
4405
4406            onFocusChanged(true, direction, previouslyFocusedRect);
4407            refreshDrawableState();
4408
4409            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4410                notifyAccessibilityStateChanged();
4411            }
4412        }
4413    }
4414
4415    /**
4416     * Request that a rectangle of this view be visible on the screen,
4417     * scrolling if necessary just enough.
4418     *
4419     * <p>A View should call this if it maintains some notion of which part
4420     * of its content is interesting.  For example, a text editing view
4421     * should call this when its cursor moves.
4422     *
4423     * @param rectangle The rectangle.
4424     * @return Whether any parent scrolled.
4425     */
4426    public boolean requestRectangleOnScreen(Rect rectangle) {
4427        return requestRectangleOnScreen(rectangle, false);
4428    }
4429
4430    /**
4431     * Request that a rectangle of this view be visible on the screen,
4432     * scrolling if necessary just enough.
4433     *
4434     * <p>A View should call this if it maintains some notion of which part
4435     * of its content is interesting.  For example, a text editing view
4436     * should call this when its cursor moves.
4437     *
4438     * <p>When <code>immediate</code> is set to true, scrolling will not be
4439     * animated.
4440     *
4441     * @param rectangle The rectangle.
4442     * @param immediate True to forbid animated scrolling, false otherwise
4443     * @return Whether any parent scrolled.
4444     */
4445    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
4446        if (mParent == null) {
4447            return false;
4448        }
4449
4450        View child = this;
4451
4452        RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF();
4453        position.set(rectangle);
4454
4455        ViewParent parent = mParent;
4456        boolean scrolled = false;
4457        while (parent != null) {
4458            rectangle.set((int) position.left, (int) position.top,
4459                    (int) position.right, (int) position.bottom);
4460
4461            scrolled |= parent.requestChildRectangleOnScreen(child,
4462                    rectangle, immediate);
4463
4464            if (!child.hasIdentityMatrix()) {
4465                child.getMatrix().mapRect(position);
4466            }
4467
4468            position.offset(child.mLeft, child.mTop);
4469
4470            if (!(parent instanceof View)) {
4471                break;
4472            }
4473
4474            View parentView = (View) parent;
4475
4476            position.offset(-parentView.getScrollX(), -parentView.getScrollY());
4477
4478            child = parentView;
4479            parent = child.getParent();
4480        }
4481
4482        return scrolled;
4483    }
4484
4485    /**
4486     * Called when this view wants to give up focus. If focus is cleared
4487     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
4488     * <p>
4489     * <strong>Note:</strong> When a View clears focus the framework is trying
4490     * to give focus to the first focusable View from the top. Hence, if this
4491     * View is the first from the top that can take focus, then all callbacks
4492     * related to clearing focus will be invoked after wich the framework will
4493     * give focus to this view.
4494     * </p>
4495     */
4496    public void clearFocus() {
4497        if (DBG) {
4498            System.out.println(this + " clearFocus()");
4499        }
4500
4501        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4502            mPrivateFlags &= ~PFLAG_FOCUSED;
4503
4504            if (mParent != null) {
4505                mParent.clearChildFocus(this);
4506            }
4507
4508            onFocusChanged(false, 0, null);
4509
4510            refreshDrawableState();
4511
4512            if (!rootViewRequestFocus()) {
4513                notifyGlobalFocusCleared(this);
4514            }
4515
4516            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4517                notifyAccessibilityStateChanged();
4518            }
4519        }
4520    }
4521
4522    void notifyGlobalFocusCleared(View oldFocus) {
4523        if (oldFocus != null && mAttachInfo != null) {
4524            mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null);
4525        }
4526    }
4527
4528    boolean rootViewRequestFocus() {
4529        View root = getRootView();
4530        if (root != null) {
4531            return root.requestFocus();
4532        }
4533        return false;
4534    }
4535
4536    /**
4537     * Called internally by the view system when a new view is getting focus.
4538     * This is what clears the old focus.
4539     */
4540    void unFocus() {
4541        if (DBG) {
4542            System.out.println(this + " unFocus()");
4543        }
4544
4545        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
4546            mPrivateFlags &= ~PFLAG_FOCUSED;
4547
4548            onFocusChanged(false, 0, null);
4549            refreshDrawableState();
4550
4551            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4552                notifyAccessibilityStateChanged();
4553            }
4554        }
4555    }
4556
4557    /**
4558     * Returns true if this view has focus iteself, or is the ancestor of the
4559     * view that has focus.
4560     *
4561     * @return True if this view has or contains focus, false otherwise.
4562     */
4563    @ViewDebug.ExportedProperty(category = "focus")
4564    public boolean hasFocus() {
4565        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
4566    }
4567
4568    /**
4569     * Returns true if this view is focusable or if it contains a reachable View
4570     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
4571     * is a View whose parents do not block descendants focus.
4572     *
4573     * Only {@link #VISIBLE} views are considered focusable.
4574     *
4575     * @return True if the view is focusable or if the view contains a focusable
4576     *         View, false otherwise.
4577     *
4578     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
4579     */
4580    public boolean hasFocusable() {
4581        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
4582    }
4583
4584    /**
4585     * Called by the view system when the focus state of this view changes.
4586     * When the focus change event is caused by directional navigation, direction
4587     * and previouslyFocusedRect provide insight into where the focus is coming from.
4588     * When overriding, be sure to call up through to the super class so that
4589     * the standard focus handling will occur.
4590     *
4591     * @param gainFocus True if the View has focus; false otherwise.
4592     * @param direction The direction focus has moved when requestFocus()
4593     *                  is called to give this view focus. Values are
4594     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
4595     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
4596     *                  It may not always apply, in which case use the default.
4597     * @param previouslyFocusedRect The rectangle, in this view's coordinate
4598     *        system, of the previously focused view.  If applicable, this will be
4599     *        passed in as finer grained information about where the focus is coming
4600     *        from (in addition to direction).  Will be <code>null</code> otherwise.
4601     */
4602    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
4603        if (gainFocus) {
4604            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4605                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
4606            }
4607        }
4608
4609        InputMethodManager imm = InputMethodManager.peekInstance();
4610        if (!gainFocus) {
4611            if (isPressed()) {
4612                setPressed(false);
4613            }
4614            if (imm != null && mAttachInfo != null
4615                    && mAttachInfo.mHasWindowFocus) {
4616                imm.focusOut(this);
4617            }
4618            onFocusLost();
4619        } else if (imm != null && mAttachInfo != null
4620                && mAttachInfo.mHasWindowFocus) {
4621            imm.focusIn(this);
4622        }
4623
4624        invalidate(true);
4625        ListenerInfo li = mListenerInfo;
4626        if (li != null && li.mOnFocusChangeListener != null) {
4627            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
4628        }
4629
4630        if (mAttachInfo != null) {
4631            mAttachInfo.mKeyDispatchState.reset(this);
4632        }
4633    }
4634
4635    /**
4636     * Sends an accessibility event of the given type. If accessibility is
4637     * not enabled this method has no effect. The default implementation calls
4638     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
4639     * to populate information about the event source (this View), then calls
4640     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
4641     * populate the text content of the event source including its descendants,
4642     * and last calls
4643     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
4644     * on its parent to resuest sending of the event to interested parties.
4645     * <p>
4646     * If an {@link AccessibilityDelegate} has been specified via calling
4647     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4648     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
4649     * responsible for handling this call.
4650     * </p>
4651     *
4652     * @param eventType The type of the event to send, as defined by several types from
4653     * {@link android.view.accessibility.AccessibilityEvent}, such as
4654     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
4655     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
4656     *
4657     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4658     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4659     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
4660     * @see AccessibilityDelegate
4661     */
4662    public void sendAccessibilityEvent(int eventType) {
4663        if (mAccessibilityDelegate != null) {
4664            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
4665        } else {
4666            sendAccessibilityEventInternal(eventType);
4667        }
4668    }
4669
4670    /**
4671     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
4672     * {@link AccessibilityEvent} to make an announcement which is related to some
4673     * sort of a context change for which none of the events representing UI transitions
4674     * is a good fit. For example, announcing a new page in a book. If accessibility
4675     * is not enabled this method does nothing.
4676     *
4677     * @param text The announcement text.
4678     */
4679    public void announceForAccessibility(CharSequence text) {
4680        if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) {
4681            AccessibilityEvent event = AccessibilityEvent.obtain(
4682                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
4683            onInitializeAccessibilityEvent(event);
4684            event.getText().add(text);
4685            event.setContentDescription(null);
4686            mParent.requestSendAccessibilityEvent(this, event);
4687        }
4688    }
4689
4690    /**
4691     * @see #sendAccessibilityEvent(int)
4692     *
4693     * Note: Called from the default {@link AccessibilityDelegate}.
4694     */
4695    void sendAccessibilityEventInternal(int eventType) {
4696        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
4697            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
4698        }
4699    }
4700
4701    /**
4702     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
4703     * takes as an argument an empty {@link AccessibilityEvent} and does not
4704     * perform a check whether accessibility is enabled.
4705     * <p>
4706     * If an {@link AccessibilityDelegate} has been specified via calling
4707     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4708     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4709     * is responsible for handling this call.
4710     * </p>
4711     *
4712     * @param event The event to send.
4713     *
4714     * @see #sendAccessibilityEvent(int)
4715     */
4716    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4717        if (mAccessibilityDelegate != null) {
4718            mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4719        } else {
4720            sendAccessibilityEventUncheckedInternal(event);
4721        }
4722    }
4723
4724    /**
4725     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4726     *
4727     * Note: Called from the default {@link AccessibilityDelegate}.
4728     */
4729    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4730        if (!isShown()) {
4731            return;
4732        }
4733        onInitializeAccessibilityEvent(event);
4734        // Only a subset of accessibility events populates text content.
4735        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4736            dispatchPopulateAccessibilityEvent(event);
4737        }
4738        // In the beginning we called #isShown(), so we know that getParent() is not null.
4739        getParent().requestSendAccessibilityEvent(this, event);
4740    }
4741
4742    /**
4743     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4744     * to its children for adding their text content to the event. Note that the
4745     * event text is populated in a separate dispatch path since we add to the
4746     * event not only the text of the source but also the text of all its descendants.
4747     * A typical implementation will call
4748     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4749     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4750     * on each child. Override this method if custom population of the event text
4751     * content is required.
4752     * <p>
4753     * If an {@link AccessibilityDelegate} has been specified via calling
4754     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4755     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4756     * is responsible for handling this call.
4757     * </p>
4758     * <p>
4759     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4760     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4761     * </p>
4762     *
4763     * @param event The event.
4764     *
4765     * @return True if the event population was completed.
4766     */
4767    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4768        if (mAccessibilityDelegate != null) {
4769            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4770        } else {
4771            return dispatchPopulateAccessibilityEventInternal(event);
4772        }
4773    }
4774
4775    /**
4776     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4777     *
4778     * Note: Called from the default {@link AccessibilityDelegate}.
4779     */
4780    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4781        onPopulateAccessibilityEvent(event);
4782        return false;
4783    }
4784
4785    /**
4786     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4787     * giving a chance to this View to populate the accessibility event with its
4788     * text content. While this method is free to modify event
4789     * attributes other than text content, doing so should normally be performed in
4790     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4791     * <p>
4792     * Example: Adding formatted date string to an accessibility event in addition
4793     *          to the text added by the super implementation:
4794     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4795     *     super.onPopulateAccessibilityEvent(event);
4796     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4797     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4798     *         mCurrentDate.getTimeInMillis(), flags);
4799     *     event.getText().add(selectedDateUtterance);
4800     * }</pre>
4801     * <p>
4802     * If an {@link AccessibilityDelegate} has been specified via calling
4803     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4804     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4805     * is responsible for handling this call.
4806     * </p>
4807     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4808     * information to the event, in case the default implementation has basic information to add.
4809     * </p>
4810     *
4811     * @param event The accessibility event which to populate.
4812     *
4813     * @see #sendAccessibilityEvent(int)
4814     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4815     */
4816    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4817        if (mAccessibilityDelegate != null) {
4818            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4819        } else {
4820            onPopulateAccessibilityEventInternal(event);
4821        }
4822    }
4823
4824    /**
4825     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4826     *
4827     * Note: Called from the default {@link AccessibilityDelegate}.
4828     */
4829    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4830
4831    }
4832
4833    /**
4834     * Initializes an {@link AccessibilityEvent} with information about
4835     * this View which is the event source. In other words, the source of
4836     * an accessibility event is the view whose state change triggered firing
4837     * the event.
4838     * <p>
4839     * Example: Setting the password property of an event in addition
4840     *          to properties set by the super implementation:
4841     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4842     *     super.onInitializeAccessibilityEvent(event);
4843     *     event.setPassword(true);
4844     * }</pre>
4845     * <p>
4846     * If an {@link AccessibilityDelegate} has been specified via calling
4847     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4848     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4849     * is responsible for handling this call.
4850     * </p>
4851     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4852     * information to the event, in case the default implementation has basic information to add.
4853     * </p>
4854     * @param event The event to initialize.
4855     *
4856     * @see #sendAccessibilityEvent(int)
4857     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4858     */
4859    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4860        if (mAccessibilityDelegate != null) {
4861            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4862        } else {
4863            onInitializeAccessibilityEventInternal(event);
4864        }
4865    }
4866
4867    /**
4868     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4869     *
4870     * Note: Called from the default {@link AccessibilityDelegate}.
4871     */
4872    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4873        event.setSource(this);
4874        event.setClassName(View.class.getName());
4875        event.setPackageName(getContext().getPackageName());
4876        event.setEnabled(isEnabled());
4877        event.setContentDescription(mContentDescription);
4878
4879        switch (event.getEventType()) {
4880            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4881                ArrayList<View> focusablesTempList = (mAttachInfo != null)
4882                        ? mAttachInfo.mTempArrayList : new ArrayList<View>();
4883                getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
4884                event.setItemCount(focusablesTempList.size());
4885                event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4886                if (mAttachInfo != null) {
4887                    focusablesTempList.clear();
4888                }
4889            } break;
4890            case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: {
4891                CharSequence text = getIterableTextForAccessibility();
4892                if (text != null && text.length() > 0) {
4893                    event.setFromIndex(getAccessibilitySelectionStart());
4894                    event.setToIndex(getAccessibilitySelectionEnd());
4895                    event.setItemCount(text.length());
4896                }
4897            } break;
4898        }
4899    }
4900
4901    /**
4902     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4903     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4904     * This method is responsible for obtaining an accessibility node info from a
4905     * pool of reusable instances and calling
4906     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4907     * initialize the former.
4908     * <p>
4909     * Note: The client is responsible for recycling the obtained instance by calling
4910     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4911     * </p>
4912     *
4913     * @return A populated {@link AccessibilityNodeInfo}.
4914     *
4915     * @see AccessibilityNodeInfo
4916     */
4917    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4918        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4919        if (provider != null) {
4920            return provider.createAccessibilityNodeInfo(View.NO_ID);
4921        } else {
4922            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4923            onInitializeAccessibilityNodeInfo(info);
4924            return info;
4925        }
4926    }
4927
4928    /**
4929     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4930     * The base implementation sets:
4931     * <ul>
4932     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4933     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4934     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4935     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4936     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4937     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4938     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4939     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4940     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4941     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4942     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4943     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4944     * </ul>
4945     * <p>
4946     * Subclasses should override this method, call the super implementation,
4947     * and set additional attributes.
4948     * </p>
4949     * <p>
4950     * If an {@link AccessibilityDelegate} has been specified via calling
4951     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4952     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4953     * is responsible for handling this call.
4954     * </p>
4955     *
4956     * @param info The instance to initialize.
4957     */
4958    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4959        if (mAccessibilityDelegate != null) {
4960            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4961        } else {
4962            onInitializeAccessibilityNodeInfoInternal(info);
4963        }
4964    }
4965
4966    /**
4967     * Gets the location of this view in screen coordintates.
4968     *
4969     * @param outRect The output location
4970     */
4971    void getBoundsOnScreen(Rect outRect) {
4972        if (mAttachInfo == null) {
4973            return;
4974        }
4975
4976        RectF position = mAttachInfo.mTmpTransformRect;
4977        position.set(0, 0, mRight - mLeft, mBottom - mTop);
4978
4979        if (!hasIdentityMatrix()) {
4980            getMatrix().mapRect(position);
4981        }
4982
4983        position.offset(mLeft, mTop);
4984
4985        ViewParent parent = mParent;
4986        while (parent instanceof View) {
4987            View parentView = (View) parent;
4988
4989            position.offset(-parentView.mScrollX, -parentView.mScrollY);
4990
4991            if (!parentView.hasIdentityMatrix()) {
4992                parentView.getMatrix().mapRect(position);
4993            }
4994
4995            position.offset(parentView.mLeft, parentView.mTop);
4996
4997            parent = parentView.mParent;
4998        }
4999
5000        if (parent instanceof ViewRootImpl) {
5001            ViewRootImpl viewRootImpl = (ViewRootImpl) parent;
5002            position.offset(0, -viewRootImpl.mCurScrollY);
5003        }
5004
5005        position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop);
5006
5007        outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f),
5008                (int) (position.right + 0.5f), (int) (position.bottom + 0.5f));
5009    }
5010
5011    /**
5012     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
5013     *
5014     * Note: Called from the default {@link AccessibilityDelegate}.
5015     */
5016    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
5017        Rect bounds = mAttachInfo.mTmpInvalRect;
5018
5019        getDrawingRect(bounds);
5020        info.setBoundsInParent(bounds);
5021
5022        getBoundsOnScreen(bounds);
5023        info.setBoundsInScreen(bounds);
5024
5025        ViewParent parent = getParentForAccessibility();
5026        if (parent instanceof View) {
5027            info.setParent((View) parent);
5028        }
5029
5030        if (mID != View.NO_ID) {
5031            View rootView = getRootView();
5032            if (rootView == null) {
5033                rootView = this;
5034            }
5035            View label = rootView.findLabelForView(this, mID);
5036            if (label != null) {
5037                info.setLabeledBy(label);
5038            }
5039
5040            if ((mAttachInfo.mAccessibilityFetchFlags
5041                    & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0) {
5042                try {
5043                    String viewId = getResources().getResourceName(mID);
5044                    info.setViewIdResourceName(viewId);
5045                } catch (Resources.NotFoundException nfe) {
5046                    /* ignore */
5047                }
5048            }
5049        }
5050
5051        if (mLabelForId != View.NO_ID) {
5052            View rootView = getRootView();
5053            if (rootView == null) {
5054                rootView = this;
5055            }
5056            View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId);
5057            if (labeled != null) {
5058                info.setLabelFor(labeled);
5059            }
5060        }
5061
5062        info.setVisibleToUser(isVisibleToUser());
5063
5064        info.setPackageName(mContext.getPackageName());
5065        info.setClassName(View.class.getName());
5066        info.setContentDescription(getContentDescription());
5067
5068        info.setEnabled(isEnabled());
5069        info.setClickable(isClickable());
5070        info.setFocusable(isFocusable());
5071        info.setFocused(isFocused());
5072        info.setAccessibilityFocused(isAccessibilityFocused());
5073        info.setSelected(isSelected());
5074        info.setLongClickable(isLongClickable());
5075
5076        // TODO: These make sense only if we are in an AdapterView but all
5077        // views can be selected. Maybe from accessibility perspective
5078        // we should report as selectable view in an AdapterView.
5079        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
5080        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
5081
5082        if (isFocusable()) {
5083            if (isFocused()) {
5084                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
5085            } else {
5086                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
5087            }
5088        }
5089
5090        if (!isAccessibilityFocused()) {
5091            info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
5092        } else {
5093            info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
5094        }
5095
5096        if (isClickable() && isEnabled()) {
5097            info.addAction(AccessibilityNodeInfo.ACTION_CLICK);
5098        }
5099
5100        if (isLongClickable() && isEnabled()) {
5101            info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
5102        }
5103
5104        CharSequence text = getIterableTextForAccessibility();
5105        if (text != null && text.length() > 0) {
5106            info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
5107
5108            info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION);
5109            info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
5110            info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
5111            info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER
5112                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD
5113                    | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH);
5114        }
5115    }
5116
5117    private View findLabelForView(View view, int labeledId) {
5118        if (mMatchLabelForPredicate == null) {
5119            mMatchLabelForPredicate = new MatchLabelForPredicate();
5120        }
5121        mMatchLabelForPredicate.mLabeledId = labeledId;
5122        return findViewByPredicateInsideOut(view, mMatchLabelForPredicate);
5123    }
5124
5125    /**
5126     * Computes whether this view is visible to the user. Such a view is
5127     * attached, visible, all its predecessors are visible, it is not clipped
5128     * entirely by its predecessors, and has an alpha greater than zero.
5129     *
5130     * @return Whether the view is visible on the screen.
5131     *
5132     * @hide
5133     */
5134    protected boolean isVisibleToUser() {
5135        return isVisibleToUser(null);
5136    }
5137
5138    /**
5139     * Computes whether the given portion of this view is visible to the user.
5140     * Such a view is attached, visible, all its predecessors are visible,
5141     * has an alpha greater than zero, and the specified portion is not
5142     * clipped entirely by its predecessors.
5143     *
5144     * @param boundInView the portion of the view to test; coordinates should be relative; may be
5145     *                    <code>null</code>, and the entire view will be tested in this case.
5146     *                    When <code>true</code> is returned by the function, the actual visible
5147     *                    region will be stored in this parameter; that is, if boundInView is fully
5148     *                    contained within the view, no modification will be made, otherwise regions
5149     *                    outside of the visible area of the view will be clipped.
5150     *
5151     * @return Whether the specified portion of the view is visible on the screen.
5152     *
5153     * @hide
5154     */
5155    protected boolean isVisibleToUser(Rect boundInView) {
5156        if (mAttachInfo != null) {
5157            // Attached to invisible window means this view is not visible.
5158            if (mAttachInfo.mWindowVisibility != View.VISIBLE) {
5159                return false;
5160            }
5161            // An invisible predecessor or one with alpha zero means
5162            // that this view is not visible to the user.
5163            Object current = this;
5164            while (current instanceof View) {
5165                View view = (View) current;
5166                // We have attach info so this view is attached and there is no
5167                // need to check whether we reach to ViewRootImpl on the way up.
5168                if (view.getAlpha() <= 0 || view.getVisibility() != VISIBLE) {
5169                    return false;
5170                }
5171                current = view.mParent;
5172            }
5173            // Check if the view is entirely covered by its predecessors.
5174            Rect visibleRect = mAttachInfo.mTmpInvalRect;
5175            Point offset = mAttachInfo.mPoint;
5176            if (!getGlobalVisibleRect(visibleRect, offset)) {
5177                return false;
5178            }
5179            // Check if the visible portion intersects the rectangle of interest.
5180            if (boundInView != null) {
5181                visibleRect.offset(-offset.x, -offset.y);
5182                return boundInView.intersect(visibleRect);
5183            }
5184            return true;
5185        }
5186        return false;
5187    }
5188
5189    /**
5190     * Returns the delegate for implementing accessibility support via
5191     * composition. For more details see {@link AccessibilityDelegate}.
5192     *
5193     * @return The delegate, or null if none set.
5194     *
5195     * @hide
5196     */
5197    public AccessibilityDelegate getAccessibilityDelegate() {
5198        return mAccessibilityDelegate;
5199    }
5200
5201    /**
5202     * Sets a delegate for implementing accessibility support via composition as
5203     * opposed to inheritance. The delegate's primary use is for implementing
5204     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
5205     *
5206     * @param delegate The delegate instance.
5207     *
5208     * @see AccessibilityDelegate
5209     */
5210    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
5211        mAccessibilityDelegate = delegate;
5212    }
5213
5214    /**
5215     * Gets the provider for managing a virtual view hierarchy rooted at this View
5216     * and reported to {@link android.accessibilityservice.AccessibilityService}s
5217     * that explore the window content.
5218     * <p>
5219     * If this method returns an instance, this instance is responsible for managing
5220     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
5221     * View including the one representing the View itself. Similarly the returned
5222     * instance is responsible for performing accessibility actions on any virtual
5223     * view or the root view itself.
5224     * </p>
5225     * <p>
5226     * If an {@link AccessibilityDelegate} has been specified via calling
5227     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
5228     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
5229     * is responsible for handling this call.
5230     * </p>
5231     *
5232     * @return The provider.
5233     *
5234     * @see AccessibilityNodeProvider
5235     */
5236    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
5237        if (mAccessibilityDelegate != null) {
5238            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
5239        } else {
5240            return null;
5241        }
5242    }
5243
5244    /**
5245     * Gets the unique identifier of this view on the screen for accessibility purposes.
5246     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
5247     *
5248     * @return The view accessibility id.
5249     *
5250     * @hide
5251     */
5252    public int getAccessibilityViewId() {
5253        if (mAccessibilityViewId == NO_ID) {
5254            mAccessibilityViewId = sNextAccessibilityViewId++;
5255        }
5256        return mAccessibilityViewId;
5257    }
5258
5259    /**
5260     * Gets the unique identifier of the window in which this View reseides.
5261     *
5262     * @return The window accessibility id.
5263     *
5264     * @hide
5265     */
5266    public int getAccessibilityWindowId() {
5267        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
5268    }
5269
5270    /**
5271     * Gets the {@link View} description. It briefly describes the view and is
5272     * primarily used for accessibility support. Set this property to enable
5273     * better accessibility support for your application. This is especially
5274     * true for views that do not have textual representation (For example,
5275     * ImageButton).
5276     *
5277     * @return The content description.
5278     *
5279     * @attr ref android.R.styleable#View_contentDescription
5280     */
5281    @ViewDebug.ExportedProperty(category = "accessibility")
5282    public CharSequence getContentDescription() {
5283        return mContentDescription;
5284    }
5285
5286    /**
5287     * Sets the {@link View} description. It briefly describes the view and is
5288     * primarily used for accessibility support. Set this property to enable
5289     * better accessibility support for your application. This is especially
5290     * true for views that do not have textual representation (For example,
5291     * ImageButton).
5292     *
5293     * @param contentDescription The content description.
5294     *
5295     * @attr ref android.R.styleable#View_contentDescription
5296     */
5297    @RemotableViewMethod
5298    public void setContentDescription(CharSequence contentDescription) {
5299        if (mContentDescription == null) {
5300            if (contentDescription == null) {
5301                return;
5302            }
5303        } else if (mContentDescription.equals(contentDescription)) {
5304            return;
5305        }
5306        mContentDescription = contentDescription;
5307        final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0;
5308        if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
5309             setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
5310        }
5311        notifyAccessibilityStateChanged();
5312    }
5313
5314    /**
5315     * Gets the id of a view for which this view serves as a label for
5316     * accessibility purposes.
5317     *
5318     * @return The labeled view id.
5319     */
5320    @ViewDebug.ExportedProperty(category = "accessibility")
5321    public int getLabelFor() {
5322        return mLabelForId;
5323    }
5324
5325    /**
5326     * Sets the id of a view for which this view serves as a label for
5327     * accessibility purposes.
5328     *
5329     * @param id The labeled view id.
5330     */
5331    @RemotableViewMethod
5332    public void setLabelFor(int id) {
5333        mLabelForId = id;
5334        if (mLabelForId != View.NO_ID
5335                && mID == View.NO_ID) {
5336            mID = generateViewId();
5337        }
5338    }
5339
5340    /**
5341     * Invoked whenever this view loses focus, either by losing window focus or by losing
5342     * focus within its window. This method can be used to clear any state tied to the
5343     * focus. For instance, if a button is held pressed with the trackball and the window
5344     * loses focus, this method can be used to cancel the press.
5345     *
5346     * Subclasses of View overriding this method should always call super.onFocusLost().
5347     *
5348     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
5349     * @see #onWindowFocusChanged(boolean)
5350     *
5351     * @hide pending API council approval
5352     */
5353    protected void onFocusLost() {
5354        resetPressedState();
5355    }
5356
5357    private void resetPressedState() {
5358        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5359            return;
5360        }
5361
5362        if (isPressed()) {
5363            setPressed(false);
5364
5365            if (!mHasPerformedLongPress) {
5366                removeLongPressCallback();
5367            }
5368        }
5369    }
5370
5371    /**
5372     * Returns true if this view has focus
5373     *
5374     * @return True if this view has focus, false otherwise.
5375     */
5376    @ViewDebug.ExportedProperty(category = "focus")
5377    public boolean isFocused() {
5378        return (mPrivateFlags & PFLAG_FOCUSED) != 0;
5379    }
5380
5381    /**
5382     * Find the view in the hierarchy rooted at this view that currently has
5383     * focus.
5384     *
5385     * @return The view that currently has focus, or null if no focused view can
5386     *         be found.
5387     */
5388    public View findFocus() {
5389        return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null;
5390    }
5391
5392    /**
5393     * Indicates whether this view is one of the set of scrollable containers in
5394     * its window.
5395     *
5396     * @return whether this view is one of the set of scrollable containers in
5397     * its window
5398     *
5399     * @attr ref android.R.styleable#View_isScrollContainer
5400     */
5401    public boolean isScrollContainer() {
5402        return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0;
5403    }
5404
5405    /**
5406     * Change whether this view is one of the set of scrollable containers in
5407     * its window.  This will be used to determine whether the window can
5408     * resize or must pan when a soft input area is open -- scrollable
5409     * containers allow the window to use resize mode since the container
5410     * will appropriately shrink.
5411     *
5412     * @attr ref android.R.styleable#View_isScrollContainer
5413     */
5414    public void setScrollContainer(boolean isScrollContainer) {
5415        if (isScrollContainer) {
5416            if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) {
5417                mAttachInfo.mScrollContainers.add(this);
5418                mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
5419            }
5420            mPrivateFlags |= PFLAG_SCROLL_CONTAINER;
5421        } else {
5422            if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
5423                mAttachInfo.mScrollContainers.remove(this);
5424            }
5425            mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED);
5426        }
5427    }
5428
5429    /**
5430     * Returns the quality of the drawing cache.
5431     *
5432     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5433     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5434     *
5435     * @see #setDrawingCacheQuality(int)
5436     * @see #setDrawingCacheEnabled(boolean)
5437     * @see #isDrawingCacheEnabled()
5438     *
5439     * @attr ref android.R.styleable#View_drawingCacheQuality
5440     */
5441    public int getDrawingCacheQuality() {
5442        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
5443    }
5444
5445    /**
5446     * Set the drawing cache quality of this view. This value is used only when the
5447     * drawing cache is enabled
5448     *
5449     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
5450     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
5451     *
5452     * @see #getDrawingCacheQuality()
5453     * @see #setDrawingCacheEnabled(boolean)
5454     * @see #isDrawingCacheEnabled()
5455     *
5456     * @attr ref android.R.styleable#View_drawingCacheQuality
5457     */
5458    public void setDrawingCacheQuality(int quality) {
5459        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
5460    }
5461
5462    /**
5463     * Returns whether the screen should remain on, corresponding to the current
5464     * value of {@link #KEEP_SCREEN_ON}.
5465     *
5466     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
5467     *
5468     * @see #setKeepScreenOn(boolean)
5469     *
5470     * @attr ref android.R.styleable#View_keepScreenOn
5471     */
5472    public boolean getKeepScreenOn() {
5473        return (mViewFlags & KEEP_SCREEN_ON) != 0;
5474    }
5475
5476    /**
5477     * Controls whether the screen should remain on, modifying the
5478     * value of {@link #KEEP_SCREEN_ON}.
5479     *
5480     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
5481     *
5482     * @see #getKeepScreenOn()
5483     *
5484     * @attr ref android.R.styleable#View_keepScreenOn
5485     */
5486    public void setKeepScreenOn(boolean keepScreenOn) {
5487        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
5488    }
5489
5490    /**
5491     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5492     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5493     *
5494     * @attr ref android.R.styleable#View_nextFocusLeft
5495     */
5496    public int getNextFocusLeftId() {
5497        return mNextFocusLeftId;
5498    }
5499
5500    /**
5501     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
5502     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
5503     * decide automatically.
5504     *
5505     * @attr ref android.R.styleable#View_nextFocusLeft
5506     */
5507    public void setNextFocusLeftId(int nextFocusLeftId) {
5508        mNextFocusLeftId = nextFocusLeftId;
5509    }
5510
5511    /**
5512     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5513     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5514     *
5515     * @attr ref android.R.styleable#View_nextFocusRight
5516     */
5517    public int getNextFocusRightId() {
5518        return mNextFocusRightId;
5519    }
5520
5521    /**
5522     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
5523     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
5524     * decide automatically.
5525     *
5526     * @attr ref android.R.styleable#View_nextFocusRight
5527     */
5528    public void setNextFocusRightId(int nextFocusRightId) {
5529        mNextFocusRightId = nextFocusRightId;
5530    }
5531
5532    /**
5533     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5534     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5535     *
5536     * @attr ref android.R.styleable#View_nextFocusUp
5537     */
5538    public int getNextFocusUpId() {
5539        return mNextFocusUpId;
5540    }
5541
5542    /**
5543     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
5544     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
5545     * decide automatically.
5546     *
5547     * @attr ref android.R.styleable#View_nextFocusUp
5548     */
5549    public void setNextFocusUpId(int nextFocusUpId) {
5550        mNextFocusUpId = nextFocusUpId;
5551    }
5552
5553    /**
5554     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5555     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5556     *
5557     * @attr ref android.R.styleable#View_nextFocusDown
5558     */
5559    public int getNextFocusDownId() {
5560        return mNextFocusDownId;
5561    }
5562
5563    /**
5564     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
5565     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
5566     * decide automatically.
5567     *
5568     * @attr ref android.R.styleable#View_nextFocusDown
5569     */
5570    public void setNextFocusDownId(int nextFocusDownId) {
5571        mNextFocusDownId = nextFocusDownId;
5572    }
5573
5574    /**
5575     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5576     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
5577     *
5578     * @attr ref android.R.styleable#View_nextFocusForward
5579     */
5580    public int getNextFocusForwardId() {
5581        return mNextFocusForwardId;
5582    }
5583
5584    /**
5585     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
5586     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
5587     * decide automatically.
5588     *
5589     * @attr ref android.R.styleable#View_nextFocusForward
5590     */
5591    public void setNextFocusForwardId(int nextFocusForwardId) {
5592        mNextFocusForwardId = nextFocusForwardId;
5593    }
5594
5595    /**
5596     * Returns the visibility of this view and all of its ancestors
5597     *
5598     * @return True if this view and all of its ancestors are {@link #VISIBLE}
5599     */
5600    public boolean isShown() {
5601        View current = this;
5602        //noinspection ConstantConditions
5603        do {
5604            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5605                return false;
5606            }
5607            ViewParent parent = current.mParent;
5608            if (parent == null) {
5609                return false; // We are not attached to the view root
5610            }
5611            if (!(parent instanceof View)) {
5612                return true;
5613            }
5614            current = (View) parent;
5615        } while (current != null);
5616
5617        return false;
5618    }
5619
5620    /**
5621     * Called by the view hierarchy when the content insets for a window have
5622     * changed, to allow it to adjust its content to fit within those windows.
5623     * The content insets tell you the space that the status bar, input method,
5624     * and other system windows infringe on the application's window.
5625     *
5626     * <p>You do not normally need to deal with this function, since the default
5627     * window decoration given to applications takes care of applying it to the
5628     * content of the window.  If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}
5629     * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case,
5630     * and your content can be placed under those system elements.  You can then
5631     * use this method within your view hierarchy if you have parts of your UI
5632     * which you would like to ensure are not being covered.
5633     *
5634     * <p>The default implementation of this method simply applies the content
5635     * inset's to the view's padding, consuming that content (modifying the
5636     * insets to be 0), and returning true.  This behavior is off by default, but can
5637     * be enabled through {@link #setFitsSystemWindows(boolean)}.
5638     *
5639     * <p>This function's traversal down the hierarchy is depth-first.  The same content
5640     * insets object is propagated down the hierarchy, so any changes made to it will
5641     * be seen by all following views (including potentially ones above in
5642     * the hierarchy since this is a depth-first traversal).  The first view
5643     * that returns true will abort the entire traversal.
5644     *
5645     * <p>The default implementation works well for a situation where it is
5646     * used with a container that covers the entire window, allowing it to
5647     * apply the appropriate insets to its content on all edges.  If you need
5648     * a more complicated layout (such as two different views fitting system
5649     * windows, one on the top of the window, and one on the bottom),
5650     * you can override the method and handle the insets however you would like.
5651     * Note that the insets provided by the framework are always relative to the
5652     * far edges of the window, not accounting for the location of the called view
5653     * within that window.  (In fact when this method is called you do not yet know
5654     * where the layout will place the view, as it is done before layout happens.)
5655     *
5656     * <p>Note: unlike many View methods, there is no dispatch phase to this
5657     * call.  If you are overriding it in a ViewGroup and want to allow the
5658     * call to continue to your children, you must be sure to call the super
5659     * implementation.
5660     *
5661     * <p>Here is a sample layout that makes use of fitting system windows
5662     * to have controls for a video view placed inside of the window decorations
5663     * that it hides and shows.  This can be used with code like the second
5664     * sample (video player) shown in {@link #setSystemUiVisibility(int)}.
5665     *
5666     * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete}
5667     *
5668     * @param insets Current content insets of the window.  Prior to
5669     * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify
5670     * the insets or else you and Android will be unhappy.
5671     *
5672     * @return Return true if this view applied the insets and it should not
5673     * continue propagating further down the hierarchy, false otherwise.
5674     * @see #getFitsSystemWindows()
5675     * @see #setFitsSystemWindows(boolean)
5676     * @see #setSystemUiVisibility(int)
5677     */
5678    protected boolean fitSystemWindows(Rect insets) {
5679        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
5680            mUserPaddingStart = UNDEFINED_PADDING;
5681            mUserPaddingEnd = UNDEFINED_PADDING;
5682            Rect localInsets = sThreadLocal.get();
5683            if (localInsets == null) {
5684                localInsets = new Rect();
5685                sThreadLocal.set(localInsets);
5686            }
5687            boolean res = computeFitSystemWindows(insets, localInsets);
5688            internalSetPadding(localInsets.left, localInsets.top,
5689                    localInsets.right, localInsets.bottom);
5690            return res;
5691        }
5692        return false;
5693    }
5694
5695    /**
5696     * @hide Compute the insets that should be consumed by this view and the ones
5697     * that should propagate to those under it.
5698     */
5699    protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) {
5700        if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0
5701                || mAttachInfo == null
5702                || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0
5703                        && !mAttachInfo.mOverscanRequested)) {
5704            outLocalInsets.set(inoutInsets);
5705            inoutInsets.set(0, 0, 0, 0);
5706            return true;
5707        } else {
5708            // The application wants to take care of fitting system window for
5709            // the content...  however we still need to take care of any overscan here.
5710            final Rect overscan = mAttachInfo.mOverscanInsets;
5711            outLocalInsets.set(overscan);
5712            inoutInsets.left -= overscan.left;
5713            inoutInsets.top -= overscan.top;
5714            inoutInsets.right -= overscan.right;
5715            inoutInsets.bottom -= overscan.bottom;
5716            return false;
5717        }
5718    }
5719
5720    /**
5721     * Sets whether or not this view should account for system screen decorations
5722     * such as the status bar and inset its content; that is, controlling whether
5723     * the default implementation of {@link #fitSystemWindows(Rect)} will be
5724     * executed.  See that method for more details.
5725     *
5726     * <p>Note that if you are providing your own implementation of
5727     * {@link #fitSystemWindows(Rect)}, then there is no need to set this
5728     * flag to true -- your implementation will be overriding the default
5729     * implementation that checks this flag.
5730     *
5731     * @param fitSystemWindows If true, then the default implementation of
5732     * {@link #fitSystemWindows(Rect)} will be executed.
5733     *
5734     * @attr ref android.R.styleable#View_fitsSystemWindows
5735     * @see #getFitsSystemWindows()
5736     * @see #fitSystemWindows(Rect)
5737     * @see #setSystemUiVisibility(int)
5738     */
5739    public void setFitsSystemWindows(boolean fitSystemWindows) {
5740        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
5741    }
5742
5743    /**
5744     * Check for state of {@link #setFitsSystemWindows(boolean). If this method
5745     * returns true, the default implementation of {@link #fitSystemWindows(Rect)}
5746     * will be executed.
5747     *
5748     * @return Returns true if the default implementation of
5749     * {@link #fitSystemWindows(Rect)} will be executed.
5750     *
5751     * @attr ref android.R.styleable#View_fitsSystemWindows
5752     * @see #setFitsSystemWindows()
5753     * @see #fitSystemWindows(Rect)
5754     * @see #setSystemUiVisibility(int)
5755     */
5756    public boolean getFitsSystemWindows() {
5757        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
5758    }
5759
5760    /** @hide */
5761    public boolean fitsSystemWindows() {
5762        return getFitsSystemWindows();
5763    }
5764
5765    /**
5766     * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed.
5767     */
5768    public void requestFitSystemWindows() {
5769        if (mParent != null) {
5770            mParent.requestFitSystemWindows();
5771        }
5772    }
5773
5774    /**
5775     * For use by PhoneWindow to make its own system window fitting optional.
5776     * @hide
5777     */
5778    public void makeOptionalFitsSystemWindows() {
5779        setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS);
5780    }
5781
5782    /**
5783     * Returns the visibility status for this view.
5784     *
5785     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5786     * @attr ref android.R.styleable#View_visibility
5787     */
5788    @ViewDebug.ExportedProperty(mapping = {
5789        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
5790        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
5791        @ViewDebug.IntToString(from = GONE,      to = "GONE")
5792    })
5793    public int getVisibility() {
5794        return mViewFlags & VISIBILITY_MASK;
5795    }
5796
5797    /**
5798     * Set the enabled state of this view.
5799     *
5800     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
5801     * @attr ref android.R.styleable#View_visibility
5802     */
5803    @RemotableViewMethod
5804    public void setVisibility(int visibility) {
5805        setFlags(visibility, VISIBILITY_MASK);
5806        if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false);
5807    }
5808
5809    /**
5810     * Returns the enabled status for this view. The interpretation of the
5811     * enabled state varies by subclass.
5812     *
5813     * @return True if this view is enabled, false otherwise.
5814     */
5815    @ViewDebug.ExportedProperty
5816    public boolean isEnabled() {
5817        return (mViewFlags & ENABLED_MASK) == ENABLED;
5818    }
5819
5820    /**
5821     * Set the enabled state of this view. The interpretation of the enabled
5822     * state varies by subclass.
5823     *
5824     * @param enabled True if this view is enabled, false otherwise.
5825     */
5826    @RemotableViewMethod
5827    public void setEnabled(boolean enabled) {
5828        if (enabled == isEnabled()) return;
5829
5830        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
5831
5832        /*
5833         * The View most likely has to change its appearance, so refresh
5834         * the drawable state.
5835         */
5836        refreshDrawableState();
5837
5838        // Invalidate too, since the default behavior for views is to be
5839        // be drawn at 50% alpha rather than to change the drawable.
5840        invalidate(true);
5841    }
5842
5843    /**
5844     * Set whether this view can receive the focus.
5845     *
5846     * Setting this to false will also ensure that this view is not focusable
5847     * in touch mode.
5848     *
5849     * @param focusable If true, this view can receive the focus.
5850     *
5851     * @see #setFocusableInTouchMode(boolean)
5852     * @attr ref android.R.styleable#View_focusable
5853     */
5854    public void setFocusable(boolean focusable) {
5855        if (!focusable) {
5856            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
5857        }
5858        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
5859    }
5860
5861    /**
5862     * Set whether this view can receive focus while in touch mode.
5863     *
5864     * Setting this to true will also ensure that this view is focusable.
5865     *
5866     * @param focusableInTouchMode If true, this view can receive the focus while
5867     *   in touch mode.
5868     *
5869     * @see #setFocusable(boolean)
5870     * @attr ref android.R.styleable#View_focusableInTouchMode
5871     */
5872    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
5873        // Focusable in touch mode should always be set before the focusable flag
5874        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
5875        // which, in touch mode, will not successfully request focus on this view
5876        // because the focusable in touch mode flag is not set
5877        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
5878        if (focusableInTouchMode) {
5879            setFlags(FOCUSABLE, FOCUSABLE_MASK);
5880        }
5881    }
5882
5883    /**
5884     * Set whether this view should have sound effects enabled for events such as
5885     * clicking and touching.
5886     *
5887     * <p>You may wish to disable sound effects for a view if you already play sounds,
5888     * for instance, a dial key that plays dtmf tones.
5889     *
5890     * @param soundEffectsEnabled whether sound effects are enabled for this view.
5891     * @see #isSoundEffectsEnabled()
5892     * @see #playSoundEffect(int)
5893     * @attr ref android.R.styleable#View_soundEffectsEnabled
5894     */
5895    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
5896        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
5897    }
5898
5899    /**
5900     * @return whether this view should have sound effects enabled for events such as
5901     *     clicking and touching.
5902     *
5903     * @see #setSoundEffectsEnabled(boolean)
5904     * @see #playSoundEffect(int)
5905     * @attr ref android.R.styleable#View_soundEffectsEnabled
5906     */
5907    @ViewDebug.ExportedProperty
5908    public boolean isSoundEffectsEnabled() {
5909        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
5910    }
5911
5912    /**
5913     * Set whether this view should have haptic feedback for events such as
5914     * long presses.
5915     *
5916     * <p>You may wish to disable haptic feedback if your view already controls
5917     * its own haptic feedback.
5918     *
5919     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
5920     * @see #isHapticFeedbackEnabled()
5921     * @see #performHapticFeedback(int)
5922     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5923     */
5924    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
5925        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
5926    }
5927
5928    /**
5929     * @return whether this view should have haptic feedback enabled for events
5930     * long presses.
5931     *
5932     * @see #setHapticFeedbackEnabled(boolean)
5933     * @see #performHapticFeedback(int)
5934     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
5935     */
5936    @ViewDebug.ExportedProperty
5937    public boolean isHapticFeedbackEnabled() {
5938        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
5939    }
5940
5941    /**
5942     * Returns the layout direction for this view.
5943     *
5944     * @return One of {@link #LAYOUT_DIRECTION_LTR},
5945     *   {@link #LAYOUT_DIRECTION_RTL},
5946     *   {@link #LAYOUT_DIRECTION_INHERIT} or
5947     *   {@link #LAYOUT_DIRECTION_LOCALE}.
5948     *
5949     * @attr ref android.R.styleable#View_layoutDirection
5950     *
5951     * @hide
5952     */
5953    @ViewDebug.ExportedProperty(category = "layout", mapping = {
5954        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
5955        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
5956        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
5957        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
5958    })
5959    public int getRawLayoutDirection() {
5960        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT;
5961    }
5962
5963    /**
5964     * Set the layout direction for this view. This will propagate a reset of layout direction
5965     * resolution to the view's children and resolve layout direction for this view.
5966     *
5967     * @param layoutDirection the layout direction to set. Should be one of:
5968     *
5969     * {@link #LAYOUT_DIRECTION_LTR},
5970     * {@link #LAYOUT_DIRECTION_RTL},
5971     * {@link #LAYOUT_DIRECTION_INHERIT},
5972     * {@link #LAYOUT_DIRECTION_LOCALE}.
5973     *
5974     * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution
5975     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
5976     * will return the default {@link #LAYOUT_DIRECTION_LTR}.
5977     *
5978     * @attr ref android.R.styleable#View_layoutDirection
5979     */
5980    @RemotableViewMethod
5981    public void setLayoutDirection(int layoutDirection) {
5982        if (getRawLayoutDirection() != layoutDirection) {
5983            // Reset the current layout direction and the resolved one
5984            mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK;
5985            resetRtlProperties();
5986            // Set the new layout direction (filtered)
5987            mPrivateFlags2 |=
5988                    ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK);
5989            // We need to resolve all RTL properties as they all depend on layout direction
5990            resolveRtlPropertiesIfNeeded();
5991            requestLayout();
5992            invalidate(true);
5993        }
5994    }
5995
5996    /**
5997     * Returns the resolved layout direction for this view.
5998     *
5999     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
6000     * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL.
6001     *
6002     * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version
6003     * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}.
6004     *
6005     * @attr ref android.R.styleable#View_layoutDirection
6006     */
6007    @ViewDebug.ExportedProperty(category = "layout", mapping = {
6008        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"),
6009        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL")
6010    })
6011    public int getLayoutDirection() {
6012        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
6013        if (targetSdkVersion < JELLY_BEAN_MR1) {
6014            mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
6015            return LAYOUT_DIRECTION_RESOLVED_DEFAULT;
6016        }
6017        return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ==
6018                PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
6019    }
6020
6021    /**
6022     * Indicates whether or not this view's layout is right-to-left. This is resolved from
6023     * layout attribute and/or the inherited value from the parent
6024     *
6025     * @return true if the layout is right-to-left.
6026     *
6027     * @hide
6028     */
6029    @ViewDebug.ExportedProperty(category = "layout")
6030    public boolean isLayoutRtl() {
6031        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
6032    }
6033
6034    /**
6035     * Indicates whether the view is currently tracking transient state that the
6036     * app should not need to concern itself with saving and restoring, but that
6037     * the framework should take special note to preserve when possible.
6038     *
6039     * <p>A view with transient state cannot be trivially rebound from an external
6040     * data source, such as an adapter binding item views in a list. This may be
6041     * because the view is performing an animation, tracking user selection
6042     * of content, or similar.</p>
6043     *
6044     * @return true if the view has transient state
6045     */
6046    @ViewDebug.ExportedProperty(category = "layout")
6047    public boolean hasTransientState() {
6048        return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE;
6049    }
6050
6051    /**
6052     * Set whether this view is currently tracking transient state that the
6053     * framework should attempt to preserve when possible. This flag is reference counted,
6054     * so every call to setHasTransientState(true) should be paired with a later call
6055     * to setHasTransientState(false).
6056     *
6057     * <p>A view with transient state cannot be trivially rebound from an external
6058     * data source, such as an adapter binding item views in a list. This may be
6059     * because the view is performing an animation, tracking user selection
6060     * of content, or similar.</p>
6061     *
6062     * @param hasTransientState true if this view has transient state
6063     */
6064    public void setHasTransientState(boolean hasTransientState) {
6065        mTransientStateCount = hasTransientState ? mTransientStateCount + 1 :
6066                mTransientStateCount - 1;
6067        if (mTransientStateCount < 0) {
6068            mTransientStateCount = 0;
6069            Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " +
6070                    "unmatched pair of setHasTransientState calls");
6071        }
6072        if ((hasTransientState && mTransientStateCount == 1) ||
6073                (!hasTransientState && mTransientStateCount == 0)) {
6074            // update flag if we've just incremented up from 0 or decremented down to 0
6075            mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) |
6076                    (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0);
6077            if (mParent != null) {
6078                try {
6079                    mParent.childHasTransientStateChanged(this, hasTransientState);
6080                } catch (AbstractMethodError e) {
6081                    Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
6082                            " does not fully implement ViewParent", e);
6083                }
6084            }
6085        }
6086    }
6087
6088    /**
6089     * If this view doesn't do any drawing on its own, set this flag to
6090     * allow further optimizations. By default, this flag is not set on
6091     * View, but could be set on some View subclasses such as ViewGroup.
6092     *
6093     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
6094     * you should clear this flag.
6095     *
6096     * @param willNotDraw whether or not this View draw on its own
6097     */
6098    public void setWillNotDraw(boolean willNotDraw) {
6099        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
6100    }
6101
6102    /**
6103     * Returns whether or not this View draws on its own.
6104     *
6105     * @return true if this view has nothing to draw, false otherwise
6106     */
6107    @ViewDebug.ExportedProperty(category = "drawing")
6108    public boolean willNotDraw() {
6109        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
6110    }
6111
6112    /**
6113     * When a View's drawing cache is enabled, drawing is redirected to an
6114     * offscreen bitmap. Some views, like an ImageView, must be able to
6115     * bypass this mechanism if they already draw a single bitmap, to avoid
6116     * unnecessary usage of the memory.
6117     *
6118     * @param willNotCacheDrawing true if this view does not cache its
6119     *        drawing, false otherwise
6120     */
6121    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
6122        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
6123    }
6124
6125    /**
6126     * Returns whether or not this View can cache its drawing or not.
6127     *
6128     * @return true if this view does not cache its drawing, false otherwise
6129     */
6130    @ViewDebug.ExportedProperty(category = "drawing")
6131    public boolean willNotCacheDrawing() {
6132        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
6133    }
6134
6135    /**
6136     * Indicates whether this view reacts to click events or not.
6137     *
6138     * @return true if the view is clickable, false otherwise
6139     *
6140     * @see #setClickable(boolean)
6141     * @attr ref android.R.styleable#View_clickable
6142     */
6143    @ViewDebug.ExportedProperty
6144    public boolean isClickable() {
6145        return (mViewFlags & CLICKABLE) == CLICKABLE;
6146    }
6147
6148    /**
6149     * Enables or disables click events for this view. When a view
6150     * is clickable it will change its state to "pressed" on every click.
6151     * Subclasses should set the view clickable to visually react to
6152     * user's clicks.
6153     *
6154     * @param clickable true to make the view clickable, false otherwise
6155     *
6156     * @see #isClickable()
6157     * @attr ref android.R.styleable#View_clickable
6158     */
6159    public void setClickable(boolean clickable) {
6160        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
6161    }
6162
6163    /**
6164     * Indicates whether this view reacts to long click events or not.
6165     *
6166     * @return true if the view is long clickable, false otherwise
6167     *
6168     * @see #setLongClickable(boolean)
6169     * @attr ref android.R.styleable#View_longClickable
6170     */
6171    public boolean isLongClickable() {
6172        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6173    }
6174
6175    /**
6176     * Enables or disables long click events for this view. When a view is long
6177     * clickable it reacts to the user holding down the button for a longer
6178     * duration than a tap. This event can either launch the listener or a
6179     * context menu.
6180     *
6181     * @param longClickable true to make the view long clickable, false otherwise
6182     * @see #isLongClickable()
6183     * @attr ref android.R.styleable#View_longClickable
6184     */
6185    public void setLongClickable(boolean longClickable) {
6186        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
6187    }
6188
6189    /**
6190     * Sets the pressed state for this view.
6191     *
6192     * @see #isClickable()
6193     * @see #setClickable(boolean)
6194     *
6195     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
6196     *        the View's internal state from a previously set "pressed" state.
6197     */
6198    public void setPressed(boolean pressed) {
6199        final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED);
6200
6201        if (pressed) {
6202            mPrivateFlags |= PFLAG_PRESSED;
6203        } else {
6204            mPrivateFlags &= ~PFLAG_PRESSED;
6205        }
6206
6207        if (needsRefresh) {
6208            refreshDrawableState();
6209        }
6210        dispatchSetPressed(pressed);
6211    }
6212
6213    /**
6214     * Dispatch setPressed to all of this View's children.
6215     *
6216     * @see #setPressed(boolean)
6217     *
6218     * @param pressed The new pressed state
6219     */
6220    protected void dispatchSetPressed(boolean pressed) {
6221    }
6222
6223    /**
6224     * Indicates whether the view is currently in pressed state. Unless
6225     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
6226     * the pressed state.
6227     *
6228     * @see #setPressed(boolean)
6229     * @see #isClickable()
6230     * @see #setClickable(boolean)
6231     *
6232     * @return true if the view is currently pressed, false otherwise
6233     */
6234    public boolean isPressed() {
6235        return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED;
6236    }
6237
6238    /**
6239     * Indicates whether this view will save its state (that is,
6240     * whether its {@link #onSaveInstanceState} method will be called).
6241     *
6242     * @return Returns true if the view state saving is enabled, else false.
6243     *
6244     * @see #setSaveEnabled(boolean)
6245     * @attr ref android.R.styleable#View_saveEnabled
6246     */
6247    public boolean isSaveEnabled() {
6248        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
6249    }
6250
6251    /**
6252     * Controls whether the saving of this view's state is
6253     * enabled (that is, whether its {@link #onSaveInstanceState} method
6254     * will be called).  Note that even if freezing is enabled, the
6255     * view still must have an id assigned to it (via {@link #setId(int)})
6256     * for its state to be saved.  This flag can only disable the
6257     * saving of this view; any child views may still have their state saved.
6258     *
6259     * @param enabled Set to false to <em>disable</em> state saving, or true
6260     * (the default) to allow it.
6261     *
6262     * @see #isSaveEnabled()
6263     * @see #setId(int)
6264     * @see #onSaveInstanceState()
6265     * @attr ref android.R.styleable#View_saveEnabled
6266     */
6267    public void setSaveEnabled(boolean enabled) {
6268        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
6269    }
6270
6271    /**
6272     * Gets whether the framework should discard touches when the view's
6273     * window is obscured by another visible window.
6274     * Refer to the {@link View} security documentation for more details.
6275     *
6276     * @return True if touch filtering is enabled.
6277     *
6278     * @see #setFilterTouchesWhenObscured(boolean)
6279     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6280     */
6281    @ViewDebug.ExportedProperty
6282    public boolean getFilterTouchesWhenObscured() {
6283        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
6284    }
6285
6286    /**
6287     * Sets whether the framework should discard touches when the view's
6288     * window is obscured by another visible window.
6289     * Refer to the {@link View} security documentation for more details.
6290     *
6291     * @param enabled True if touch filtering should be enabled.
6292     *
6293     * @see #getFilterTouchesWhenObscured
6294     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
6295     */
6296    public void setFilterTouchesWhenObscured(boolean enabled) {
6297        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
6298                FILTER_TOUCHES_WHEN_OBSCURED);
6299    }
6300
6301    /**
6302     * Indicates whether the entire hierarchy under this view will save its
6303     * state when a state saving traversal occurs from its parent.  The default
6304     * is true; if false, these views will not be saved unless
6305     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6306     *
6307     * @return Returns true if the view state saving from parent is enabled, else false.
6308     *
6309     * @see #setSaveFromParentEnabled(boolean)
6310     */
6311    public boolean isSaveFromParentEnabled() {
6312        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
6313    }
6314
6315    /**
6316     * Controls whether the entire hierarchy under this view will save its
6317     * state when a state saving traversal occurs from its parent.  The default
6318     * is true; if false, these views will not be saved unless
6319     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
6320     *
6321     * @param enabled Set to false to <em>disable</em> state saving, or true
6322     * (the default) to allow it.
6323     *
6324     * @see #isSaveFromParentEnabled()
6325     * @see #setId(int)
6326     * @see #onSaveInstanceState()
6327     */
6328    public void setSaveFromParentEnabled(boolean enabled) {
6329        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
6330    }
6331
6332
6333    /**
6334     * Returns whether this View is able to take focus.
6335     *
6336     * @return True if this view can take focus, or false otherwise.
6337     * @attr ref android.R.styleable#View_focusable
6338     */
6339    @ViewDebug.ExportedProperty(category = "focus")
6340    public final boolean isFocusable() {
6341        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
6342    }
6343
6344    /**
6345     * When a view is focusable, it may not want to take focus when in touch mode.
6346     * For example, a button would like focus when the user is navigating via a D-pad
6347     * so that the user can click on it, but once the user starts touching the screen,
6348     * the button shouldn't take focus
6349     * @return Whether the view is focusable in touch mode.
6350     * @attr ref android.R.styleable#View_focusableInTouchMode
6351     */
6352    @ViewDebug.ExportedProperty
6353    public final boolean isFocusableInTouchMode() {
6354        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
6355    }
6356
6357    /**
6358     * Find the nearest view in the specified direction that can take focus.
6359     * This does not actually give focus to that view.
6360     *
6361     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6362     *
6363     * @return The nearest focusable in the specified direction, or null if none
6364     *         can be found.
6365     */
6366    public View focusSearch(int direction) {
6367        if (mParent != null) {
6368            return mParent.focusSearch(this, direction);
6369        } else {
6370            return null;
6371        }
6372    }
6373
6374    /**
6375     * This method is the last chance for the focused view and its ancestors to
6376     * respond to an arrow key. This is called when the focused view did not
6377     * consume the key internally, nor could the view system find a new view in
6378     * the requested direction to give focus to.
6379     *
6380     * @param focused The currently focused view.
6381     * @param direction The direction focus wants to move. One of FOCUS_UP,
6382     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
6383     * @return True if the this view consumed this unhandled move.
6384     */
6385    public boolean dispatchUnhandledMove(View focused, int direction) {
6386        return false;
6387    }
6388
6389    /**
6390     * If a user manually specified the next view id for a particular direction,
6391     * use the root to look up the view.
6392     * @param root The root view of the hierarchy containing this view.
6393     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
6394     * or FOCUS_BACKWARD.
6395     * @return The user specified next view, or null if there is none.
6396     */
6397    View findUserSetNextFocus(View root, int direction) {
6398        switch (direction) {
6399            case FOCUS_LEFT:
6400                if (mNextFocusLeftId == View.NO_ID) return null;
6401                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
6402            case FOCUS_RIGHT:
6403                if (mNextFocusRightId == View.NO_ID) return null;
6404                return findViewInsideOutShouldExist(root, mNextFocusRightId);
6405            case FOCUS_UP:
6406                if (mNextFocusUpId == View.NO_ID) return null;
6407                return findViewInsideOutShouldExist(root, mNextFocusUpId);
6408            case FOCUS_DOWN:
6409                if (mNextFocusDownId == View.NO_ID) return null;
6410                return findViewInsideOutShouldExist(root, mNextFocusDownId);
6411            case FOCUS_FORWARD:
6412                if (mNextFocusForwardId == View.NO_ID) return null;
6413                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
6414            case FOCUS_BACKWARD: {
6415                if (mID == View.NO_ID) return null;
6416                final int id = mID;
6417                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
6418                    @Override
6419                    public boolean apply(View t) {
6420                        return t.mNextFocusForwardId == id;
6421                    }
6422                });
6423            }
6424        }
6425        return null;
6426    }
6427
6428    private View findViewInsideOutShouldExist(View root, int id) {
6429        if (mMatchIdPredicate == null) {
6430            mMatchIdPredicate = new MatchIdPredicate();
6431        }
6432        mMatchIdPredicate.mId = id;
6433        View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate);
6434        if (result == null) {
6435            Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id);
6436        }
6437        return result;
6438    }
6439
6440    /**
6441     * Find and return all focusable views that are descendants of this view,
6442     * possibly including this view if it is focusable itself.
6443     *
6444     * @param direction The direction of the focus
6445     * @return A list of focusable views
6446     */
6447    public ArrayList<View> getFocusables(int direction) {
6448        ArrayList<View> result = new ArrayList<View>(24);
6449        addFocusables(result, direction);
6450        return result;
6451    }
6452
6453    /**
6454     * Add any focusable views that are descendants of this view (possibly
6455     * including this view if it is focusable itself) to views.  If we are in touch mode,
6456     * only add views that are also focusable in touch mode.
6457     *
6458     * @param views Focusable views found so far
6459     * @param direction The direction of the focus
6460     */
6461    public void addFocusables(ArrayList<View> views, int direction) {
6462        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
6463    }
6464
6465    /**
6466     * Adds any focusable views that are descendants of this view (possibly
6467     * including this view if it is focusable itself) to views. This method
6468     * adds all focusable views regardless if we are in touch mode or
6469     * only views focusable in touch mode if we are in touch mode or
6470     * only views that can take accessibility focus if accessibility is enabeld
6471     * depending on the focusable mode paramater.
6472     *
6473     * @param views Focusable views found so far or null if all we are interested is
6474     *        the number of focusables.
6475     * @param direction The direction of the focus.
6476     * @param focusableMode The type of focusables to be added.
6477     *
6478     * @see #FOCUSABLES_ALL
6479     * @see #FOCUSABLES_TOUCH_MODE
6480     */
6481    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
6482        if (views == null) {
6483            return;
6484        }
6485        if (!isFocusable()) {
6486            return;
6487        }
6488        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE
6489                && isInTouchMode() && !isFocusableInTouchMode()) {
6490            return;
6491        }
6492        views.add(this);
6493    }
6494
6495    /**
6496     * Finds the Views that contain given text. The containment is case insensitive.
6497     * The search is performed by either the text that the View renders or the content
6498     * description that describes the view for accessibility purposes and the view does
6499     * not render or both. Clients can specify how the search is to be performed via
6500     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
6501     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
6502     *
6503     * @param outViews The output list of matching Views.
6504     * @param searched The text to match against.
6505     *
6506     * @see #FIND_VIEWS_WITH_TEXT
6507     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
6508     * @see #setContentDescription(CharSequence)
6509     */
6510    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
6511        if (getAccessibilityNodeProvider() != null) {
6512            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
6513                outViews.add(this);
6514            }
6515        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
6516                && (searched != null && searched.length() > 0)
6517                && (mContentDescription != null && mContentDescription.length() > 0)) {
6518            String searchedLowerCase = searched.toString().toLowerCase();
6519            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
6520            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
6521                outViews.add(this);
6522            }
6523        }
6524    }
6525
6526    /**
6527     * Find and return all touchable views that are descendants of this view,
6528     * possibly including this view if it is touchable itself.
6529     *
6530     * @return A list of touchable views
6531     */
6532    public ArrayList<View> getTouchables() {
6533        ArrayList<View> result = new ArrayList<View>();
6534        addTouchables(result);
6535        return result;
6536    }
6537
6538    /**
6539     * Add any touchable views that are descendants of this view (possibly
6540     * including this view if it is touchable itself) to views.
6541     *
6542     * @param views Touchable views found so far
6543     */
6544    public void addTouchables(ArrayList<View> views) {
6545        final int viewFlags = mViewFlags;
6546
6547        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
6548                && (viewFlags & ENABLED_MASK) == ENABLED) {
6549            views.add(this);
6550        }
6551    }
6552
6553    /**
6554     * Returns whether this View is accessibility focused.
6555     *
6556     * @return True if this View is accessibility focused.
6557     */
6558    boolean isAccessibilityFocused() {
6559        return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0;
6560    }
6561
6562    /**
6563     * Call this to try to give accessibility focus to this view.
6564     *
6565     * A view will not actually take focus if {@link AccessibilityManager#isEnabled()}
6566     * returns false or the view is no visible or the view already has accessibility
6567     * focus.
6568     *
6569     * See also {@link #focusSearch(int)}, which is what you call to say that you
6570     * have focus, and you want your parent to look for the next one.
6571     *
6572     * @return Whether this view actually took accessibility focus.
6573     *
6574     * @hide
6575     */
6576    public boolean requestAccessibilityFocus() {
6577        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
6578        if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) {
6579            return false;
6580        }
6581        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6582            return false;
6583        }
6584        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) {
6585            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED;
6586            ViewRootImpl viewRootImpl = getViewRootImpl();
6587            if (viewRootImpl != null) {
6588                viewRootImpl.setAccessibilityFocus(this, null);
6589            }
6590            invalidate();
6591            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED);
6592            notifyAccessibilityStateChanged();
6593            return true;
6594        }
6595        return false;
6596    }
6597
6598    /**
6599     * Call this to try to clear accessibility focus of this view.
6600     *
6601     * See also {@link #focusSearch(int)}, which is what you call to say that you
6602     * have focus, and you want your parent to look for the next one.
6603     *
6604     * @hide
6605     */
6606    public void clearAccessibilityFocus() {
6607        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6608            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6609            invalidate();
6610            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED);
6611            notifyAccessibilityStateChanged();
6612        }
6613        // Clear the global reference of accessibility focus if this
6614        // view or any of its descendants had accessibility focus.
6615        ViewRootImpl viewRootImpl = getViewRootImpl();
6616        if (viewRootImpl != null) {
6617            View focusHost = viewRootImpl.getAccessibilityFocusedHost();
6618            if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) {
6619                viewRootImpl.setAccessibilityFocus(null, null);
6620            }
6621        }
6622    }
6623
6624    private void sendAccessibilityHoverEvent(int eventType) {
6625        // Since we are not delivering to a client accessibility events from not
6626        // important views (unless the clinet request that) we need to fire the
6627        // event from the deepest view exposed to the client. As a consequence if
6628        // the user crosses a not exposed view the client will see enter and exit
6629        // of the exposed predecessor followed by and enter and exit of that same
6630        // predecessor when entering and exiting the not exposed descendant. This
6631        // is fine since the client has a clear idea which view is hovered at the
6632        // price of a couple more events being sent. This is a simple and
6633        // working solution.
6634        View source = this;
6635        while (true) {
6636            if (source.includeForAccessibility()) {
6637                source.sendAccessibilityEvent(eventType);
6638                return;
6639            }
6640            ViewParent parent = source.getParent();
6641            if (parent instanceof View) {
6642                source = (View) parent;
6643            } else {
6644                return;
6645            }
6646        }
6647    }
6648
6649    /**
6650     * Clears accessibility focus without calling any callback methods
6651     * normally invoked in {@link #clearAccessibilityFocus()}. This method
6652     * is used for clearing accessibility focus when giving this focus to
6653     * another view.
6654     */
6655    void clearAccessibilityFocusNoCallbacks() {
6656        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) {
6657            mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED;
6658            invalidate();
6659        }
6660    }
6661
6662    /**
6663     * Call this to try to give focus to a specific view or to one of its
6664     * descendants.
6665     *
6666     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6667     * false), or if it is focusable and it is not focusable in touch mode
6668     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6669     *
6670     * See also {@link #focusSearch(int)}, which is what you call to say that you
6671     * have focus, and you want your parent to look for the next one.
6672     *
6673     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
6674     * {@link #FOCUS_DOWN} and <code>null</code>.
6675     *
6676     * @return Whether this view or one of its descendants actually took focus.
6677     */
6678    public final boolean requestFocus() {
6679        return requestFocus(View.FOCUS_DOWN);
6680    }
6681
6682    /**
6683     * Call this to try to give focus to a specific view or to one of its
6684     * descendants and give it a hint about what direction focus is heading.
6685     *
6686     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6687     * false), or if it is focusable and it is not focusable in touch mode
6688     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6689     *
6690     * See also {@link #focusSearch(int)}, which is what you call to say that you
6691     * have focus, and you want your parent to look for the next one.
6692     *
6693     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
6694     * <code>null</code> set for the previously focused rectangle.
6695     *
6696     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6697     * @return Whether this view or one of its descendants actually took focus.
6698     */
6699    public final boolean requestFocus(int direction) {
6700        return requestFocus(direction, null);
6701    }
6702
6703    /**
6704     * Call this to try to give focus to a specific view or to one of its descendants
6705     * and give it hints about the direction and a specific rectangle that the focus
6706     * is coming from.  The rectangle can help give larger views a finer grained hint
6707     * about where focus is coming from, and therefore, where to show selection, or
6708     * forward focus change internally.
6709     *
6710     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
6711     * false), or if it is focusable and it is not focusable in touch mode
6712     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
6713     *
6714     * A View will not take focus if it is not visible.
6715     *
6716     * A View will not take focus if one of its parents has
6717     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
6718     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
6719     *
6720     * See also {@link #focusSearch(int)}, which is what you call to say that you
6721     * have focus, and you want your parent to look for the next one.
6722     *
6723     * You may wish to override this method if your custom {@link View} has an internal
6724     * {@link View} that it wishes to forward the request to.
6725     *
6726     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
6727     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
6728     *        to give a finer grained hint about where focus is coming from.  May be null
6729     *        if there is no hint.
6730     * @return Whether this view or one of its descendants actually took focus.
6731     */
6732    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6733        return requestFocusNoSearch(direction, previouslyFocusedRect);
6734    }
6735
6736    private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) {
6737        // need to be focusable
6738        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
6739                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
6740            return false;
6741        }
6742
6743        // need to be focusable in touch mode if in touch mode
6744        if (isInTouchMode() &&
6745            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
6746               return false;
6747        }
6748
6749        // need to not have any parents blocking us
6750        if (hasAncestorThatBlocksDescendantFocus()) {
6751            return false;
6752        }
6753
6754        handleFocusGainInternal(direction, previouslyFocusedRect);
6755        return true;
6756    }
6757
6758    /**
6759     * Call this to try to give focus to a specific view or to one of its descendants. This is a
6760     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
6761     * touch mode to request focus when they are touched.
6762     *
6763     * @return Whether this view or one of its descendants actually took focus.
6764     *
6765     * @see #isInTouchMode()
6766     *
6767     */
6768    public final boolean requestFocusFromTouch() {
6769        // Leave touch mode if we need to
6770        if (isInTouchMode()) {
6771            ViewRootImpl viewRoot = getViewRootImpl();
6772            if (viewRoot != null) {
6773                viewRoot.ensureTouchMode(false);
6774            }
6775        }
6776        return requestFocus(View.FOCUS_DOWN);
6777    }
6778
6779    /**
6780     * @return Whether any ancestor of this view blocks descendant focus.
6781     */
6782    private boolean hasAncestorThatBlocksDescendantFocus() {
6783        ViewParent ancestor = mParent;
6784        while (ancestor instanceof ViewGroup) {
6785            final ViewGroup vgAncestor = (ViewGroup) ancestor;
6786            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
6787                return true;
6788            } else {
6789                ancestor = vgAncestor.getParent();
6790            }
6791        }
6792        return false;
6793    }
6794
6795    /**
6796     * Gets the mode for determining whether this View is important for accessibility
6797     * which is if it fires accessibility events and if it is reported to
6798     * accessibility services that query the screen.
6799     *
6800     * @return The mode for determining whether a View is important for accessibility.
6801     *
6802     * @attr ref android.R.styleable#View_importantForAccessibility
6803     *
6804     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6805     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6806     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6807     */
6808    @ViewDebug.ExportedProperty(category = "accessibility", mapping = {
6809            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"),
6810            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"),
6811            @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no")
6812        })
6813    public int getImportantForAccessibility() {
6814        return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6815                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6816    }
6817
6818    /**
6819     * Sets how to determine whether this view is important for accessibility
6820     * which is if it fires accessibility events and if it is reported to
6821     * accessibility services that query the screen.
6822     *
6823     * @param mode How to determine whether this view is important for accessibility.
6824     *
6825     * @attr ref android.R.styleable#View_importantForAccessibility
6826     *
6827     * @see #IMPORTANT_FOR_ACCESSIBILITY_YES
6828     * @see #IMPORTANT_FOR_ACCESSIBILITY_NO
6829     * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO
6830     */
6831    public void setImportantForAccessibility(int mode) {
6832        if (mode != getImportantForAccessibility()) {
6833            mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6834            mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT)
6835                    & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK;
6836            notifyAccessibilityStateChanged();
6837        }
6838    }
6839
6840    /**
6841     * Gets whether this view should be exposed for accessibility.
6842     *
6843     * @return Whether the view is exposed for accessibility.
6844     *
6845     * @hide
6846     */
6847    public boolean isImportantForAccessibility() {
6848        final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK)
6849                >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT;
6850        switch (mode) {
6851            case IMPORTANT_FOR_ACCESSIBILITY_YES:
6852                return true;
6853            case IMPORTANT_FOR_ACCESSIBILITY_NO:
6854                return false;
6855            case IMPORTANT_FOR_ACCESSIBILITY_AUTO:
6856                return isActionableForAccessibility() || hasListenersForAccessibility()
6857                        || getAccessibilityNodeProvider() != null;
6858            default:
6859                throw new IllegalArgumentException("Unknow important for accessibility mode: "
6860                        + mode);
6861        }
6862    }
6863
6864    /**
6865     * Gets the parent for accessibility purposes. Note that the parent for
6866     * accessibility is not necessary the immediate parent. It is the first
6867     * predecessor that is important for accessibility.
6868     *
6869     * @return The parent for accessibility purposes.
6870     */
6871    public ViewParent getParentForAccessibility() {
6872        if (mParent instanceof View) {
6873            View parentView = (View) mParent;
6874            if (parentView.includeForAccessibility()) {
6875                return mParent;
6876            } else {
6877                return mParent.getParentForAccessibility();
6878            }
6879        }
6880        return null;
6881    }
6882
6883    /**
6884     * Adds the children of a given View for accessibility. Since some Views are
6885     * not important for accessibility the children for accessibility are not
6886     * necessarily direct children of the riew, rather they are the first level of
6887     * descendants important for accessibility.
6888     *
6889     * @param children The list of children for accessibility.
6890     */
6891    public void addChildrenForAccessibility(ArrayList<View> children) {
6892        if (includeForAccessibility()) {
6893            children.add(this);
6894        }
6895    }
6896
6897    /**
6898     * Whether to regard this view for accessibility. A view is regarded for
6899     * accessibility if it is important for accessibility or the querying
6900     * accessibility service has explicitly requested that view not
6901     * important for accessibility are regarded.
6902     *
6903     * @return Whether to regard the view for accessibility.
6904     *
6905     * @hide
6906     */
6907    public boolean includeForAccessibility() {
6908        if (mAttachInfo != null) {
6909            return (mAttachInfo.mAccessibilityFetchFlags
6910                    & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0
6911                    || isImportantForAccessibility();
6912        }
6913        return false;
6914    }
6915
6916    /**
6917     * Returns whether the View is considered actionable from
6918     * accessibility perspective. Such view are important for
6919     * accessibility.
6920     *
6921     * @return True if the view is actionable for accessibility.
6922     *
6923     * @hide
6924     */
6925    public boolean isActionableForAccessibility() {
6926        return (isClickable() || isLongClickable() || isFocusable());
6927    }
6928
6929    /**
6930     * Returns whether the View has registered callbacks wich makes it
6931     * important for accessibility.
6932     *
6933     * @return True if the view is actionable for accessibility.
6934     */
6935    private boolean hasListenersForAccessibility() {
6936        ListenerInfo info = getListenerInfo();
6937        return mTouchDelegate != null || info.mOnKeyListener != null
6938                || info.mOnTouchListener != null || info.mOnGenericMotionListener != null
6939                || info.mOnHoverListener != null || info.mOnDragListener != null;
6940    }
6941
6942    /**
6943     * Notifies accessibility services that some view's important for
6944     * accessibility state has changed. Note that such notifications
6945     * are made at most once every
6946     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}
6947     * to avoid unnecessary load to the system. Also once a view has
6948     * made a notifucation this method is a NOP until the notification has
6949     * been sent to clients.
6950     *
6951     * @hide
6952     *
6953     * TODO: Makse sure this method is called for any view state change
6954     *       that is interesting for accessilility purposes.
6955     */
6956    public void notifyAccessibilityStateChanged() {
6957        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
6958            return;
6959        }
6960        if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_STATE_CHANGED) == 0) {
6961            mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6962            if (mParent != null) {
6963                mParent.childAccessibilityStateChanged(this);
6964            }
6965        }
6966    }
6967
6968    /**
6969     * Reset the state indicating the this view has requested clients
6970     * interested in its accessibility state to be notified.
6971     *
6972     * @hide
6973     */
6974    public void resetAccessibilityStateChanged() {
6975        mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_STATE_CHANGED;
6976    }
6977
6978    /**
6979     * Performs the specified accessibility action on the view. For
6980     * possible accessibility actions look at {@link AccessibilityNodeInfo}.
6981     * <p>
6982     * If an {@link AccessibilityDelegate} has been specified via calling
6983     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
6984     * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)}
6985     * is responsible for handling this call.
6986     * </p>
6987     *
6988     * @param action The action to perform.
6989     * @param arguments Optional action arguments.
6990     * @return Whether the action was performed.
6991     */
6992    public boolean performAccessibilityAction(int action, Bundle arguments) {
6993      if (mAccessibilityDelegate != null) {
6994          return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments);
6995      } else {
6996          return performAccessibilityActionInternal(action, arguments);
6997      }
6998    }
6999
7000   /**
7001    * @see #performAccessibilityAction(int, Bundle)
7002    *
7003    * Note: Called from the default {@link AccessibilityDelegate}.
7004    */
7005    boolean performAccessibilityActionInternal(int action, Bundle arguments) {
7006        switch (action) {
7007            case AccessibilityNodeInfo.ACTION_CLICK: {
7008                if (isClickable()) {
7009                    performClick();
7010                    return true;
7011                }
7012            } break;
7013            case AccessibilityNodeInfo.ACTION_LONG_CLICK: {
7014                if (isLongClickable()) {
7015                    performLongClick();
7016                    return true;
7017                }
7018            } break;
7019            case AccessibilityNodeInfo.ACTION_FOCUS: {
7020                if (!hasFocus()) {
7021                    // Get out of touch mode since accessibility
7022                    // wants to move focus around.
7023                    getViewRootImpl().ensureTouchMode(false);
7024                    return requestFocus();
7025                }
7026            } break;
7027            case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: {
7028                if (hasFocus()) {
7029                    clearFocus();
7030                    return !isFocused();
7031                }
7032            } break;
7033            case AccessibilityNodeInfo.ACTION_SELECT: {
7034                if (!isSelected()) {
7035                    setSelected(true);
7036                    return isSelected();
7037                }
7038            } break;
7039            case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: {
7040                if (isSelected()) {
7041                    setSelected(false);
7042                    return !isSelected();
7043                }
7044            } break;
7045            case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: {
7046                if (!isAccessibilityFocused()) {
7047                    return requestAccessibilityFocus();
7048                }
7049            } break;
7050            case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: {
7051                if (isAccessibilityFocused()) {
7052                    clearAccessibilityFocus();
7053                    return true;
7054                }
7055            } break;
7056            case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: {
7057                if (arguments != null) {
7058                    final int granularity = arguments.getInt(
7059                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7060                    final boolean extendSelection = arguments.getBoolean(
7061                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7062                    return nextAtGranularity(granularity, extendSelection);
7063                }
7064            } break;
7065            case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: {
7066                if (arguments != null) {
7067                    final int granularity = arguments.getInt(
7068                            AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT);
7069                    final boolean extendSelection = arguments.getBoolean(
7070                            AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN);
7071                    return previousAtGranularity(granularity, extendSelection);
7072                }
7073            } break;
7074            case AccessibilityNodeInfo.ACTION_SET_SELECTION: {
7075                CharSequence text = getIterableTextForAccessibility();
7076                if (text == null) {
7077                    return false;
7078                }
7079                final int start = (arguments != null) ? arguments.getInt(
7080                        AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1;
7081                final int end = (arguments != null) ? arguments.getInt(
7082                AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1;
7083                // Only cursor position can be specified (selection length == 0)
7084                if ((getAccessibilitySelectionStart() != start
7085                        || getAccessibilitySelectionEnd() != end)
7086                        && (start == end)) {
7087                    setAccessibilitySelection(start, end);
7088                    notifyAccessibilityStateChanged();
7089                    return true;
7090                }
7091            } break;
7092        }
7093        return false;
7094    }
7095
7096    private boolean nextAtGranularity(int granularity, boolean extendSelection) {
7097        CharSequence text = getIterableTextForAccessibility();
7098        if (text == null || text.length() == 0) {
7099            return false;
7100        }
7101        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7102        if (iterator == null) {
7103            return false;
7104        }
7105        int current = getAccessibilitySelectionEnd();
7106        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7107            current = 0;
7108        }
7109        final int[] range = iterator.following(current);
7110        if (range == null) {
7111            return false;
7112        }
7113        final int start = range[0];
7114        final int end = range[1];
7115        if (extendSelection && isAccessibilitySelectionExtendable()) {
7116            int selectionStart = getAccessibilitySelectionStart();
7117            if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7118                selectionStart = start;
7119            }
7120            setAccessibilitySelection(selectionStart, end);
7121        } else {
7122            setAccessibilitySelection(end, end);
7123        }
7124        sendViewTextTraversedAtGranularityEvent(
7125                AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY,
7126                granularity, start, end);
7127        return true;
7128    }
7129
7130    private boolean previousAtGranularity(int granularity, boolean extendSelection) {
7131        CharSequence text = getIterableTextForAccessibility();
7132        if (text == null || text.length() == 0) {
7133            return false;
7134        }
7135        TextSegmentIterator iterator = getIteratorForGranularity(granularity);
7136        if (iterator == null) {
7137            return false;
7138        }
7139        int current = getAccessibilitySelectionStart();
7140        if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7141            current = text.length();
7142        }
7143        final int[] range = iterator.preceding(current);
7144        if (range == null) {
7145            return false;
7146        }
7147        final int start = range[0];
7148        final int end = range[1];
7149        if (extendSelection && isAccessibilitySelectionExtendable()) {
7150            int selectionEnd = getAccessibilitySelectionEnd();
7151            if (selectionEnd == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) {
7152                selectionEnd = end;
7153            }
7154            setAccessibilitySelection(start, selectionEnd);
7155        } else {
7156            setAccessibilitySelection(start, start);
7157        }
7158        sendViewTextTraversedAtGranularityEvent(
7159                AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY,
7160                granularity, start, end);
7161        return true;
7162    }
7163
7164    /**
7165     * Gets the text reported for accessibility purposes.
7166     *
7167     * @return The accessibility text.
7168     *
7169     * @hide
7170     */
7171    public CharSequence getIterableTextForAccessibility() {
7172        return getContentDescription();
7173    }
7174
7175    /**
7176     * Gets whether accessibility selection can be extended.
7177     *
7178     * @return If selection is extensible.
7179     *
7180     * @hide
7181     */
7182    public boolean isAccessibilitySelectionExtendable() {
7183        return false;
7184    }
7185
7186    /**
7187     * @hide
7188     */
7189    public int getAccessibilitySelectionStart() {
7190        return mAccessibilityCursorPosition;
7191    }
7192
7193    /**
7194     * @hide
7195     */
7196    public int getAccessibilitySelectionEnd() {
7197        return getAccessibilitySelectionStart();
7198    }
7199
7200    /**
7201     * @hide
7202     */
7203    public void setAccessibilitySelection(int start, int end) {
7204        if (start ==  end && end == mAccessibilityCursorPosition) {
7205            return;
7206        }
7207        if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) {
7208            mAccessibilityCursorPosition = start;
7209        } else {
7210            mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED;
7211        }
7212        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED);
7213    }
7214
7215    private void sendViewTextTraversedAtGranularityEvent(int action, int granularity,
7216            int fromIndex, int toIndex) {
7217        if (mParent == null) {
7218            return;
7219        }
7220        AccessibilityEvent event = AccessibilityEvent.obtain(
7221                AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY);
7222        onInitializeAccessibilityEvent(event);
7223        onPopulateAccessibilityEvent(event);
7224        event.setFromIndex(fromIndex);
7225        event.setToIndex(toIndex);
7226        event.setAction(action);
7227        event.setMovementGranularity(granularity);
7228        mParent.requestSendAccessibilityEvent(this, event);
7229    }
7230
7231    /**
7232     * @hide
7233     */
7234    public TextSegmentIterator getIteratorForGranularity(int granularity) {
7235        switch (granularity) {
7236            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: {
7237                CharSequence text = getIterableTextForAccessibility();
7238                if (text != null && text.length() > 0) {
7239                    CharacterTextSegmentIterator iterator =
7240                        CharacterTextSegmentIterator.getInstance(
7241                                mContext.getResources().getConfiguration().locale);
7242                    iterator.initialize(text.toString());
7243                    return iterator;
7244                }
7245            } break;
7246            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: {
7247                CharSequence text = getIterableTextForAccessibility();
7248                if (text != null && text.length() > 0) {
7249                    WordTextSegmentIterator iterator =
7250                        WordTextSegmentIterator.getInstance(
7251                                mContext.getResources().getConfiguration().locale);
7252                    iterator.initialize(text.toString());
7253                    return iterator;
7254                }
7255            } break;
7256            case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: {
7257                CharSequence text = getIterableTextForAccessibility();
7258                if (text != null && text.length() > 0) {
7259                    ParagraphTextSegmentIterator iterator =
7260                        ParagraphTextSegmentIterator.getInstance();
7261                    iterator.initialize(text.toString());
7262                    return iterator;
7263                }
7264            } break;
7265        }
7266        return null;
7267    }
7268
7269    /**
7270     * @hide
7271     */
7272    public void dispatchStartTemporaryDetach() {
7273        clearAccessibilityFocus();
7274        clearDisplayList();
7275
7276        onStartTemporaryDetach();
7277    }
7278
7279    /**
7280     * This is called when a container is going to temporarily detach a child, with
7281     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
7282     * It will either be followed by {@link #onFinishTemporaryDetach()} or
7283     * {@link #onDetachedFromWindow()} when the container is done.
7284     */
7285    public void onStartTemporaryDetach() {
7286        removeUnsetPressCallback();
7287        mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT;
7288    }
7289
7290    /**
7291     * @hide
7292     */
7293    public void dispatchFinishTemporaryDetach() {
7294        onFinishTemporaryDetach();
7295    }
7296
7297    /**
7298     * Called after {@link #onStartTemporaryDetach} when the container is done
7299     * changing the view.
7300     */
7301    public void onFinishTemporaryDetach() {
7302    }
7303
7304    /**
7305     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
7306     * for this view's window.  Returns null if the view is not currently attached
7307     * to the window.  Normally you will not need to use this directly, but
7308     * just use the standard high-level event callbacks like
7309     * {@link #onKeyDown(int, KeyEvent)}.
7310     */
7311    public KeyEvent.DispatcherState getKeyDispatcherState() {
7312        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
7313    }
7314
7315    /**
7316     * Dispatch a key event before it is processed by any input method
7317     * associated with the view hierarchy.  This can be used to intercept
7318     * key events in special situations before the IME consumes them; a
7319     * typical example would be handling the BACK key to update the application's
7320     * UI instead of allowing the IME to see it and close itself.
7321     *
7322     * @param event The key event to be dispatched.
7323     * @return True if the event was handled, false otherwise.
7324     */
7325    public boolean dispatchKeyEventPreIme(KeyEvent event) {
7326        return onKeyPreIme(event.getKeyCode(), event);
7327    }
7328
7329    /**
7330     * Dispatch a key event to the next view on the focus path. This path runs
7331     * from the top of the view tree down to the currently focused view. If this
7332     * view has focus, it will dispatch to itself. Otherwise it will dispatch
7333     * the next node down the focus path. This method also fires any key
7334     * listeners.
7335     *
7336     * @param event The key event to be dispatched.
7337     * @return True if the event was handled, false otherwise.
7338     */
7339    public boolean dispatchKeyEvent(KeyEvent event) {
7340        if (mInputEventConsistencyVerifier != null) {
7341            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
7342        }
7343
7344        // Give any attached key listener a first crack at the event.
7345        //noinspection SimplifiableIfStatement
7346        ListenerInfo li = mListenerInfo;
7347        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7348                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
7349            return true;
7350        }
7351
7352        if (event.dispatch(this, mAttachInfo != null
7353                ? mAttachInfo.mKeyDispatchState : null, this)) {
7354            return true;
7355        }
7356
7357        if (mInputEventConsistencyVerifier != null) {
7358            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7359        }
7360        return false;
7361    }
7362
7363    /**
7364     * Dispatches a key shortcut event.
7365     *
7366     * @param event The key event to be dispatched.
7367     * @return True if the event was handled by the view, false otherwise.
7368     */
7369    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
7370        return onKeyShortcut(event.getKeyCode(), event);
7371    }
7372
7373    /**
7374     * Pass the touch screen motion event down to the target view, or this
7375     * view if it is the target.
7376     *
7377     * @param event The motion event to be dispatched.
7378     * @return True if the event was handled by the view, false otherwise.
7379     */
7380    public boolean dispatchTouchEvent(MotionEvent event) {
7381        if (mInputEventConsistencyVerifier != null) {
7382            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
7383        }
7384
7385        if (onFilterTouchEventForSecurity(event)) {
7386            //noinspection SimplifiableIfStatement
7387            ListenerInfo li = mListenerInfo;
7388            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
7389                    && li.mOnTouchListener.onTouch(this, event)) {
7390                return true;
7391            }
7392
7393            if (onTouchEvent(event)) {
7394                return true;
7395            }
7396        }
7397
7398        if (mInputEventConsistencyVerifier != null) {
7399            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7400        }
7401        return false;
7402    }
7403
7404    /**
7405     * Filter the touch event to apply security policies.
7406     *
7407     * @param event The motion event to be filtered.
7408     * @return True if the event should be dispatched, false if the event should be dropped.
7409     *
7410     * @see #getFilterTouchesWhenObscured
7411     */
7412    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
7413        //noinspection RedundantIfStatement
7414        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
7415                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
7416            // Window is obscured, drop this touch.
7417            return false;
7418        }
7419        return true;
7420    }
7421
7422    /**
7423     * Pass a trackball motion event down to the focused view.
7424     *
7425     * @param event The motion event to be dispatched.
7426     * @return True if the event was handled by the view, false otherwise.
7427     */
7428    public boolean dispatchTrackballEvent(MotionEvent event) {
7429        if (mInputEventConsistencyVerifier != null) {
7430            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
7431        }
7432
7433        return onTrackballEvent(event);
7434    }
7435
7436    /**
7437     * Dispatch a generic motion event.
7438     * <p>
7439     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
7440     * are delivered to the view under the pointer.  All other generic motion events are
7441     * delivered to the focused view.  Hover events are handled specially and are delivered
7442     * to {@link #onHoverEvent(MotionEvent)}.
7443     * </p>
7444     *
7445     * @param event The motion event to be dispatched.
7446     * @return True if the event was handled by the view, false otherwise.
7447     */
7448    public boolean dispatchGenericMotionEvent(MotionEvent event) {
7449        if (mInputEventConsistencyVerifier != null) {
7450            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
7451        }
7452
7453        final int source = event.getSource();
7454        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
7455            final int action = event.getAction();
7456            if (action == MotionEvent.ACTION_HOVER_ENTER
7457                    || action == MotionEvent.ACTION_HOVER_MOVE
7458                    || action == MotionEvent.ACTION_HOVER_EXIT) {
7459                if (dispatchHoverEvent(event)) {
7460                    return true;
7461                }
7462            } else if (dispatchGenericPointerEvent(event)) {
7463                return true;
7464            }
7465        } else if (dispatchGenericFocusedEvent(event)) {
7466            return true;
7467        }
7468
7469        if (dispatchGenericMotionEventInternal(event)) {
7470            return true;
7471        }
7472
7473        if (mInputEventConsistencyVerifier != null) {
7474            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7475        }
7476        return false;
7477    }
7478
7479    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
7480        //noinspection SimplifiableIfStatement
7481        ListenerInfo li = mListenerInfo;
7482        if (li != null && li.mOnGenericMotionListener != null
7483                && (mViewFlags & ENABLED_MASK) == ENABLED
7484                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
7485            return true;
7486        }
7487
7488        if (onGenericMotionEvent(event)) {
7489            return true;
7490        }
7491
7492        if (mInputEventConsistencyVerifier != null) {
7493            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
7494        }
7495        return false;
7496    }
7497
7498    /**
7499     * Dispatch a hover event.
7500     * <p>
7501     * Do not call this method directly.
7502     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7503     * </p>
7504     *
7505     * @param event The motion event to be dispatched.
7506     * @return True if the event was handled by the view, false otherwise.
7507     */
7508    protected boolean dispatchHoverEvent(MotionEvent event) {
7509        //noinspection SimplifiableIfStatement
7510        ListenerInfo li = mListenerInfo;
7511        if (li != null && li.mOnHoverListener != null
7512                && (mViewFlags & ENABLED_MASK) == ENABLED
7513                && li.mOnHoverListener.onHover(this, event)) {
7514            return true;
7515        }
7516
7517        return onHoverEvent(event);
7518    }
7519
7520    /**
7521     * Returns true if the view has a child to which it has recently sent
7522     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
7523     * it does not have a hovered child, then it must be the innermost hovered view.
7524     * @hide
7525     */
7526    protected boolean hasHoveredChild() {
7527        return false;
7528    }
7529
7530    /**
7531     * Dispatch a generic motion event to the view under the first pointer.
7532     * <p>
7533     * Do not call this method directly.
7534     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7535     * </p>
7536     *
7537     * @param event The motion event to be dispatched.
7538     * @return True if the event was handled by the view, false otherwise.
7539     */
7540    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
7541        return false;
7542    }
7543
7544    /**
7545     * Dispatch a generic motion event to the currently focused view.
7546     * <p>
7547     * Do not call this method directly.
7548     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
7549     * </p>
7550     *
7551     * @param event The motion event to be dispatched.
7552     * @return True if the event was handled by the view, false otherwise.
7553     */
7554    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
7555        return false;
7556    }
7557
7558    /**
7559     * Dispatch a pointer event.
7560     * <p>
7561     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
7562     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
7563     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
7564     * and should not be expected to handle other pointing device features.
7565     * </p>
7566     *
7567     * @param event The motion event to be dispatched.
7568     * @return True if the event was handled by the view, false otherwise.
7569     * @hide
7570     */
7571    public final boolean dispatchPointerEvent(MotionEvent event) {
7572        if (event.isTouchEvent()) {
7573            return dispatchTouchEvent(event);
7574        } else {
7575            return dispatchGenericMotionEvent(event);
7576        }
7577    }
7578
7579    /**
7580     * Called when the window containing this view gains or loses window focus.
7581     * ViewGroups should override to route to their children.
7582     *
7583     * @param hasFocus True if the window containing this view now has focus,
7584     *        false otherwise.
7585     */
7586    public void dispatchWindowFocusChanged(boolean hasFocus) {
7587        onWindowFocusChanged(hasFocus);
7588    }
7589
7590    /**
7591     * Called when the window containing this view gains or loses focus.  Note
7592     * that this is separate from view focus: to receive key events, both
7593     * your view and its window must have focus.  If a window is displayed
7594     * on top of yours that takes input focus, then your own window will lose
7595     * focus but the view focus will remain unchanged.
7596     *
7597     * @param hasWindowFocus True if the window containing this view now has
7598     *        focus, false otherwise.
7599     */
7600    public void onWindowFocusChanged(boolean hasWindowFocus) {
7601        InputMethodManager imm = InputMethodManager.peekInstance();
7602        if (!hasWindowFocus) {
7603            if (isPressed()) {
7604                setPressed(false);
7605            }
7606            if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7607                imm.focusOut(this);
7608            }
7609            removeLongPressCallback();
7610            removeTapCallback();
7611            onFocusLost();
7612        } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) {
7613            imm.focusIn(this);
7614        }
7615        refreshDrawableState();
7616    }
7617
7618    /**
7619     * Returns true if this view is in a window that currently has window focus.
7620     * Note that this is not the same as the view itself having focus.
7621     *
7622     * @return True if this view is in a window that currently has window focus.
7623     */
7624    public boolean hasWindowFocus() {
7625        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
7626    }
7627
7628    /**
7629     * Dispatch a view visibility change down the view hierarchy.
7630     * ViewGroups should override to route to their children.
7631     * @param changedView The view whose visibility changed. Could be 'this' or
7632     * an ancestor view.
7633     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7634     * {@link #INVISIBLE} or {@link #GONE}.
7635     */
7636    protected void dispatchVisibilityChanged(View changedView, int visibility) {
7637        onVisibilityChanged(changedView, visibility);
7638    }
7639
7640    /**
7641     * Called when the visibility of the view or an ancestor of the view is changed.
7642     * @param changedView The view whose visibility changed. Could be 'this' or
7643     * an ancestor view.
7644     * @param visibility The new visibility of changedView: {@link #VISIBLE},
7645     * {@link #INVISIBLE} or {@link #GONE}.
7646     */
7647    protected void onVisibilityChanged(View changedView, int visibility) {
7648        if (visibility == VISIBLE) {
7649            if (mAttachInfo != null) {
7650                initialAwakenScrollBars();
7651            } else {
7652                mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
7653            }
7654        }
7655    }
7656
7657    /**
7658     * Dispatch a hint about whether this view is displayed. For instance, when
7659     * a View moves out of the screen, it might receives a display hint indicating
7660     * the view is not displayed. Applications should not <em>rely</em> on this hint
7661     * as there is no guarantee that they will receive one.
7662     *
7663     * @param hint A hint about whether or not this view is displayed:
7664     * {@link #VISIBLE} or {@link #INVISIBLE}.
7665     */
7666    public void dispatchDisplayHint(int hint) {
7667        onDisplayHint(hint);
7668    }
7669
7670    /**
7671     * Gives this view a hint about whether is displayed or not. For instance, when
7672     * a View moves out of the screen, it might receives a display hint indicating
7673     * the view is not displayed. Applications should not <em>rely</em> on this hint
7674     * as there is no guarantee that they will receive one.
7675     *
7676     * @param hint A hint about whether or not this view is displayed:
7677     * {@link #VISIBLE} or {@link #INVISIBLE}.
7678     */
7679    protected void onDisplayHint(int hint) {
7680    }
7681
7682    /**
7683     * Dispatch a window visibility change down the view hierarchy.
7684     * ViewGroups should override to route to their children.
7685     *
7686     * @param visibility The new visibility of the window.
7687     *
7688     * @see #onWindowVisibilityChanged(int)
7689     */
7690    public void dispatchWindowVisibilityChanged(int visibility) {
7691        onWindowVisibilityChanged(visibility);
7692    }
7693
7694    /**
7695     * Called when the window containing has change its visibility
7696     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
7697     * that this tells you whether or not your window is being made visible
7698     * to the window manager; this does <em>not</em> tell you whether or not
7699     * your window is obscured by other windows on the screen, even if it
7700     * is itself visible.
7701     *
7702     * @param visibility The new visibility of the window.
7703     */
7704    protected void onWindowVisibilityChanged(int visibility) {
7705        if (visibility == VISIBLE) {
7706            initialAwakenScrollBars();
7707        }
7708    }
7709
7710    /**
7711     * Returns the current visibility of the window this view is attached to
7712     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
7713     *
7714     * @return Returns the current visibility of the view's window.
7715     */
7716    public int getWindowVisibility() {
7717        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
7718    }
7719
7720    /**
7721     * Retrieve the overall visible display size in which the window this view is
7722     * attached to has been positioned in.  This takes into account screen
7723     * decorations above the window, for both cases where the window itself
7724     * is being position inside of them or the window is being placed under
7725     * then and covered insets are used for the window to position its content
7726     * inside.  In effect, this tells you the available area where content can
7727     * be placed and remain visible to users.
7728     *
7729     * <p>This function requires an IPC back to the window manager to retrieve
7730     * the requested information, so should not be used in performance critical
7731     * code like drawing.
7732     *
7733     * @param outRect Filled in with the visible display frame.  If the view
7734     * is not attached to a window, this is simply the raw display size.
7735     */
7736    public void getWindowVisibleDisplayFrame(Rect outRect) {
7737        if (mAttachInfo != null) {
7738            try {
7739                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
7740            } catch (RemoteException e) {
7741                return;
7742            }
7743            // XXX This is really broken, and probably all needs to be done
7744            // in the window manager, and we need to know more about whether
7745            // we want the area behind or in front of the IME.
7746            final Rect insets = mAttachInfo.mVisibleInsets;
7747            outRect.left += insets.left;
7748            outRect.top += insets.top;
7749            outRect.right -= insets.right;
7750            outRect.bottom -= insets.bottom;
7751            return;
7752        }
7753        // The view is not attached to a display so we don't have a context.
7754        // Make a best guess about the display size.
7755        Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY);
7756        d.getRectSize(outRect);
7757    }
7758
7759    /**
7760     * Dispatch a notification about a resource configuration change down
7761     * the view hierarchy.
7762     * ViewGroups should override to route to their children.
7763     *
7764     * @param newConfig The new resource configuration.
7765     *
7766     * @see #onConfigurationChanged(android.content.res.Configuration)
7767     */
7768    public void dispatchConfigurationChanged(Configuration newConfig) {
7769        onConfigurationChanged(newConfig);
7770    }
7771
7772    /**
7773     * Called when the current configuration of the resources being used
7774     * by the application have changed.  You can use this to decide when
7775     * to reload resources that can changed based on orientation and other
7776     * configuration characterstics.  You only need to use this if you are
7777     * not relying on the normal {@link android.app.Activity} mechanism of
7778     * recreating the activity instance upon a configuration change.
7779     *
7780     * @param newConfig The new resource configuration.
7781     */
7782    protected void onConfigurationChanged(Configuration newConfig) {
7783    }
7784
7785    /**
7786     * Private function to aggregate all per-view attributes in to the view
7787     * root.
7788     */
7789    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7790        performCollectViewAttributes(attachInfo, visibility);
7791    }
7792
7793    void performCollectViewAttributes(AttachInfo attachInfo, int visibility) {
7794        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
7795            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
7796                attachInfo.mKeepScreenOn = true;
7797            }
7798            attachInfo.mSystemUiVisibility |= mSystemUiVisibility;
7799            ListenerInfo li = mListenerInfo;
7800            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
7801                attachInfo.mHasSystemUiListeners = true;
7802            }
7803        }
7804    }
7805
7806    void needGlobalAttributesUpdate(boolean force) {
7807        final AttachInfo ai = mAttachInfo;
7808        if (ai != null && !ai.mRecomputeGlobalAttributes) {
7809            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
7810                    || ai.mHasSystemUiListeners) {
7811                ai.mRecomputeGlobalAttributes = true;
7812            }
7813        }
7814    }
7815
7816    /**
7817     * Returns whether the device is currently in touch mode.  Touch mode is entered
7818     * once the user begins interacting with the device by touch, and affects various
7819     * things like whether focus is always visible to the user.
7820     *
7821     * @return Whether the device is in touch mode.
7822     */
7823    @ViewDebug.ExportedProperty
7824    public boolean isInTouchMode() {
7825        if (mAttachInfo != null) {
7826            return mAttachInfo.mInTouchMode;
7827        } else {
7828            return ViewRootImpl.isInTouchMode();
7829        }
7830    }
7831
7832    /**
7833     * Returns the context the view is running in, through which it can
7834     * access the current theme, resources, etc.
7835     *
7836     * @return The view's Context.
7837     */
7838    @ViewDebug.CapturedViewProperty
7839    public final Context getContext() {
7840        return mContext;
7841    }
7842
7843    /**
7844     * Handle a key event before it is processed by any input method
7845     * associated with the view hierarchy.  This can be used to intercept
7846     * key events in special situations before the IME consumes them; a
7847     * typical example would be handling the BACK key to update the application's
7848     * UI instead of allowing the IME to see it and close itself.
7849     *
7850     * @param keyCode The value in event.getKeyCode().
7851     * @param event Description of the key event.
7852     * @return If you handled the event, return true. If you want to allow the
7853     *         event to be handled by the next receiver, return false.
7854     */
7855    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
7856        return false;
7857    }
7858
7859    /**
7860     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
7861     * KeyEvent.Callback.onKeyDown()}: perform press of the view
7862     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
7863     * is released, if the view is enabled and clickable.
7864     *
7865     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7866     * although some may elect to do so in some situations. Do not rely on this to
7867     * catch software key presses.
7868     *
7869     * @param keyCode A key code that represents the button pressed, from
7870     *                {@link android.view.KeyEvent}.
7871     * @param event   The KeyEvent object that defines the button action.
7872     */
7873    public boolean onKeyDown(int keyCode, KeyEvent event) {
7874        boolean result = false;
7875
7876        switch (keyCode) {
7877            case KeyEvent.KEYCODE_DPAD_CENTER:
7878            case KeyEvent.KEYCODE_ENTER: {
7879                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7880                    return true;
7881                }
7882                // Long clickable items don't necessarily have to be clickable
7883                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
7884                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
7885                        (event.getRepeatCount() == 0)) {
7886                    setPressed(true);
7887                    checkForLongClick(0);
7888                    return true;
7889                }
7890                break;
7891            }
7892        }
7893        return result;
7894    }
7895
7896    /**
7897     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
7898     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
7899     * the event).
7900     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7901     * although some may elect to do so in some situations. Do not rely on this to
7902     * catch software key presses.
7903     */
7904    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
7905        return false;
7906    }
7907
7908    /**
7909     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
7910     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
7911     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
7912     * {@link KeyEvent#KEYCODE_ENTER} is released.
7913     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7914     * although some may elect to do so in some situations. Do not rely on this to
7915     * catch software key presses.
7916     *
7917     * @param keyCode A key code that represents the button pressed, from
7918     *                {@link android.view.KeyEvent}.
7919     * @param event   The KeyEvent object that defines the button action.
7920     */
7921    public boolean onKeyUp(int keyCode, KeyEvent event) {
7922        boolean result = false;
7923
7924        switch (keyCode) {
7925            case KeyEvent.KEYCODE_DPAD_CENTER:
7926            case KeyEvent.KEYCODE_ENTER: {
7927                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
7928                    return true;
7929                }
7930                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
7931                    setPressed(false);
7932
7933                    if (!mHasPerformedLongPress) {
7934                        // This is a tap, so remove the longpress check
7935                        removeLongPressCallback();
7936
7937                        result = performClick();
7938                    }
7939                }
7940                break;
7941            }
7942        }
7943        return result;
7944    }
7945
7946    /**
7947     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
7948     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
7949     * the event).
7950     * <p>Key presses in software keyboards will generally NOT trigger this listener,
7951     * although some may elect to do so in some situations. Do not rely on this to
7952     * catch software key presses.
7953     *
7954     * @param keyCode     A key code that represents the button pressed, from
7955     *                    {@link android.view.KeyEvent}.
7956     * @param repeatCount The number of times the action was made.
7957     * @param event       The KeyEvent object that defines the button action.
7958     */
7959    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
7960        return false;
7961    }
7962
7963    /**
7964     * Called on the focused view when a key shortcut event is not handled.
7965     * Override this method to implement local key shortcuts for the View.
7966     * Key shortcuts can also be implemented by setting the
7967     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
7968     *
7969     * @param keyCode The value in event.getKeyCode().
7970     * @param event Description of the key event.
7971     * @return If you handled the event, return true. If you want to allow the
7972     *         event to be handled by the next receiver, return false.
7973     */
7974    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
7975        return false;
7976    }
7977
7978    /**
7979     * Check whether the called view is a text editor, in which case it
7980     * would make sense to automatically display a soft input window for
7981     * it.  Subclasses should override this if they implement
7982     * {@link #onCreateInputConnection(EditorInfo)} to return true if
7983     * a call on that method would return a non-null InputConnection, and
7984     * they are really a first-class editor that the user would normally
7985     * start typing on when the go into a window containing your view.
7986     *
7987     * <p>The default implementation always returns false.  This does
7988     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
7989     * will not be called or the user can not otherwise perform edits on your
7990     * view; it is just a hint to the system that this is not the primary
7991     * purpose of this view.
7992     *
7993     * @return Returns true if this view is a text editor, else false.
7994     */
7995    public boolean onCheckIsTextEditor() {
7996        return false;
7997    }
7998
7999    /**
8000     * Create a new InputConnection for an InputMethod to interact
8001     * with the view.  The default implementation returns null, since it doesn't
8002     * support input methods.  You can override this to implement such support.
8003     * This is only needed for views that take focus and text input.
8004     *
8005     * <p>When implementing this, you probably also want to implement
8006     * {@link #onCheckIsTextEditor()} to indicate you will return a
8007     * non-null InputConnection.
8008     *
8009     * @param outAttrs Fill in with attribute information about the connection.
8010     */
8011    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
8012        return null;
8013    }
8014
8015    /**
8016     * Called by the {@link android.view.inputmethod.InputMethodManager}
8017     * when a view who is not the current
8018     * input connection target is trying to make a call on the manager.  The
8019     * default implementation returns false; you can override this to return
8020     * true for certain views if you are performing InputConnection proxying
8021     * to them.
8022     * @param view The View that is making the InputMethodManager call.
8023     * @return Return true to allow the call, false to reject.
8024     */
8025    public boolean checkInputConnectionProxy(View view) {
8026        return false;
8027    }
8028
8029    /**
8030     * Show the context menu for this view. It is not safe to hold on to the
8031     * menu after returning from this method.
8032     *
8033     * You should normally not overload this method. Overload
8034     * {@link #onCreateContextMenu(ContextMenu)} or define an
8035     * {@link OnCreateContextMenuListener} to add items to the context menu.
8036     *
8037     * @param menu The context menu to populate
8038     */
8039    public void createContextMenu(ContextMenu menu) {
8040        ContextMenuInfo menuInfo = getContextMenuInfo();
8041
8042        // Sets the current menu info so all items added to menu will have
8043        // my extra info set.
8044        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
8045
8046        onCreateContextMenu(menu);
8047        ListenerInfo li = mListenerInfo;
8048        if (li != null && li.mOnCreateContextMenuListener != null) {
8049            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
8050        }
8051
8052        // Clear the extra information so subsequent items that aren't mine don't
8053        // have my extra info.
8054        ((MenuBuilder)menu).setCurrentMenuInfo(null);
8055
8056        if (mParent != null) {
8057            mParent.createContextMenu(menu);
8058        }
8059    }
8060
8061    /**
8062     * Views should implement this if they have extra information to associate
8063     * with the context menu. The return result is supplied as a parameter to
8064     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
8065     * callback.
8066     *
8067     * @return Extra information about the item for which the context menu
8068     *         should be shown. This information will vary across different
8069     *         subclasses of View.
8070     */
8071    protected ContextMenuInfo getContextMenuInfo() {
8072        return null;
8073    }
8074
8075    /**
8076     * Views should implement this if the view itself is going to add items to
8077     * the context menu.
8078     *
8079     * @param menu the context menu to populate
8080     */
8081    protected void onCreateContextMenu(ContextMenu menu) {
8082    }
8083
8084    /**
8085     * Implement this method to handle trackball motion events.  The
8086     * <em>relative</em> movement of the trackball since the last event
8087     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
8088     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
8089     * that a movement of 1 corresponds to the user pressing one DPAD key (so
8090     * they will often be fractional values, representing the more fine-grained
8091     * movement information available from a trackball).
8092     *
8093     * @param event The motion event.
8094     * @return True if the event was handled, false otherwise.
8095     */
8096    public boolean onTrackballEvent(MotionEvent event) {
8097        return false;
8098    }
8099
8100    /**
8101     * Implement this method to handle generic motion events.
8102     * <p>
8103     * Generic motion events describe joystick movements, mouse hovers, track pad
8104     * touches, scroll wheel movements and other input events.  The
8105     * {@link MotionEvent#getSource() source} of the motion event specifies
8106     * the class of input that was received.  Implementations of this method
8107     * must examine the bits in the source before processing the event.
8108     * The following code example shows how this is done.
8109     * </p><p>
8110     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
8111     * are delivered to the view under the pointer.  All other generic motion events are
8112     * delivered to the focused view.
8113     * </p>
8114     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
8115     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
8116     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
8117     *             // process the joystick movement...
8118     *             return true;
8119     *         }
8120     *     }
8121     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
8122     *         switch (event.getAction()) {
8123     *             case MotionEvent.ACTION_HOVER_MOVE:
8124     *                 // process the mouse hover movement...
8125     *                 return true;
8126     *             case MotionEvent.ACTION_SCROLL:
8127     *                 // process the scroll wheel movement...
8128     *                 return true;
8129     *         }
8130     *     }
8131     *     return super.onGenericMotionEvent(event);
8132     * }</pre>
8133     *
8134     * @param event The generic motion event being processed.
8135     * @return True if the event was handled, false otherwise.
8136     */
8137    public boolean onGenericMotionEvent(MotionEvent event) {
8138        return false;
8139    }
8140
8141    /**
8142     * Implement this method to handle hover events.
8143     * <p>
8144     * This method is called whenever a pointer is hovering into, over, or out of the
8145     * bounds of a view and the view is not currently being touched.
8146     * Hover events are represented as pointer events with action
8147     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
8148     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
8149     * </p>
8150     * <ul>
8151     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
8152     * when the pointer enters the bounds of the view.</li>
8153     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
8154     * when the pointer has already entered the bounds of the view and has moved.</li>
8155     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
8156     * when the pointer has exited the bounds of the view or when the pointer is
8157     * about to go down due to a button click, tap, or similar user action that
8158     * causes the view to be touched.</li>
8159     * </ul>
8160     * <p>
8161     * The view should implement this method to return true to indicate that it is
8162     * handling the hover event, such as by changing its drawable state.
8163     * </p><p>
8164     * The default implementation calls {@link #setHovered} to update the hovered state
8165     * of the view when a hover enter or hover exit event is received, if the view
8166     * is enabled and is clickable.  The default implementation also sends hover
8167     * accessibility events.
8168     * </p>
8169     *
8170     * @param event The motion event that describes the hover.
8171     * @return True if the view handled the hover event.
8172     *
8173     * @see #isHovered
8174     * @see #setHovered
8175     * @see #onHoverChanged
8176     */
8177    public boolean onHoverEvent(MotionEvent event) {
8178        // The root view may receive hover (or touch) events that are outside the bounds of
8179        // the window.  This code ensures that we only send accessibility events for
8180        // hovers that are actually within the bounds of the root view.
8181        final int action = event.getActionMasked();
8182        if (!mSendingHoverAccessibilityEvents) {
8183            if ((action == MotionEvent.ACTION_HOVER_ENTER
8184                    || action == MotionEvent.ACTION_HOVER_MOVE)
8185                    && !hasHoveredChild()
8186                    && pointInView(event.getX(), event.getY())) {
8187                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
8188                mSendingHoverAccessibilityEvents = true;
8189            }
8190        } else {
8191            if (action == MotionEvent.ACTION_HOVER_EXIT
8192                    || (action == MotionEvent.ACTION_MOVE
8193                            && !pointInView(event.getX(), event.getY()))) {
8194                mSendingHoverAccessibilityEvents = false;
8195                sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
8196                // If the window does not have input focus we take away accessibility
8197                // focus as soon as the user stop hovering over the view.
8198                if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) {
8199                    getViewRootImpl().setAccessibilityFocus(null, null);
8200                }
8201            }
8202        }
8203
8204        if (isHoverable()) {
8205            switch (action) {
8206                case MotionEvent.ACTION_HOVER_ENTER:
8207                    setHovered(true);
8208                    break;
8209                case MotionEvent.ACTION_HOVER_EXIT:
8210                    setHovered(false);
8211                    break;
8212            }
8213
8214            // Dispatch the event to onGenericMotionEvent before returning true.
8215            // This is to provide compatibility with existing applications that
8216            // handled HOVER_MOVE events in onGenericMotionEvent and that would
8217            // break because of the new default handling for hoverable views
8218            // in onHoverEvent.
8219            // Note that onGenericMotionEvent will be called by default when
8220            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
8221            return dispatchGenericMotionEventInternal(event);
8222        }
8223
8224        return false;
8225    }
8226
8227    /**
8228     * Returns true if the view should handle {@link #onHoverEvent}
8229     * by calling {@link #setHovered} to change its hovered state.
8230     *
8231     * @return True if the view is hoverable.
8232     */
8233    private boolean isHoverable() {
8234        final int viewFlags = mViewFlags;
8235        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8236            return false;
8237        }
8238
8239        return (viewFlags & CLICKABLE) == CLICKABLE
8240                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
8241    }
8242
8243    /**
8244     * Returns true if the view is currently hovered.
8245     *
8246     * @return True if the view is currently hovered.
8247     *
8248     * @see #setHovered
8249     * @see #onHoverChanged
8250     */
8251    @ViewDebug.ExportedProperty
8252    public boolean isHovered() {
8253        return (mPrivateFlags & PFLAG_HOVERED) != 0;
8254    }
8255
8256    /**
8257     * Sets whether the view is currently hovered.
8258     * <p>
8259     * Calling this method also changes the drawable state of the view.  This
8260     * enables the view to react to hover by using different drawable resources
8261     * to change its appearance.
8262     * </p><p>
8263     * The {@link #onHoverChanged} method is called when the hovered state changes.
8264     * </p>
8265     *
8266     * @param hovered True if the view is hovered.
8267     *
8268     * @see #isHovered
8269     * @see #onHoverChanged
8270     */
8271    public void setHovered(boolean hovered) {
8272        if (hovered) {
8273            if ((mPrivateFlags & PFLAG_HOVERED) == 0) {
8274                mPrivateFlags |= PFLAG_HOVERED;
8275                refreshDrawableState();
8276                onHoverChanged(true);
8277            }
8278        } else {
8279            if ((mPrivateFlags & PFLAG_HOVERED) != 0) {
8280                mPrivateFlags &= ~PFLAG_HOVERED;
8281                refreshDrawableState();
8282                onHoverChanged(false);
8283            }
8284        }
8285    }
8286
8287    /**
8288     * Implement this method to handle hover state changes.
8289     * <p>
8290     * This method is called whenever the hover state changes as a result of a
8291     * call to {@link #setHovered}.
8292     * </p>
8293     *
8294     * @param hovered The current hover state, as returned by {@link #isHovered}.
8295     *
8296     * @see #isHovered
8297     * @see #setHovered
8298     */
8299    public void onHoverChanged(boolean hovered) {
8300    }
8301
8302    /**
8303     * Implement this method to handle touch screen motion events.
8304     *
8305     * @param event The motion event.
8306     * @return True if the event was handled, false otherwise.
8307     */
8308    public boolean onTouchEvent(MotionEvent event) {
8309        final int viewFlags = mViewFlags;
8310
8311        if ((viewFlags & ENABLED_MASK) == DISABLED) {
8312            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
8313                setPressed(false);
8314            }
8315            // A disabled view that is clickable still consumes the touch
8316            // events, it just doesn't respond to them.
8317            return (((viewFlags & CLICKABLE) == CLICKABLE ||
8318                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
8319        }
8320
8321        if (mTouchDelegate != null) {
8322            if (mTouchDelegate.onTouchEvent(event)) {
8323                return true;
8324            }
8325        }
8326
8327        if (((viewFlags & CLICKABLE) == CLICKABLE ||
8328                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
8329            switch (event.getAction()) {
8330                case MotionEvent.ACTION_UP:
8331                    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
8332                    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
8333                        // take focus if we don't have it already and we should in
8334                        // touch mode.
8335                        boolean focusTaken = false;
8336                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
8337                            focusTaken = requestFocus();
8338                        }
8339
8340                        if (prepressed) {
8341                            // The button is being released before we actually
8342                            // showed it as pressed.  Make it show the pressed
8343                            // state now (before scheduling the click) to ensure
8344                            // the user sees it.
8345                            setPressed(true);
8346                       }
8347
8348                        if (!mHasPerformedLongPress) {
8349                            // This is a tap, so remove the longpress check
8350                            removeLongPressCallback();
8351
8352                            // Only perform take click actions if we were in the pressed state
8353                            if (!focusTaken) {
8354                                // Use a Runnable and post this rather than calling
8355                                // performClick directly. This lets other visual state
8356                                // of the view update before click actions start.
8357                                if (mPerformClick == null) {
8358                                    mPerformClick = new PerformClick();
8359                                }
8360                                if (!post(mPerformClick)) {
8361                                    performClick();
8362                                }
8363                            }
8364                        }
8365
8366                        if (mUnsetPressedState == null) {
8367                            mUnsetPressedState = new UnsetPressedState();
8368                        }
8369
8370                        if (prepressed) {
8371                            postDelayed(mUnsetPressedState,
8372                                    ViewConfiguration.getPressedStateDuration());
8373                        } else if (!post(mUnsetPressedState)) {
8374                            // If the post failed, unpress right now
8375                            mUnsetPressedState.run();
8376                        }
8377                        removeTapCallback();
8378                    }
8379                    break;
8380
8381                case MotionEvent.ACTION_DOWN:
8382                    mHasPerformedLongPress = false;
8383
8384                    if (performButtonActionOnTouchDown(event)) {
8385                        break;
8386                    }
8387
8388                    // Walk up the hierarchy to determine if we're inside a scrolling container.
8389                    boolean isInScrollingContainer = isInScrollingContainer();
8390
8391                    // For views inside a scrolling container, delay the pressed feedback for
8392                    // a short period in case this is a scroll.
8393                    if (isInScrollingContainer) {
8394                        mPrivateFlags |= PFLAG_PREPRESSED;
8395                        if (mPendingCheckForTap == null) {
8396                            mPendingCheckForTap = new CheckForTap();
8397                        }
8398                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
8399                    } else {
8400                        // Not inside a scrolling container, so show the feedback right away
8401                        setPressed(true);
8402                        checkForLongClick(0);
8403                    }
8404                    break;
8405
8406                case MotionEvent.ACTION_CANCEL:
8407                    setPressed(false);
8408                    removeTapCallback();
8409                    removeLongPressCallback();
8410                    break;
8411
8412                case MotionEvent.ACTION_MOVE:
8413                    final int x = (int) event.getX();
8414                    final int y = (int) event.getY();
8415
8416                    // Be lenient about moving outside of buttons
8417                    if (!pointInView(x, y, mTouchSlop)) {
8418                        // Outside button
8419                        removeTapCallback();
8420                        if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
8421                            // Remove any future long press/tap checks
8422                            removeLongPressCallback();
8423
8424                            setPressed(false);
8425                        }
8426                    }
8427                    break;
8428            }
8429            return true;
8430        }
8431
8432        return false;
8433    }
8434
8435    /**
8436     * @hide
8437     */
8438    public boolean isInScrollingContainer() {
8439        ViewParent p = getParent();
8440        while (p != null && p instanceof ViewGroup) {
8441            if (((ViewGroup) p).shouldDelayChildPressedState()) {
8442                return true;
8443            }
8444            p = p.getParent();
8445        }
8446        return false;
8447    }
8448
8449    /**
8450     * Remove the longpress detection timer.
8451     */
8452    private void removeLongPressCallback() {
8453        if (mPendingCheckForLongPress != null) {
8454          removeCallbacks(mPendingCheckForLongPress);
8455        }
8456    }
8457
8458    /**
8459     * Remove the pending click action
8460     */
8461    private void removePerformClickCallback() {
8462        if (mPerformClick != null) {
8463            removeCallbacks(mPerformClick);
8464        }
8465    }
8466
8467    /**
8468     * Remove the prepress detection timer.
8469     */
8470    private void removeUnsetPressCallback() {
8471        if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) {
8472            setPressed(false);
8473            removeCallbacks(mUnsetPressedState);
8474        }
8475    }
8476
8477    /**
8478     * Remove the tap detection timer.
8479     */
8480    private void removeTapCallback() {
8481        if (mPendingCheckForTap != null) {
8482            mPrivateFlags &= ~PFLAG_PREPRESSED;
8483            removeCallbacks(mPendingCheckForTap);
8484        }
8485    }
8486
8487    /**
8488     * Cancels a pending long press.  Your subclass can use this if you
8489     * want the context menu to come up if the user presses and holds
8490     * at the same place, but you don't want it to come up if they press
8491     * and then move around enough to cause scrolling.
8492     */
8493    public void cancelLongPress() {
8494        removeLongPressCallback();
8495
8496        /*
8497         * The prepressed state handled by the tap callback is a display
8498         * construct, but the tap callback will post a long press callback
8499         * less its own timeout. Remove it here.
8500         */
8501        removeTapCallback();
8502    }
8503
8504    /**
8505     * Remove the pending callback for sending a
8506     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
8507     */
8508    private void removeSendViewScrolledAccessibilityEventCallback() {
8509        if (mSendViewScrolledAccessibilityEvent != null) {
8510            removeCallbacks(mSendViewScrolledAccessibilityEvent);
8511            mSendViewScrolledAccessibilityEvent.mIsPending = false;
8512        }
8513    }
8514
8515    /**
8516     * Sets the TouchDelegate for this View.
8517     */
8518    public void setTouchDelegate(TouchDelegate delegate) {
8519        mTouchDelegate = delegate;
8520    }
8521
8522    /**
8523     * Gets the TouchDelegate for this View.
8524     */
8525    public TouchDelegate getTouchDelegate() {
8526        return mTouchDelegate;
8527    }
8528
8529    /**
8530     * Set flags controlling behavior of this view.
8531     *
8532     * @param flags Constant indicating the value which should be set
8533     * @param mask Constant indicating the bit range that should be changed
8534     */
8535    void setFlags(int flags, int mask) {
8536        int old = mViewFlags;
8537        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
8538
8539        int changed = mViewFlags ^ old;
8540        if (changed == 0) {
8541            return;
8542        }
8543        int privateFlags = mPrivateFlags;
8544
8545        /* Check if the FOCUSABLE bit has changed */
8546        if (((changed & FOCUSABLE_MASK) != 0) &&
8547                ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) {
8548            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
8549                    && ((privateFlags & PFLAG_FOCUSED) != 0)) {
8550                /* Give up focus if we are no longer focusable */
8551                clearFocus();
8552            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
8553                    && ((privateFlags & PFLAG_FOCUSED) == 0)) {
8554                /*
8555                 * Tell the view system that we are now available to take focus
8556                 * if no one else already has it.
8557                 */
8558                if (mParent != null) mParent.focusableViewAvailable(this);
8559            }
8560            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8561                notifyAccessibilityStateChanged();
8562            }
8563        }
8564
8565        if ((flags & VISIBILITY_MASK) == VISIBLE) {
8566            if ((changed & VISIBILITY_MASK) != 0) {
8567                /*
8568                 * If this view is becoming visible, invalidate it in case it changed while
8569                 * it was not visible. Marking it drawn ensures that the invalidation will
8570                 * go through.
8571                 */
8572                mPrivateFlags |= PFLAG_DRAWN;
8573                invalidate(true);
8574
8575                needGlobalAttributesUpdate(true);
8576
8577                // a view becoming visible is worth notifying the parent
8578                // about in case nothing has focus.  even if this specific view
8579                // isn't focusable, it may contain something that is, so let
8580                // the root view try to give this focus if nothing else does.
8581                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
8582                    mParent.focusableViewAvailable(this);
8583                }
8584            }
8585        }
8586
8587        /* Check if the GONE bit has changed */
8588        if ((changed & GONE) != 0) {
8589            needGlobalAttributesUpdate(false);
8590            requestLayout();
8591
8592            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
8593                if (hasFocus()) clearFocus();
8594                clearAccessibilityFocus();
8595                destroyDrawingCache();
8596                if (mParent instanceof View) {
8597                    // GONE views noop invalidation, so invalidate the parent
8598                    ((View) mParent).invalidate(true);
8599                }
8600                // Mark the view drawn to ensure that it gets invalidated properly the next
8601                // time it is visible and gets invalidated
8602                mPrivateFlags |= PFLAG_DRAWN;
8603            }
8604            if (mAttachInfo != null) {
8605                mAttachInfo.mViewVisibilityChanged = true;
8606            }
8607        }
8608
8609        /* Check if the VISIBLE bit has changed */
8610        if ((changed & INVISIBLE) != 0) {
8611            needGlobalAttributesUpdate(false);
8612            /*
8613             * If this view is becoming invisible, set the DRAWN flag so that
8614             * the next invalidate() will not be skipped.
8615             */
8616            mPrivateFlags |= PFLAG_DRAWN;
8617
8618            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
8619                // root view becoming invisible shouldn't clear focus and accessibility focus
8620                if (getRootView() != this) {
8621                    clearFocus();
8622                    clearAccessibilityFocus();
8623                }
8624            }
8625            if (mAttachInfo != null) {
8626                mAttachInfo.mViewVisibilityChanged = true;
8627            }
8628        }
8629
8630        if ((changed & VISIBILITY_MASK) != 0) {
8631            if (mParent instanceof ViewGroup) {
8632                ((ViewGroup) mParent).onChildVisibilityChanged(this,
8633                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
8634                ((View) mParent).invalidate(true);
8635            } else if (mParent != null) {
8636                mParent.invalidateChild(this, null);
8637            }
8638            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
8639        }
8640
8641        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
8642            destroyDrawingCache();
8643        }
8644
8645        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
8646            destroyDrawingCache();
8647            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8648            invalidateParentCaches();
8649        }
8650
8651        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
8652            destroyDrawingCache();
8653            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
8654        }
8655
8656        if ((changed & DRAW_MASK) != 0) {
8657            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
8658                if (mBackground != null) {
8659                    mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8660                    mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
8661                } else {
8662                    mPrivateFlags |= PFLAG_SKIP_DRAW;
8663                }
8664            } else {
8665                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
8666            }
8667            requestLayout();
8668            invalidate(true);
8669        }
8670
8671        if ((changed & KEEP_SCREEN_ON) != 0) {
8672            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
8673                mParent.recomputeViewAttributes(this);
8674            }
8675        }
8676
8677        if (AccessibilityManager.getInstance(mContext).isEnabled()
8678                && ((changed & FOCUSABLE) != 0 || (changed & CLICKABLE) != 0
8679                        || (changed & LONG_CLICKABLE) != 0 || (changed & ENABLED) != 0)) {
8680            notifyAccessibilityStateChanged();
8681        }
8682    }
8683
8684    /**
8685     * Change the view's z order in the tree, so it's on top of other sibling
8686     * views
8687     */
8688    public void bringToFront() {
8689        if (mParent != null) {
8690            mParent.bringChildToFront(this);
8691        }
8692    }
8693
8694    /**
8695     * This is called in response to an internal scroll in this view (i.e., the
8696     * view scrolled its own contents). This is typically as a result of
8697     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
8698     * called.
8699     *
8700     * @param l Current horizontal scroll origin.
8701     * @param t Current vertical scroll origin.
8702     * @param oldl Previous horizontal scroll origin.
8703     * @param oldt Previous vertical scroll origin.
8704     */
8705    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
8706        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
8707            postSendViewScrolledAccessibilityEventCallback();
8708        }
8709
8710        mBackgroundSizeChanged = true;
8711
8712        final AttachInfo ai = mAttachInfo;
8713        if (ai != null) {
8714            ai.mViewScrollChanged = true;
8715        }
8716    }
8717
8718    /**
8719     * Interface definition for a callback to be invoked when the layout bounds of a view
8720     * changes due to layout processing.
8721     */
8722    public interface OnLayoutChangeListener {
8723        /**
8724         * Called when the focus state of a view has changed.
8725         *
8726         * @param v The view whose state has changed.
8727         * @param left The new value of the view's left property.
8728         * @param top The new value of the view's top property.
8729         * @param right The new value of the view's right property.
8730         * @param bottom The new value of the view's bottom property.
8731         * @param oldLeft The previous value of the view's left property.
8732         * @param oldTop The previous value of the view's top property.
8733         * @param oldRight The previous value of the view's right property.
8734         * @param oldBottom The previous value of the view's bottom property.
8735         */
8736        void onLayoutChange(View v, int left, int top, int right, int bottom,
8737            int oldLeft, int oldTop, int oldRight, int oldBottom);
8738    }
8739
8740    /**
8741     * This is called during layout when the size of this view has changed. If
8742     * you were just added to the view hierarchy, you're called with the old
8743     * values of 0.
8744     *
8745     * @param w Current width of this view.
8746     * @param h Current height of this view.
8747     * @param oldw Old width of this view.
8748     * @param oldh Old height of this view.
8749     */
8750    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
8751    }
8752
8753    /**
8754     * Called by draw to draw the child views. This may be overridden
8755     * by derived classes to gain control just before its children are drawn
8756     * (but after its own view has been drawn).
8757     * @param canvas the canvas on which to draw the view
8758     */
8759    protected void dispatchDraw(Canvas canvas) {
8760
8761    }
8762
8763    /**
8764     * Gets the parent of this view. Note that the parent is a
8765     * ViewParent and not necessarily a View.
8766     *
8767     * @return Parent of this view.
8768     */
8769    public final ViewParent getParent() {
8770        return mParent;
8771    }
8772
8773    /**
8774     * Set the horizontal scrolled position of your view. This will cause a call to
8775     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8776     * invalidated.
8777     * @param value the x position to scroll to
8778     */
8779    public void setScrollX(int value) {
8780        scrollTo(value, mScrollY);
8781    }
8782
8783    /**
8784     * Set the vertical scrolled position of your view. This will cause a call to
8785     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8786     * invalidated.
8787     * @param value the y position to scroll to
8788     */
8789    public void setScrollY(int value) {
8790        scrollTo(mScrollX, value);
8791    }
8792
8793    /**
8794     * Return the scrolled left position of this view. This is the left edge of
8795     * the displayed part of your view. You do not need to draw any pixels
8796     * farther left, since those are outside of the frame of your view on
8797     * screen.
8798     *
8799     * @return The left edge of the displayed part of your view, in pixels.
8800     */
8801    public final int getScrollX() {
8802        return mScrollX;
8803    }
8804
8805    /**
8806     * Return the scrolled top position of this view. This is the top edge of
8807     * the displayed part of your view. You do not need to draw any pixels above
8808     * it, since those are outside of the frame of your view on screen.
8809     *
8810     * @return The top edge of the displayed part of your view, in pixels.
8811     */
8812    public final int getScrollY() {
8813        return mScrollY;
8814    }
8815
8816    /**
8817     * Return the width of the your view.
8818     *
8819     * @return The width of your view, in pixels.
8820     */
8821    @ViewDebug.ExportedProperty(category = "layout")
8822    public final int getWidth() {
8823        return mRight - mLeft;
8824    }
8825
8826    /**
8827     * Return the height of your view.
8828     *
8829     * @return The height of your view, in pixels.
8830     */
8831    @ViewDebug.ExportedProperty(category = "layout")
8832    public final int getHeight() {
8833        return mBottom - mTop;
8834    }
8835
8836    /**
8837     * Return the visible drawing bounds of your view. Fills in the output
8838     * rectangle with the values from getScrollX(), getScrollY(),
8839     * getWidth(), and getHeight(). These bounds do not account for any
8840     * transformation properties currently set on the view, such as
8841     * {@link #setScaleX(float)} or {@link #setRotation(float)}.
8842     *
8843     * @param outRect The (scrolled) drawing bounds of the view.
8844     */
8845    public void getDrawingRect(Rect outRect) {
8846        outRect.left = mScrollX;
8847        outRect.top = mScrollY;
8848        outRect.right = mScrollX + (mRight - mLeft);
8849        outRect.bottom = mScrollY + (mBottom - mTop);
8850    }
8851
8852    /**
8853     * Like {@link #getMeasuredWidthAndState()}, but only returns the
8854     * raw width component (that is the result is masked by
8855     * {@link #MEASURED_SIZE_MASK}).
8856     *
8857     * @return The raw measured width of this view.
8858     */
8859    public final int getMeasuredWidth() {
8860        return mMeasuredWidth & MEASURED_SIZE_MASK;
8861    }
8862
8863    /**
8864     * Return the full width measurement information for this view as computed
8865     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8866     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8867     * This should be used during measurement and layout calculations only. Use
8868     * {@link #getWidth()} to see how wide a view is after layout.
8869     *
8870     * @return The measured width of this view as a bit mask.
8871     */
8872    public final int getMeasuredWidthAndState() {
8873        return mMeasuredWidth;
8874    }
8875
8876    /**
8877     * Like {@link #getMeasuredHeightAndState()}, but only returns the
8878     * raw width component (that is the result is masked by
8879     * {@link #MEASURED_SIZE_MASK}).
8880     *
8881     * @return The raw measured height of this view.
8882     */
8883    public final int getMeasuredHeight() {
8884        return mMeasuredHeight & MEASURED_SIZE_MASK;
8885    }
8886
8887    /**
8888     * Return the full height measurement information for this view as computed
8889     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
8890     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
8891     * This should be used during measurement and layout calculations only. Use
8892     * {@link #getHeight()} to see how wide a view is after layout.
8893     *
8894     * @return The measured width of this view as a bit mask.
8895     */
8896    public final int getMeasuredHeightAndState() {
8897        return mMeasuredHeight;
8898    }
8899
8900    /**
8901     * Return only the state bits of {@link #getMeasuredWidthAndState()}
8902     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
8903     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
8904     * and the height component is at the shifted bits
8905     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
8906     */
8907    public final int getMeasuredState() {
8908        return (mMeasuredWidth&MEASURED_STATE_MASK)
8909                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
8910                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
8911    }
8912
8913    /**
8914     * The transform matrix of this view, which is calculated based on the current
8915     * roation, scale, and pivot properties.
8916     *
8917     * @see #getRotation()
8918     * @see #getScaleX()
8919     * @see #getScaleY()
8920     * @see #getPivotX()
8921     * @see #getPivotY()
8922     * @return The current transform matrix for the view
8923     */
8924    public Matrix getMatrix() {
8925        if (mTransformationInfo != null) {
8926            updateMatrix();
8927            return mTransformationInfo.mMatrix;
8928        }
8929        return Matrix.IDENTITY_MATRIX;
8930    }
8931
8932    /**
8933     * Utility function to determine if the value is far enough away from zero to be
8934     * considered non-zero.
8935     * @param value A floating point value to check for zero-ness
8936     * @return whether the passed-in value is far enough away from zero to be considered non-zero
8937     */
8938    private static boolean nonzero(float value) {
8939        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
8940    }
8941
8942    /**
8943     * Returns true if the transform matrix is the identity matrix.
8944     * Recomputes the matrix if necessary.
8945     *
8946     * @return True if the transform matrix is the identity matrix, false otherwise.
8947     */
8948    final boolean hasIdentityMatrix() {
8949        if (mTransformationInfo != null) {
8950            updateMatrix();
8951            return mTransformationInfo.mMatrixIsIdentity;
8952        }
8953        return true;
8954    }
8955
8956    void ensureTransformationInfo() {
8957        if (mTransformationInfo == null) {
8958            mTransformationInfo = new TransformationInfo();
8959        }
8960    }
8961
8962    /**
8963     * Recomputes the transform matrix if necessary.
8964     */
8965    private void updateMatrix() {
8966        final TransformationInfo info = mTransformationInfo;
8967        if (info == null) {
8968            return;
8969        }
8970        if (info.mMatrixDirty) {
8971            // transform-related properties have changed since the last time someone
8972            // asked for the matrix; recalculate it with the current values
8973
8974            // Figure out if we need to update the pivot point
8975            if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
8976                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
8977                    info.mPrevWidth = mRight - mLeft;
8978                    info.mPrevHeight = mBottom - mTop;
8979                    info.mPivotX = info.mPrevWidth / 2f;
8980                    info.mPivotY = info.mPrevHeight / 2f;
8981                }
8982            }
8983            info.mMatrix.reset();
8984            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
8985                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
8986                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
8987                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8988            } else {
8989                if (info.mCamera == null) {
8990                    info.mCamera = new Camera();
8991                    info.matrix3D = new Matrix();
8992                }
8993                info.mCamera.save();
8994                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
8995                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
8996                info.mCamera.getMatrix(info.matrix3D);
8997                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
8998                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
8999                        info.mPivotY + info.mTranslationY);
9000                info.mMatrix.postConcat(info.matrix3D);
9001                info.mCamera.restore();
9002            }
9003            info.mMatrixDirty = false;
9004            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
9005            info.mInverseMatrixDirty = true;
9006        }
9007    }
9008
9009   /**
9010     * Utility method to retrieve the inverse of the current mMatrix property.
9011     * We cache the matrix to avoid recalculating it when transform properties
9012     * have not changed.
9013     *
9014     * @return The inverse of the current matrix of this view.
9015     */
9016    final Matrix getInverseMatrix() {
9017        final TransformationInfo info = mTransformationInfo;
9018        if (info != null) {
9019            updateMatrix();
9020            if (info.mInverseMatrixDirty) {
9021                if (info.mInverseMatrix == null) {
9022                    info.mInverseMatrix = new Matrix();
9023                }
9024                info.mMatrix.invert(info.mInverseMatrix);
9025                info.mInverseMatrixDirty = false;
9026            }
9027            return info.mInverseMatrix;
9028        }
9029        return Matrix.IDENTITY_MATRIX;
9030    }
9031
9032    /**
9033     * Gets the distance along the Z axis from the camera to this view.
9034     *
9035     * @see #setCameraDistance(float)
9036     *
9037     * @return The distance along the Z axis.
9038     */
9039    public float getCameraDistance() {
9040        ensureTransformationInfo();
9041        final float dpi = mResources.getDisplayMetrics().densityDpi;
9042        final TransformationInfo info = mTransformationInfo;
9043        if (info.mCamera == null) {
9044            info.mCamera = new Camera();
9045            info.matrix3D = new Matrix();
9046        }
9047        return -(info.mCamera.getLocationZ() * dpi);
9048    }
9049
9050    /**
9051     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
9052     * views are drawn) from the camera to this view. The camera's distance
9053     * affects 3D transformations, for instance rotations around the X and Y
9054     * axis. If the rotationX or rotationY properties are changed and this view is
9055     * large (more than half the size of the screen), it is recommended to always
9056     * use a camera distance that's greater than the height (X axis rotation) or
9057     * the width (Y axis rotation) of this view.</p>
9058     *
9059     * <p>The distance of the camera from the view plane can have an affect on the
9060     * perspective distortion of the view when it is rotated around the x or y axis.
9061     * For example, a large distance will result in a large viewing angle, and there
9062     * will not be much perspective distortion of the view as it rotates. A short
9063     * distance may cause much more perspective distortion upon rotation, and can
9064     * also result in some drawing artifacts if the rotated view ends up partially
9065     * behind the camera (which is why the recommendation is to use a distance at
9066     * least as far as the size of the view, if the view is to be rotated.)</p>
9067     *
9068     * <p>The distance is expressed in "depth pixels." The default distance depends
9069     * on the screen density. For instance, on a medium density display, the
9070     * default distance is 1280. On a high density display, the default distance
9071     * is 1920.</p>
9072     *
9073     * <p>If you want to specify a distance that leads to visually consistent
9074     * results across various densities, use the following formula:</p>
9075     * <pre>
9076     * float scale = context.getResources().getDisplayMetrics().density;
9077     * view.setCameraDistance(distance * scale);
9078     * </pre>
9079     *
9080     * <p>The density scale factor of a high density display is 1.5,
9081     * and 1920 = 1280 * 1.5.</p>
9082     *
9083     * @param distance The distance in "depth pixels", if negative the opposite
9084     *        value is used
9085     *
9086     * @see #setRotationX(float)
9087     * @see #setRotationY(float)
9088     */
9089    public void setCameraDistance(float distance) {
9090        invalidateViewProperty(true, false);
9091
9092        ensureTransformationInfo();
9093        final float dpi = mResources.getDisplayMetrics().densityDpi;
9094        final TransformationInfo info = mTransformationInfo;
9095        if (info.mCamera == null) {
9096            info.mCamera = new Camera();
9097            info.matrix3D = new Matrix();
9098        }
9099
9100        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
9101        info.mMatrixDirty = true;
9102
9103        invalidateViewProperty(false, false);
9104        if (mDisplayList != null) {
9105            mDisplayList.setCameraDistance(-Math.abs(distance) / dpi);
9106        }
9107        if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9108            // View was rejected last time it was drawn by its parent; this may have changed
9109            invalidateParentIfNeeded();
9110        }
9111    }
9112
9113    /**
9114     * The degrees that the view is rotated around the pivot point.
9115     *
9116     * @see #setRotation(float)
9117     * @see #getPivotX()
9118     * @see #getPivotY()
9119     *
9120     * @return The degrees of rotation.
9121     */
9122    @ViewDebug.ExportedProperty(category = "drawing")
9123    public float getRotation() {
9124        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
9125    }
9126
9127    /**
9128     * Sets the degrees that the view is rotated around the pivot point. Increasing values
9129     * result in clockwise rotation.
9130     *
9131     * @param rotation The degrees of rotation.
9132     *
9133     * @see #getRotation()
9134     * @see #getPivotX()
9135     * @see #getPivotY()
9136     * @see #setRotationX(float)
9137     * @see #setRotationY(float)
9138     *
9139     * @attr ref android.R.styleable#View_rotation
9140     */
9141    public void setRotation(float rotation) {
9142        ensureTransformationInfo();
9143        final TransformationInfo info = mTransformationInfo;
9144        if (info.mRotation != rotation) {
9145            // Double-invalidation is necessary to capture view's old and new areas
9146            invalidateViewProperty(true, false);
9147            info.mRotation = rotation;
9148            info.mMatrixDirty = true;
9149            invalidateViewProperty(false, true);
9150            if (mDisplayList != null) {
9151                mDisplayList.setRotation(rotation);
9152            }
9153            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9154                // View was rejected last time it was drawn by its parent; this may have changed
9155                invalidateParentIfNeeded();
9156            }
9157        }
9158    }
9159
9160    /**
9161     * The degrees that the view is rotated around the vertical axis through the pivot point.
9162     *
9163     * @see #getPivotX()
9164     * @see #getPivotY()
9165     * @see #setRotationY(float)
9166     *
9167     * @return The degrees of Y rotation.
9168     */
9169    @ViewDebug.ExportedProperty(category = "drawing")
9170    public float getRotationY() {
9171        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
9172    }
9173
9174    /**
9175     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
9176     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
9177     * down the y axis.
9178     *
9179     * When rotating large views, it is recommended to adjust the camera distance
9180     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9181     *
9182     * @param rotationY The degrees of Y rotation.
9183     *
9184     * @see #getRotationY()
9185     * @see #getPivotX()
9186     * @see #getPivotY()
9187     * @see #setRotation(float)
9188     * @see #setRotationX(float)
9189     * @see #setCameraDistance(float)
9190     *
9191     * @attr ref android.R.styleable#View_rotationY
9192     */
9193    public void setRotationY(float rotationY) {
9194        ensureTransformationInfo();
9195        final TransformationInfo info = mTransformationInfo;
9196        if (info.mRotationY != rotationY) {
9197            invalidateViewProperty(true, false);
9198            info.mRotationY = rotationY;
9199            info.mMatrixDirty = true;
9200            invalidateViewProperty(false, true);
9201            if (mDisplayList != null) {
9202                mDisplayList.setRotationY(rotationY);
9203            }
9204            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9205                // View was rejected last time it was drawn by its parent; this may have changed
9206                invalidateParentIfNeeded();
9207            }
9208        }
9209    }
9210
9211    /**
9212     * The degrees that the view is rotated around the horizontal axis through the pivot point.
9213     *
9214     * @see #getPivotX()
9215     * @see #getPivotY()
9216     * @see #setRotationX(float)
9217     *
9218     * @return The degrees of X rotation.
9219     */
9220    @ViewDebug.ExportedProperty(category = "drawing")
9221    public float getRotationX() {
9222        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
9223    }
9224
9225    /**
9226     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
9227     * Increasing values result in clockwise rotation from the viewpoint of looking down the
9228     * x axis.
9229     *
9230     * When rotating large views, it is recommended to adjust the camera distance
9231     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
9232     *
9233     * @param rotationX The degrees of X rotation.
9234     *
9235     * @see #getRotationX()
9236     * @see #getPivotX()
9237     * @see #getPivotY()
9238     * @see #setRotation(float)
9239     * @see #setRotationY(float)
9240     * @see #setCameraDistance(float)
9241     *
9242     * @attr ref android.R.styleable#View_rotationX
9243     */
9244    public void setRotationX(float rotationX) {
9245        ensureTransformationInfo();
9246        final TransformationInfo info = mTransformationInfo;
9247        if (info.mRotationX != rotationX) {
9248            invalidateViewProperty(true, false);
9249            info.mRotationX = rotationX;
9250            info.mMatrixDirty = true;
9251            invalidateViewProperty(false, true);
9252            if (mDisplayList != null) {
9253                mDisplayList.setRotationX(rotationX);
9254            }
9255            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9256                // View was rejected last time it was drawn by its parent; this may have changed
9257                invalidateParentIfNeeded();
9258            }
9259        }
9260    }
9261
9262    /**
9263     * The amount that the view is scaled in x around the pivot point, as a proportion of
9264     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
9265     *
9266     * <p>By default, this is 1.0f.
9267     *
9268     * @see #getPivotX()
9269     * @see #getPivotY()
9270     * @return The scaling factor.
9271     */
9272    @ViewDebug.ExportedProperty(category = "drawing")
9273    public float getScaleX() {
9274        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
9275    }
9276
9277    /**
9278     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
9279     * the view's unscaled width. A value of 1 means that no scaling is applied.
9280     *
9281     * @param scaleX The scaling factor.
9282     * @see #getPivotX()
9283     * @see #getPivotY()
9284     *
9285     * @attr ref android.R.styleable#View_scaleX
9286     */
9287    public void setScaleX(float scaleX) {
9288        ensureTransformationInfo();
9289        final TransformationInfo info = mTransformationInfo;
9290        if (info.mScaleX != scaleX) {
9291            invalidateViewProperty(true, false);
9292            info.mScaleX = scaleX;
9293            info.mMatrixDirty = true;
9294            invalidateViewProperty(false, true);
9295            if (mDisplayList != null) {
9296                mDisplayList.setScaleX(scaleX);
9297            }
9298            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9299                // View was rejected last time it was drawn by its parent; this may have changed
9300                invalidateParentIfNeeded();
9301            }
9302        }
9303    }
9304
9305    /**
9306     * The amount that the view is scaled in y around the pivot point, as a proportion of
9307     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
9308     *
9309     * <p>By default, this is 1.0f.
9310     *
9311     * @see #getPivotX()
9312     * @see #getPivotY()
9313     * @return The scaling factor.
9314     */
9315    @ViewDebug.ExportedProperty(category = "drawing")
9316    public float getScaleY() {
9317        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
9318    }
9319
9320    /**
9321     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
9322     * the view's unscaled width. A value of 1 means that no scaling is applied.
9323     *
9324     * @param scaleY The scaling factor.
9325     * @see #getPivotX()
9326     * @see #getPivotY()
9327     *
9328     * @attr ref android.R.styleable#View_scaleY
9329     */
9330    public void setScaleY(float scaleY) {
9331        ensureTransformationInfo();
9332        final TransformationInfo info = mTransformationInfo;
9333        if (info.mScaleY != scaleY) {
9334            invalidateViewProperty(true, false);
9335            info.mScaleY = scaleY;
9336            info.mMatrixDirty = true;
9337            invalidateViewProperty(false, true);
9338            if (mDisplayList != null) {
9339                mDisplayList.setScaleY(scaleY);
9340            }
9341            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9342                // View was rejected last time it was drawn by its parent; this may have changed
9343                invalidateParentIfNeeded();
9344            }
9345        }
9346    }
9347
9348    /**
9349     * The x location of the point around which the view is {@link #setRotation(float) rotated}
9350     * and {@link #setScaleX(float) scaled}.
9351     *
9352     * @see #getRotation()
9353     * @see #getScaleX()
9354     * @see #getScaleY()
9355     * @see #getPivotY()
9356     * @return The x location of the pivot point.
9357     *
9358     * @attr ref android.R.styleable#View_transformPivotX
9359     */
9360    @ViewDebug.ExportedProperty(category = "drawing")
9361    public float getPivotX() {
9362        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
9363    }
9364
9365    /**
9366     * Sets the x location of the point around which the view is
9367     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
9368     * By default, the pivot point is centered on the object.
9369     * Setting this property disables this behavior and causes the view to use only the
9370     * explicitly set pivotX and pivotY values.
9371     *
9372     * @param pivotX The x location of the pivot point.
9373     * @see #getRotation()
9374     * @see #getScaleX()
9375     * @see #getScaleY()
9376     * @see #getPivotY()
9377     *
9378     * @attr ref android.R.styleable#View_transformPivotX
9379     */
9380    public void setPivotX(float pivotX) {
9381        ensureTransformationInfo();
9382        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9383        final TransformationInfo info = mTransformationInfo;
9384        if (info.mPivotX != pivotX) {
9385            invalidateViewProperty(true, false);
9386            info.mPivotX = pivotX;
9387            info.mMatrixDirty = true;
9388            invalidateViewProperty(false, true);
9389            if (mDisplayList != null) {
9390                mDisplayList.setPivotX(pivotX);
9391            }
9392            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9393                // View was rejected last time it was drawn by its parent; this may have changed
9394                invalidateParentIfNeeded();
9395            }
9396        }
9397    }
9398
9399    /**
9400     * The y location of the point around which the view is {@link #setRotation(float) rotated}
9401     * and {@link #setScaleY(float) scaled}.
9402     *
9403     * @see #getRotation()
9404     * @see #getScaleX()
9405     * @see #getScaleY()
9406     * @see #getPivotY()
9407     * @return The y location of the pivot point.
9408     *
9409     * @attr ref android.R.styleable#View_transformPivotY
9410     */
9411    @ViewDebug.ExportedProperty(category = "drawing")
9412    public float getPivotY() {
9413        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
9414    }
9415
9416    /**
9417     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
9418     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
9419     * Setting this property disables this behavior and causes the view to use only the
9420     * explicitly set pivotX and pivotY values.
9421     *
9422     * @param pivotY The y location of the pivot point.
9423     * @see #getRotation()
9424     * @see #getScaleX()
9425     * @see #getScaleY()
9426     * @see #getPivotY()
9427     *
9428     * @attr ref android.R.styleable#View_transformPivotY
9429     */
9430    public void setPivotY(float pivotY) {
9431        ensureTransformationInfo();
9432        mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET;
9433        final TransformationInfo info = mTransformationInfo;
9434        if (info.mPivotY != pivotY) {
9435            invalidateViewProperty(true, false);
9436            info.mPivotY = pivotY;
9437            info.mMatrixDirty = true;
9438            invalidateViewProperty(false, true);
9439            if (mDisplayList != null) {
9440                mDisplayList.setPivotY(pivotY);
9441            }
9442            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9443                // View was rejected last time it was drawn by its parent; this may have changed
9444                invalidateParentIfNeeded();
9445            }
9446        }
9447    }
9448
9449    /**
9450     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
9451     * completely transparent and 1 means the view is completely opaque.
9452     *
9453     * <p>By default this is 1.0f.
9454     * @return The opacity of the view.
9455     */
9456    @ViewDebug.ExportedProperty(category = "drawing")
9457    public float getAlpha() {
9458        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
9459    }
9460
9461    /**
9462     * Returns whether this View has content which overlaps. This function, intended to be
9463     * overridden by specific View types, is an optimization when alpha is set on a view. If
9464     * rendering overlaps in a view with alpha < 1, that view is drawn to an offscreen buffer
9465     * and then composited it into place, which can be expensive. If the view has no overlapping
9466     * rendering, the view can draw each primitive with the appropriate alpha value directly.
9467     * An example of overlapping rendering is a TextView with a background image, such as a
9468     * Button. An example of non-overlapping rendering is a TextView with no background, or
9469     * an ImageView with only the foreground image. The default implementation returns true;
9470     * subclasses should override if they have cases which can be optimized.
9471     *
9472     * @return true if the content in this view might overlap, false otherwise.
9473     */
9474    public boolean hasOverlappingRendering() {
9475        return true;
9476    }
9477
9478    /**
9479     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
9480     * completely transparent and 1 means the view is completely opaque.</p>
9481     *
9482     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
9483     * responsible for applying the opacity itself. Otherwise, calling this method is
9484     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
9485     * setting a hardware layer.</p>
9486     *
9487     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
9488     * performance implications. It is generally best to use the alpha property sparingly and
9489     * transiently, as in the case of fading animations.</p>
9490     *
9491     * @param alpha The opacity of the view.
9492     *
9493     * @see #setLayerType(int, android.graphics.Paint)
9494     *
9495     * @attr ref android.R.styleable#View_alpha
9496     */
9497    public void setAlpha(float alpha) {
9498        ensureTransformationInfo();
9499        if (mTransformationInfo.mAlpha != alpha) {
9500            mTransformationInfo.mAlpha = alpha;
9501            if (onSetAlpha((int) (alpha * 255))) {
9502                mPrivateFlags |= PFLAG_ALPHA_SET;
9503                // subclass is handling alpha - don't optimize rendering cache invalidation
9504                invalidateParentCaches();
9505                invalidate(true);
9506            } else {
9507                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9508                invalidateViewProperty(true, false);
9509                if (mDisplayList != null) {
9510                    mDisplayList.setAlpha(alpha);
9511                }
9512            }
9513        }
9514    }
9515
9516    /**
9517     * Faster version of setAlpha() which performs the same steps except there are
9518     * no calls to invalidate(). The caller of this function should perform proper invalidation
9519     * on the parent and this object. The return value indicates whether the subclass handles
9520     * alpha (the return value for onSetAlpha()).
9521     *
9522     * @param alpha The new value for the alpha property
9523     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
9524     *         the new value for the alpha property is different from the old value
9525     */
9526    boolean setAlphaNoInvalidation(float alpha) {
9527        ensureTransformationInfo();
9528        if (mTransformationInfo.mAlpha != alpha) {
9529            mTransformationInfo.mAlpha = alpha;
9530            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
9531            if (subclassHandlesAlpha) {
9532                mPrivateFlags |= PFLAG_ALPHA_SET;
9533                return true;
9534            } else {
9535                mPrivateFlags &= ~PFLAG_ALPHA_SET;
9536                if (mDisplayList != null) {
9537                    mDisplayList.setAlpha(alpha);
9538                }
9539            }
9540        }
9541        return false;
9542    }
9543
9544    /**
9545     * Top position of this view relative to its parent.
9546     *
9547     * @return The top of this view, in pixels.
9548     */
9549    @ViewDebug.CapturedViewProperty
9550    public final int getTop() {
9551        return mTop;
9552    }
9553
9554    /**
9555     * Sets the top position of this view relative to its parent. This method is meant to be called
9556     * by the layout system and should not generally be called otherwise, because the property
9557     * may be changed at any time by the layout.
9558     *
9559     * @param top The top of this view, in pixels.
9560     */
9561    public final void setTop(int top) {
9562        if (top != mTop) {
9563            updateMatrix();
9564            final boolean matrixIsIdentity = mTransformationInfo == null
9565                    || mTransformationInfo.mMatrixIsIdentity;
9566            if (matrixIsIdentity) {
9567                if (mAttachInfo != null) {
9568                    int minTop;
9569                    int yLoc;
9570                    if (top < mTop) {
9571                        minTop = top;
9572                        yLoc = top - mTop;
9573                    } else {
9574                        minTop = mTop;
9575                        yLoc = 0;
9576                    }
9577                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
9578                }
9579            } else {
9580                // Double-invalidation is necessary to capture view's old and new areas
9581                invalidate(true);
9582            }
9583
9584            int width = mRight - mLeft;
9585            int oldHeight = mBottom - mTop;
9586
9587            mTop = top;
9588            if (mDisplayList != null) {
9589                mDisplayList.setTop(mTop);
9590            }
9591
9592            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9593
9594            if (!matrixIsIdentity) {
9595                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9596                    // A change in dimension means an auto-centered pivot point changes, too
9597                    mTransformationInfo.mMatrixDirty = true;
9598                }
9599                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9600                invalidate(true);
9601            }
9602            mBackgroundSizeChanged = true;
9603            invalidateParentIfNeeded();
9604            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9605                // View was rejected last time it was drawn by its parent; this may have changed
9606                invalidateParentIfNeeded();
9607            }
9608        }
9609    }
9610
9611    /**
9612     * Bottom position of this view relative to its parent.
9613     *
9614     * @return The bottom of this view, in pixels.
9615     */
9616    @ViewDebug.CapturedViewProperty
9617    public final int getBottom() {
9618        return mBottom;
9619    }
9620
9621    /**
9622     * True if this view has changed since the last time being drawn.
9623     *
9624     * @return The dirty state of this view.
9625     */
9626    public boolean isDirty() {
9627        return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0;
9628    }
9629
9630    /**
9631     * Sets the bottom position of this view relative to its parent. This method is meant to be
9632     * called by the layout system and should not generally be called otherwise, because the
9633     * property may be changed at any time by the layout.
9634     *
9635     * @param bottom The bottom of this view, in pixels.
9636     */
9637    public final void setBottom(int bottom) {
9638        if (bottom != mBottom) {
9639            updateMatrix();
9640            final boolean matrixIsIdentity = mTransformationInfo == null
9641                    || mTransformationInfo.mMatrixIsIdentity;
9642            if (matrixIsIdentity) {
9643                if (mAttachInfo != null) {
9644                    int maxBottom;
9645                    if (bottom < mBottom) {
9646                        maxBottom = mBottom;
9647                    } else {
9648                        maxBottom = bottom;
9649                    }
9650                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
9651                }
9652            } else {
9653                // Double-invalidation is necessary to capture view's old and new areas
9654                invalidate(true);
9655            }
9656
9657            int width = mRight - mLeft;
9658            int oldHeight = mBottom - mTop;
9659
9660            mBottom = bottom;
9661            if (mDisplayList != null) {
9662                mDisplayList.setBottom(mBottom);
9663            }
9664
9665            onSizeChanged(width, mBottom - mTop, width, oldHeight);
9666
9667            if (!matrixIsIdentity) {
9668                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9669                    // A change in dimension means an auto-centered pivot point changes, too
9670                    mTransformationInfo.mMatrixDirty = true;
9671                }
9672                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9673                invalidate(true);
9674            }
9675            mBackgroundSizeChanged = true;
9676            invalidateParentIfNeeded();
9677            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9678                // View was rejected last time it was drawn by its parent; this may have changed
9679                invalidateParentIfNeeded();
9680            }
9681        }
9682    }
9683
9684    /**
9685     * Left position of this view relative to its parent.
9686     *
9687     * @return The left edge of this view, in pixels.
9688     */
9689    @ViewDebug.CapturedViewProperty
9690    public final int getLeft() {
9691        return mLeft;
9692    }
9693
9694    /**
9695     * Sets the left position of this view relative to its parent. This method is meant to be called
9696     * by the layout system and should not generally be called otherwise, because the property
9697     * may be changed at any time by the layout.
9698     *
9699     * @param left The bottom of this view, in pixels.
9700     */
9701    public final void setLeft(int left) {
9702        if (left != mLeft) {
9703            updateMatrix();
9704            final boolean matrixIsIdentity = mTransformationInfo == null
9705                    || mTransformationInfo.mMatrixIsIdentity;
9706            if (matrixIsIdentity) {
9707                if (mAttachInfo != null) {
9708                    int minLeft;
9709                    int xLoc;
9710                    if (left < mLeft) {
9711                        minLeft = left;
9712                        xLoc = left - mLeft;
9713                    } else {
9714                        minLeft = mLeft;
9715                        xLoc = 0;
9716                    }
9717                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
9718                }
9719            } else {
9720                // Double-invalidation is necessary to capture view's old and new areas
9721                invalidate(true);
9722            }
9723
9724            int oldWidth = mRight - mLeft;
9725            int height = mBottom - mTop;
9726
9727            mLeft = left;
9728            if (mDisplayList != null) {
9729                mDisplayList.setLeft(left);
9730            }
9731
9732            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9733
9734            if (!matrixIsIdentity) {
9735                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9736                    // A change in dimension means an auto-centered pivot point changes, too
9737                    mTransformationInfo.mMatrixDirty = true;
9738                }
9739                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9740                invalidate(true);
9741            }
9742            mBackgroundSizeChanged = true;
9743            invalidateParentIfNeeded();
9744            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9745                // View was rejected last time it was drawn by its parent; this may have changed
9746                invalidateParentIfNeeded();
9747            }
9748        }
9749    }
9750
9751    /**
9752     * Right position of this view relative to its parent.
9753     *
9754     * @return The right edge of this view, in pixels.
9755     */
9756    @ViewDebug.CapturedViewProperty
9757    public final int getRight() {
9758        return mRight;
9759    }
9760
9761    /**
9762     * Sets the right position of this view relative to its parent. This method is meant to be called
9763     * by the layout system and should not generally be called otherwise, because the property
9764     * may be changed at any time by the layout.
9765     *
9766     * @param right The bottom of this view, in pixels.
9767     */
9768    public final void setRight(int right) {
9769        if (right != mRight) {
9770            updateMatrix();
9771            final boolean matrixIsIdentity = mTransformationInfo == null
9772                    || mTransformationInfo.mMatrixIsIdentity;
9773            if (matrixIsIdentity) {
9774                if (mAttachInfo != null) {
9775                    int maxRight;
9776                    if (right < mRight) {
9777                        maxRight = mRight;
9778                    } else {
9779                        maxRight = right;
9780                    }
9781                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
9782                }
9783            } else {
9784                // Double-invalidation is necessary to capture view's old and new areas
9785                invalidate(true);
9786            }
9787
9788            int oldWidth = mRight - mLeft;
9789            int height = mBottom - mTop;
9790
9791            mRight = right;
9792            if (mDisplayList != null) {
9793                mDisplayList.setRight(mRight);
9794            }
9795
9796            onSizeChanged(mRight - mLeft, height, oldWidth, height);
9797
9798            if (!matrixIsIdentity) {
9799                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
9800                    // A change in dimension means an auto-centered pivot point changes, too
9801                    mTransformationInfo.mMatrixDirty = true;
9802                }
9803                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
9804                invalidate(true);
9805            }
9806            mBackgroundSizeChanged = true;
9807            invalidateParentIfNeeded();
9808            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9809                // View was rejected last time it was drawn by its parent; this may have changed
9810                invalidateParentIfNeeded();
9811            }
9812        }
9813    }
9814
9815    /**
9816     * The visual x position of this view, in pixels. This is equivalent to the
9817     * {@link #setTranslationX(float) translationX} property plus the current
9818     * {@link #getLeft() left} property.
9819     *
9820     * @return The visual x position of this view, in pixels.
9821     */
9822    @ViewDebug.ExportedProperty(category = "drawing")
9823    public float getX() {
9824        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
9825    }
9826
9827    /**
9828     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
9829     * {@link #setTranslationX(float) translationX} property to be the difference between
9830     * the x value passed in and the current {@link #getLeft() left} property.
9831     *
9832     * @param x The visual x position of this view, in pixels.
9833     */
9834    public void setX(float x) {
9835        setTranslationX(x - mLeft);
9836    }
9837
9838    /**
9839     * The visual y position of this view, in pixels. This is equivalent to the
9840     * {@link #setTranslationY(float) translationY} property plus the current
9841     * {@link #getTop() top} property.
9842     *
9843     * @return The visual y position of this view, in pixels.
9844     */
9845    @ViewDebug.ExportedProperty(category = "drawing")
9846    public float getY() {
9847        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
9848    }
9849
9850    /**
9851     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
9852     * {@link #setTranslationY(float) translationY} property to be the difference between
9853     * the y value passed in and the current {@link #getTop() top} property.
9854     *
9855     * @param y The visual y position of this view, in pixels.
9856     */
9857    public void setY(float y) {
9858        setTranslationY(y - mTop);
9859    }
9860
9861
9862    /**
9863     * The horizontal location of this view relative to its {@link #getLeft() left} position.
9864     * This position is post-layout, in addition to wherever the object's
9865     * layout placed it.
9866     *
9867     * @return The horizontal position of this view relative to its left position, in pixels.
9868     */
9869    @ViewDebug.ExportedProperty(category = "drawing")
9870    public float getTranslationX() {
9871        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
9872    }
9873
9874    /**
9875     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
9876     * This effectively positions the object post-layout, in addition to wherever the object's
9877     * layout placed it.
9878     *
9879     * @param translationX The horizontal position of this view relative to its left position,
9880     * in pixels.
9881     *
9882     * @attr ref android.R.styleable#View_translationX
9883     */
9884    public void setTranslationX(float translationX) {
9885        ensureTransformationInfo();
9886        final TransformationInfo info = mTransformationInfo;
9887        if (info.mTranslationX != translationX) {
9888            // Double-invalidation is necessary to capture view's old and new areas
9889            invalidateViewProperty(true, false);
9890            info.mTranslationX = translationX;
9891            info.mMatrixDirty = true;
9892            invalidateViewProperty(false, true);
9893            if (mDisplayList != null) {
9894                mDisplayList.setTranslationX(translationX);
9895            }
9896            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9897                // View was rejected last time it was drawn by its parent; this may have changed
9898                invalidateParentIfNeeded();
9899            }
9900        }
9901    }
9902
9903    /**
9904     * The horizontal location of this view relative to its {@link #getTop() top} position.
9905     * This position is post-layout, in addition to wherever the object's
9906     * layout placed it.
9907     *
9908     * @return The vertical position of this view relative to its top position,
9909     * in pixels.
9910     */
9911    @ViewDebug.ExportedProperty(category = "drawing")
9912    public float getTranslationY() {
9913        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
9914    }
9915
9916    /**
9917     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
9918     * This effectively positions the object post-layout, in addition to wherever the object's
9919     * layout placed it.
9920     *
9921     * @param translationY The vertical position of this view relative to its top position,
9922     * in pixels.
9923     *
9924     * @attr ref android.R.styleable#View_translationY
9925     */
9926    public void setTranslationY(float translationY) {
9927        ensureTransformationInfo();
9928        final TransformationInfo info = mTransformationInfo;
9929        if (info.mTranslationY != translationY) {
9930            invalidateViewProperty(true, false);
9931            info.mTranslationY = translationY;
9932            info.mMatrixDirty = true;
9933            invalidateViewProperty(false, true);
9934            if (mDisplayList != null) {
9935                mDisplayList.setTranslationY(translationY);
9936            }
9937            if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) {
9938                // View was rejected last time it was drawn by its parent; this may have changed
9939                invalidateParentIfNeeded();
9940            }
9941        }
9942    }
9943
9944    /**
9945     * Hit rectangle in parent's coordinates
9946     *
9947     * @param outRect The hit rectangle of the view.
9948     */
9949    public void getHitRect(Rect outRect) {
9950        updateMatrix();
9951        final TransformationInfo info = mTransformationInfo;
9952        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
9953            outRect.set(mLeft, mTop, mRight, mBottom);
9954        } else {
9955            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
9956            tmpRect.set(0, 0, getWidth(), getHeight());
9957            info.mMatrix.mapRect(tmpRect);
9958            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
9959                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
9960        }
9961    }
9962
9963    /**
9964     * Determines whether the given point, in local coordinates is inside the view.
9965     */
9966    /*package*/ final boolean pointInView(float localX, float localY) {
9967        return localX >= 0 && localX < (mRight - mLeft)
9968                && localY >= 0 && localY < (mBottom - mTop);
9969    }
9970
9971    /**
9972     * Utility method to determine whether the given point, in local coordinates,
9973     * is inside the view, where the area of the view is expanded by the slop factor.
9974     * This method is called while processing touch-move events to determine if the event
9975     * is still within the view.
9976     */
9977    private boolean pointInView(float localX, float localY, float slop) {
9978        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
9979                localY < ((mBottom - mTop) + slop);
9980    }
9981
9982    /**
9983     * When a view has focus and the user navigates away from it, the next view is searched for
9984     * starting from the rectangle filled in by this method.
9985     *
9986     * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)})
9987     * of the view.  However, if your view maintains some idea of internal selection,
9988     * such as a cursor, or a selected row or column, you should override this method and
9989     * fill in a more specific rectangle.
9990     *
9991     * @param r The rectangle to fill in, in this view's coordinates.
9992     */
9993    public void getFocusedRect(Rect r) {
9994        getDrawingRect(r);
9995    }
9996
9997    /**
9998     * If some part of this view is not clipped by any of its parents, then
9999     * return that area in r in global (root) coordinates. To convert r to local
10000     * coordinates (without taking possible View rotations into account), offset
10001     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
10002     * If the view is completely clipped or translated out, return false.
10003     *
10004     * @param r If true is returned, r holds the global coordinates of the
10005     *        visible portion of this view.
10006     * @param globalOffset If true is returned, globalOffset holds the dx,dy
10007     *        between this view and its root. globalOffet may be null.
10008     * @return true if r is non-empty (i.e. part of the view is visible at the
10009     *         root level.
10010     */
10011    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
10012        int width = mRight - mLeft;
10013        int height = mBottom - mTop;
10014        if (width > 0 && height > 0) {
10015            r.set(0, 0, width, height);
10016            if (globalOffset != null) {
10017                globalOffset.set(-mScrollX, -mScrollY);
10018            }
10019            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
10020        }
10021        return false;
10022    }
10023
10024    public final boolean getGlobalVisibleRect(Rect r) {
10025        return getGlobalVisibleRect(r, null);
10026    }
10027
10028    public final boolean getLocalVisibleRect(Rect r) {
10029        final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point();
10030        if (getGlobalVisibleRect(r, offset)) {
10031            r.offset(-offset.x, -offset.y); // make r local
10032            return true;
10033        }
10034        return false;
10035    }
10036
10037    /**
10038     * Offset this view's vertical location by the specified number of pixels.
10039     *
10040     * @param offset the number of pixels to offset the view by
10041     */
10042    public void offsetTopAndBottom(int offset) {
10043        if (offset != 0) {
10044            updateMatrix();
10045            final boolean matrixIsIdentity = mTransformationInfo == null
10046                    || mTransformationInfo.mMatrixIsIdentity;
10047            if (matrixIsIdentity) {
10048                if (mDisplayList != null) {
10049                    invalidateViewProperty(false, false);
10050                } else {
10051                    final ViewParent p = mParent;
10052                    if (p != null && mAttachInfo != null) {
10053                        final Rect r = mAttachInfo.mTmpInvalRect;
10054                        int minTop;
10055                        int maxBottom;
10056                        int yLoc;
10057                        if (offset < 0) {
10058                            minTop = mTop + offset;
10059                            maxBottom = mBottom;
10060                            yLoc = offset;
10061                        } else {
10062                            minTop = mTop;
10063                            maxBottom = mBottom + offset;
10064                            yLoc = 0;
10065                        }
10066                        r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
10067                        p.invalidateChild(this, r);
10068                    }
10069                }
10070            } else {
10071                invalidateViewProperty(false, false);
10072            }
10073
10074            mTop += offset;
10075            mBottom += offset;
10076            if (mDisplayList != null) {
10077                mDisplayList.offsetTopAndBottom(offset);
10078                invalidateViewProperty(false, false);
10079            } else {
10080                if (!matrixIsIdentity) {
10081                    invalidateViewProperty(false, true);
10082                }
10083                invalidateParentIfNeeded();
10084            }
10085        }
10086    }
10087
10088    /**
10089     * Offset this view's horizontal location by the specified amount of pixels.
10090     *
10091     * @param offset the numer of pixels to offset the view by
10092     */
10093    public void offsetLeftAndRight(int offset) {
10094        if (offset != 0) {
10095            updateMatrix();
10096            final boolean matrixIsIdentity = mTransformationInfo == null
10097                    || mTransformationInfo.mMatrixIsIdentity;
10098            if (matrixIsIdentity) {
10099                if (mDisplayList != null) {
10100                    invalidateViewProperty(false, false);
10101                } else {
10102                    final ViewParent p = mParent;
10103                    if (p != null && mAttachInfo != null) {
10104                        final Rect r = mAttachInfo.mTmpInvalRect;
10105                        int minLeft;
10106                        int maxRight;
10107                        if (offset < 0) {
10108                            minLeft = mLeft + offset;
10109                            maxRight = mRight;
10110                        } else {
10111                            minLeft = mLeft;
10112                            maxRight = mRight + offset;
10113                        }
10114                        r.set(0, 0, maxRight - minLeft, mBottom - mTop);
10115                        p.invalidateChild(this, r);
10116                    }
10117                }
10118            } else {
10119                invalidateViewProperty(false, false);
10120            }
10121
10122            mLeft += offset;
10123            mRight += offset;
10124            if (mDisplayList != null) {
10125                mDisplayList.offsetLeftAndRight(offset);
10126                invalidateViewProperty(false, false);
10127            } else {
10128                if (!matrixIsIdentity) {
10129                    invalidateViewProperty(false, true);
10130                }
10131                invalidateParentIfNeeded();
10132            }
10133        }
10134    }
10135
10136    /**
10137     * Get the LayoutParams associated with this view. All views should have
10138     * layout parameters. These supply parameters to the <i>parent</i> of this
10139     * view specifying how it should be arranged. There are many subclasses of
10140     * ViewGroup.LayoutParams, and these correspond to the different subclasses
10141     * of ViewGroup that are responsible for arranging their children.
10142     *
10143     * This method may return null if this View is not attached to a parent
10144     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
10145     * was not invoked successfully. When a View is attached to a parent
10146     * ViewGroup, this method must not return null.
10147     *
10148     * @return The LayoutParams associated with this view, or null if no
10149     *         parameters have been set yet
10150     */
10151    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
10152    public ViewGroup.LayoutParams getLayoutParams() {
10153        return mLayoutParams;
10154    }
10155
10156    /**
10157     * Set the layout parameters associated with this view. These supply
10158     * parameters to the <i>parent</i> of this view specifying how it should be
10159     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
10160     * correspond to the different subclasses of ViewGroup that are responsible
10161     * for arranging their children.
10162     *
10163     * @param params The layout parameters for this view, cannot be null
10164     */
10165    public void setLayoutParams(ViewGroup.LayoutParams params) {
10166        if (params == null) {
10167            throw new NullPointerException("Layout parameters cannot be null");
10168        }
10169        mLayoutParams = params;
10170        resolveLayoutParams();
10171        if (mParent instanceof ViewGroup) {
10172            ((ViewGroup) mParent).onSetLayoutParams(this, params);
10173        }
10174        requestLayout();
10175    }
10176
10177    /**
10178     * Resolve the layout parameters depending on the resolved layout direction
10179     *
10180     * @hide
10181     */
10182    public void resolveLayoutParams() {
10183        if (mLayoutParams != null) {
10184            mLayoutParams.resolveLayoutDirection(getLayoutDirection());
10185        }
10186    }
10187
10188    /**
10189     * Set the scrolled position of your view. This will cause a call to
10190     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10191     * invalidated.
10192     * @param x the x position to scroll to
10193     * @param y the y position to scroll to
10194     */
10195    public void scrollTo(int x, int y) {
10196        if (mScrollX != x || mScrollY != y) {
10197            int oldX = mScrollX;
10198            int oldY = mScrollY;
10199            mScrollX = x;
10200            mScrollY = y;
10201            invalidateParentCaches();
10202            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
10203            if (!awakenScrollBars()) {
10204                postInvalidateOnAnimation();
10205            }
10206        }
10207    }
10208
10209    /**
10210     * Move the scrolled position of your view. This will cause a call to
10211     * {@link #onScrollChanged(int, int, int, int)} and the view will be
10212     * invalidated.
10213     * @param x the amount of pixels to scroll by horizontally
10214     * @param y the amount of pixels to scroll by vertically
10215     */
10216    public void scrollBy(int x, int y) {
10217        scrollTo(mScrollX + x, mScrollY + y);
10218    }
10219
10220    /**
10221     * <p>Trigger the scrollbars to draw. When invoked this method starts an
10222     * animation to fade the scrollbars out after a default delay. If a subclass
10223     * provides animated scrolling, the start delay should equal the duration
10224     * of the scrolling animation.</p>
10225     *
10226     * <p>The animation starts only if at least one of the scrollbars is
10227     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
10228     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10229     * this method returns true, and false otherwise. If the animation is
10230     * started, this method calls {@link #invalidate()}; in that case the
10231     * caller should not call {@link #invalidate()}.</p>
10232     *
10233     * <p>This method should be invoked every time a subclass directly updates
10234     * the scroll parameters.</p>
10235     *
10236     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
10237     * and {@link #scrollTo(int, int)}.</p>
10238     *
10239     * @return true if the animation is played, false otherwise
10240     *
10241     * @see #awakenScrollBars(int)
10242     * @see #scrollBy(int, int)
10243     * @see #scrollTo(int, int)
10244     * @see #isHorizontalScrollBarEnabled()
10245     * @see #isVerticalScrollBarEnabled()
10246     * @see #setHorizontalScrollBarEnabled(boolean)
10247     * @see #setVerticalScrollBarEnabled(boolean)
10248     */
10249    protected boolean awakenScrollBars() {
10250        return mScrollCache != null &&
10251                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
10252    }
10253
10254    /**
10255     * Trigger the scrollbars to draw.
10256     * This method differs from awakenScrollBars() only in its default duration.
10257     * initialAwakenScrollBars() will show the scroll bars for longer than
10258     * usual to give the user more of a chance to notice them.
10259     *
10260     * @return true if the animation is played, false otherwise.
10261     */
10262    private boolean initialAwakenScrollBars() {
10263        return mScrollCache != null &&
10264                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
10265    }
10266
10267    /**
10268     * <p>
10269     * Trigger the scrollbars to draw. When invoked this method starts an
10270     * animation to fade the scrollbars out after a fixed delay. If a subclass
10271     * provides animated scrolling, the start delay should equal the duration of
10272     * the scrolling animation.
10273     * </p>
10274     *
10275     * <p>
10276     * The animation starts only if at least one of the scrollbars is enabled,
10277     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10278     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10279     * this method returns true, and false otherwise. If the animation is
10280     * started, this method calls {@link #invalidate()}; in that case the caller
10281     * should not call {@link #invalidate()}.
10282     * </p>
10283     *
10284     * <p>
10285     * This method should be invoked everytime a subclass directly updates the
10286     * scroll parameters.
10287     * </p>
10288     *
10289     * @param startDelay the delay, in milliseconds, after which the animation
10290     *        should start; when the delay is 0, the animation starts
10291     *        immediately
10292     * @return true if the animation is played, false otherwise
10293     *
10294     * @see #scrollBy(int, int)
10295     * @see #scrollTo(int, int)
10296     * @see #isHorizontalScrollBarEnabled()
10297     * @see #isVerticalScrollBarEnabled()
10298     * @see #setHorizontalScrollBarEnabled(boolean)
10299     * @see #setVerticalScrollBarEnabled(boolean)
10300     */
10301    protected boolean awakenScrollBars(int startDelay) {
10302        return awakenScrollBars(startDelay, true);
10303    }
10304
10305    /**
10306     * <p>
10307     * Trigger the scrollbars to draw. When invoked this method starts an
10308     * animation to fade the scrollbars out after a fixed delay. If a subclass
10309     * provides animated scrolling, the start delay should equal the duration of
10310     * the scrolling animation.
10311     * </p>
10312     *
10313     * <p>
10314     * The animation starts only if at least one of the scrollbars is enabled,
10315     * as specified by {@link #isHorizontalScrollBarEnabled()} and
10316     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
10317     * this method returns true, and false otherwise. If the animation is
10318     * started, this method calls {@link #invalidate()} if the invalidate parameter
10319     * is set to true; in that case the caller
10320     * should not call {@link #invalidate()}.
10321     * </p>
10322     *
10323     * <p>
10324     * This method should be invoked everytime a subclass directly updates the
10325     * scroll parameters.
10326     * </p>
10327     *
10328     * @param startDelay the delay, in milliseconds, after which the animation
10329     *        should start; when the delay is 0, the animation starts
10330     *        immediately
10331     *
10332     * @param invalidate Wheter this method should call invalidate
10333     *
10334     * @return true if the animation is played, false otherwise
10335     *
10336     * @see #scrollBy(int, int)
10337     * @see #scrollTo(int, int)
10338     * @see #isHorizontalScrollBarEnabled()
10339     * @see #isVerticalScrollBarEnabled()
10340     * @see #setHorizontalScrollBarEnabled(boolean)
10341     * @see #setVerticalScrollBarEnabled(boolean)
10342     */
10343    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
10344        final ScrollabilityCache scrollCache = mScrollCache;
10345
10346        if (scrollCache == null || !scrollCache.fadeScrollBars) {
10347            return false;
10348        }
10349
10350        if (scrollCache.scrollBar == null) {
10351            scrollCache.scrollBar = new ScrollBarDrawable();
10352        }
10353
10354        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
10355
10356            if (invalidate) {
10357                // Invalidate to show the scrollbars
10358                postInvalidateOnAnimation();
10359            }
10360
10361            if (scrollCache.state == ScrollabilityCache.OFF) {
10362                // FIXME: this is copied from WindowManagerService.
10363                // We should get this value from the system when it
10364                // is possible to do so.
10365                final int KEY_REPEAT_FIRST_DELAY = 750;
10366                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
10367            }
10368
10369            // Tell mScrollCache when we should start fading. This may
10370            // extend the fade start time if one was already scheduled
10371            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
10372            scrollCache.fadeStartTime = fadeStartTime;
10373            scrollCache.state = ScrollabilityCache.ON;
10374
10375            // Schedule our fader to run, unscheduling any old ones first
10376            if (mAttachInfo != null) {
10377                mAttachInfo.mHandler.removeCallbacks(scrollCache);
10378                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
10379            }
10380
10381            return true;
10382        }
10383
10384        return false;
10385    }
10386
10387    /**
10388     * Do not invalidate views which are not visible and which are not running an animation. They
10389     * will not get drawn and they should not set dirty flags as if they will be drawn
10390     */
10391    private boolean skipInvalidate() {
10392        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
10393                (!(mParent instanceof ViewGroup) ||
10394                        !((ViewGroup) mParent).isViewTransitioning(this));
10395    }
10396    /**
10397     * Mark the area defined by dirty as needing to be drawn. If the view is
10398     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
10399     * in the future. This must be called from a UI thread. To call from a non-UI
10400     * thread, call {@link #postInvalidate()}.
10401     *
10402     * WARNING: This method is destructive to dirty.
10403     * @param dirty the rectangle representing the bounds of the dirty region
10404     */
10405    public void invalidate(Rect dirty) {
10406        if (skipInvalidate()) {
10407            return;
10408        }
10409        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10410                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10411                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10412            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10413            mPrivateFlags |= PFLAG_INVALIDATED;
10414            mPrivateFlags |= PFLAG_DIRTY;
10415            final ViewParent p = mParent;
10416            final AttachInfo ai = mAttachInfo;
10417            //noinspection PointlessBooleanExpression,ConstantConditions
10418            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10419                if (p != null && ai != null && ai.mHardwareAccelerated) {
10420                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10421                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10422                    p.invalidateChild(this, null);
10423                    return;
10424                }
10425            }
10426            if (p != null && ai != null) {
10427                final int scrollX = mScrollX;
10428                final int scrollY = mScrollY;
10429                final Rect r = ai.mTmpInvalRect;
10430                r.set(dirty.left - scrollX, dirty.top - scrollY,
10431                        dirty.right - scrollX, dirty.bottom - scrollY);
10432                mParent.invalidateChild(this, r);
10433            }
10434        }
10435    }
10436
10437    /**
10438     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
10439     * The coordinates of the dirty rect are relative to the view.
10440     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
10441     * will be called at some point in the future. This must be called from
10442     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
10443     * @param l the left position of the dirty region
10444     * @param t the top position of the dirty region
10445     * @param r the right position of the dirty region
10446     * @param b the bottom position of the dirty region
10447     */
10448    public void invalidate(int l, int t, int r, int b) {
10449        if (skipInvalidate()) {
10450            return;
10451        }
10452        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10453                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID ||
10454                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) {
10455            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10456            mPrivateFlags |= PFLAG_INVALIDATED;
10457            mPrivateFlags |= PFLAG_DIRTY;
10458            final ViewParent p = mParent;
10459            final AttachInfo ai = mAttachInfo;
10460            //noinspection PointlessBooleanExpression,ConstantConditions
10461            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10462                if (p != null && ai != null && ai.mHardwareAccelerated) {
10463                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10464                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10465                    p.invalidateChild(this, null);
10466                    return;
10467                }
10468            }
10469            if (p != null && ai != null && l < r && t < b) {
10470                final int scrollX = mScrollX;
10471                final int scrollY = mScrollY;
10472                final Rect tmpr = ai.mTmpInvalRect;
10473                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
10474                p.invalidateChild(this, tmpr);
10475            }
10476        }
10477    }
10478
10479    /**
10480     * Invalidate the whole view. If the view is visible,
10481     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
10482     * the future. This must be called from a UI thread. To call from a non-UI thread,
10483     * call {@link #postInvalidate()}.
10484     */
10485    public void invalidate() {
10486        invalidate(true);
10487    }
10488
10489    /**
10490     * This is where the invalidate() work actually happens. A full invalidate()
10491     * causes the drawing cache to be invalidated, but this function can be called with
10492     * invalidateCache set to false to skip that invalidation step for cases that do not
10493     * need it (for example, a component that remains at the same dimensions with the same
10494     * content).
10495     *
10496     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
10497     * well. This is usually true for a full invalidate, but may be set to false if the
10498     * View's contents or dimensions have not changed.
10499     */
10500    void invalidate(boolean invalidateCache) {
10501        if (skipInvalidate()) {
10502            return;
10503        }
10504        if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) ||
10505                (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) ||
10506                (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) {
10507            mLastIsOpaque = isOpaque();
10508            mPrivateFlags &= ~PFLAG_DRAWN;
10509            mPrivateFlags |= PFLAG_DIRTY;
10510            if (invalidateCache) {
10511                mPrivateFlags |= PFLAG_INVALIDATED;
10512                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
10513            }
10514            final AttachInfo ai = mAttachInfo;
10515            final ViewParent p = mParent;
10516            //noinspection PointlessBooleanExpression,ConstantConditions
10517            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
10518                if (p != null && ai != null && ai.mHardwareAccelerated) {
10519                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
10520                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
10521                    p.invalidateChild(this, null);
10522                    return;
10523                }
10524            }
10525
10526            if (p != null && ai != null) {
10527                final Rect r = ai.mTmpInvalRect;
10528                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10529                // Don't call invalidate -- we don't want to internally scroll
10530                // our own bounds
10531                p.invalidateChild(this, r);
10532            }
10533        }
10534    }
10535
10536    /**
10537     * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to
10538     * set any flags or handle all of the cases handled by the default invalidation methods.
10539     * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate
10540     * dirty rect. This method calls into fast invalidation methods in ViewGroup that
10541     * walk up the hierarchy, transforming the dirty rect as necessary.
10542     *
10543     * The method also handles normal invalidation logic if display list properties are not
10544     * being used in this view. The invalidateParent and forceRedraw flags are used by that
10545     * backup approach, to handle these cases used in the various property-setting methods.
10546     *
10547     * @param invalidateParent Force a call to invalidateParentCaches() if display list properties
10548     * are not being used in this view
10549     * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display
10550     * list properties are not being used in this view
10551     */
10552    void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) {
10553        if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) {
10554            if (invalidateParent) {
10555                invalidateParentCaches();
10556            }
10557            if (forceRedraw) {
10558                mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation
10559            }
10560            invalidate(false);
10561        } else {
10562            final AttachInfo ai = mAttachInfo;
10563            final ViewParent p = mParent;
10564            if (p != null && ai != null) {
10565                final Rect r = ai.mTmpInvalRect;
10566                r.set(0, 0, mRight - mLeft, mBottom - mTop);
10567                if (mParent instanceof ViewGroup) {
10568                    ((ViewGroup) mParent).invalidateChildFast(this, r);
10569                } else {
10570                    mParent.invalidateChild(this, r);
10571                }
10572            }
10573        }
10574    }
10575
10576    /**
10577     * Utility method to transform a given Rect by the current matrix of this view.
10578     */
10579    void transformRect(final Rect rect) {
10580        if (!getMatrix().isIdentity()) {
10581            RectF boundingRect = mAttachInfo.mTmpTransformRect;
10582            boundingRect.set(rect);
10583            getMatrix().mapRect(boundingRect);
10584            rect.set((int) (boundingRect.left - 0.5f),
10585                    (int) (boundingRect.top - 0.5f),
10586                    (int) (boundingRect.right + 0.5f),
10587                    (int) (boundingRect.bottom + 0.5f));
10588        }
10589    }
10590
10591    /**
10592     * Used to indicate that the parent of this view should clear its caches. This functionality
10593     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10594     * which is necessary when various parent-managed properties of the view change, such as
10595     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
10596     * clears the parent caches and does not causes an invalidate event.
10597     *
10598     * @hide
10599     */
10600    protected void invalidateParentCaches() {
10601        if (mParent instanceof View) {
10602            ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED;
10603        }
10604    }
10605
10606    /**
10607     * Used to indicate that the parent of this view should be invalidated. This functionality
10608     * is used to force the parent to rebuild its display list (when hardware-accelerated),
10609     * which is necessary when various parent-managed properties of the view change, such as
10610     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
10611     * an invalidation event to the parent.
10612     *
10613     * @hide
10614     */
10615    protected void invalidateParentIfNeeded() {
10616        if (isHardwareAccelerated() && mParent instanceof View) {
10617            ((View) mParent).invalidate(true);
10618        }
10619    }
10620
10621    /**
10622     * Indicates whether this View is opaque. An opaque View guarantees that it will
10623     * draw all the pixels overlapping its bounds using a fully opaque color.
10624     *
10625     * Subclasses of View should override this method whenever possible to indicate
10626     * whether an instance is opaque. Opaque Views are treated in a special way by
10627     * the View hierarchy, possibly allowing it to perform optimizations during
10628     * invalidate/draw passes.
10629     *
10630     * @return True if this View is guaranteed to be fully opaque, false otherwise.
10631     */
10632    @ViewDebug.ExportedProperty(category = "drawing")
10633    public boolean isOpaque() {
10634        return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK &&
10635                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1.0f) >= 1.0f);
10636    }
10637
10638    /**
10639     * @hide
10640     */
10641    protected void computeOpaqueFlags() {
10642        // Opaque if:
10643        //   - Has a background
10644        //   - Background is opaque
10645        //   - Doesn't have scrollbars or scrollbars are inside overlay
10646
10647        if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) {
10648            mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND;
10649        } else {
10650            mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND;
10651        }
10652
10653        final int flags = mViewFlags;
10654        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
10655                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
10656            mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS;
10657        } else {
10658            mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS;
10659        }
10660    }
10661
10662    /**
10663     * @hide
10664     */
10665    protected boolean hasOpaqueScrollbars() {
10666        return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS;
10667    }
10668
10669    /**
10670     * @return A handler associated with the thread running the View. This
10671     * handler can be used to pump events in the UI events queue.
10672     */
10673    public Handler getHandler() {
10674        if (mAttachInfo != null) {
10675            return mAttachInfo.mHandler;
10676        }
10677        return null;
10678    }
10679
10680    /**
10681     * Gets the view root associated with the View.
10682     * @return The view root, or null if none.
10683     * @hide
10684     */
10685    public ViewRootImpl getViewRootImpl() {
10686        if (mAttachInfo != null) {
10687            return mAttachInfo.mViewRootImpl;
10688        }
10689        return null;
10690    }
10691
10692    /**
10693     * <p>Causes the Runnable to be added to the message queue.
10694     * The runnable will be run on the user interface thread.</p>
10695     *
10696     * @param action The Runnable that will be executed.
10697     *
10698     * @return Returns true if the Runnable was successfully placed in to the
10699     *         message queue.  Returns false on failure, usually because the
10700     *         looper processing the message queue is exiting.
10701     *
10702     * @see #postDelayed
10703     * @see #removeCallbacks
10704     */
10705    public boolean post(Runnable action) {
10706        final AttachInfo attachInfo = mAttachInfo;
10707        if (attachInfo != null) {
10708            return attachInfo.mHandler.post(action);
10709        }
10710        // Assume that post will succeed later
10711        ViewRootImpl.getRunQueue().post(action);
10712        return true;
10713    }
10714
10715    /**
10716     * <p>Causes the Runnable to be added to the message queue, to be run
10717     * after the specified amount of time elapses.
10718     * The runnable will be run on the user interface thread.</p>
10719     *
10720     * @param action The Runnable that will be executed.
10721     * @param delayMillis The delay (in milliseconds) until the Runnable
10722     *        will be executed.
10723     *
10724     * @return true if the Runnable was successfully placed in to the
10725     *         message queue.  Returns false on failure, usually because the
10726     *         looper processing the message queue is exiting.  Note that a
10727     *         result of true does not mean the Runnable will be processed --
10728     *         if the looper is quit before the delivery time of the message
10729     *         occurs then the message will be dropped.
10730     *
10731     * @see #post
10732     * @see #removeCallbacks
10733     */
10734    public boolean postDelayed(Runnable action, long delayMillis) {
10735        final AttachInfo attachInfo = mAttachInfo;
10736        if (attachInfo != null) {
10737            return attachInfo.mHandler.postDelayed(action, delayMillis);
10738        }
10739        // Assume that post will succeed later
10740        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10741        return true;
10742    }
10743
10744    /**
10745     * <p>Causes the Runnable to execute on the next animation time step.
10746     * The runnable will be run on the user interface thread.</p>
10747     *
10748     * @param action The Runnable that will be executed.
10749     *
10750     * @see #postOnAnimationDelayed
10751     * @see #removeCallbacks
10752     */
10753    public void postOnAnimation(Runnable action) {
10754        final AttachInfo attachInfo = mAttachInfo;
10755        if (attachInfo != null) {
10756            attachInfo.mViewRootImpl.mChoreographer.postCallback(
10757                    Choreographer.CALLBACK_ANIMATION, action, null);
10758        } else {
10759            // Assume that post will succeed later
10760            ViewRootImpl.getRunQueue().post(action);
10761        }
10762    }
10763
10764    /**
10765     * <p>Causes the Runnable to execute on the next animation time step,
10766     * after the specified amount of time elapses.
10767     * The runnable will be run on the user interface thread.</p>
10768     *
10769     * @param action The Runnable that will be executed.
10770     * @param delayMillis The delay (in milliseconds) until the Runnable
10771     *        will be executed.
10772     *
10773     * @see #postOnAnimation
10774     * @see #removeCallbacks
10775     */
10776    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
10777        final AttachInfo attachInfo = mAttachInfo;
10778        if (attachInfo != null) {
10779            attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
10780                    Choreographer.CALLBACK_ANIMATION, action, null, delayMillis);
10781        } else {
10782            // Assume that post will succeed later
10783            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
10784        }
10785    }
10786
10787    /**
10788     * <p>Removes the specified Runnable from the message queue.</p>
10789     *
10790     * @param action The Runnable to remove from the message handling queue
10791     *
10792     * @return true if this view could ask the Handler to remove the Runnable,
10793     *         false otherwise. When the returned value is true, the Runnable
10794     *         may or may not have been actually removed from the message queue
10795     *         (for instance, if the Runnable was not in the queue already.)
10796     *
10797     * @see #post
10798     * @see #postDelayed
10799     * @see #postOnAnimation
10800     * @see #postOnAnimationDelayed
10801     */
10802    public boolean removeCallbacks(Runnable action) {
10803        if (action != null) {
10804            final AttachInfo attachInfo = mAttachInfo;
10805            if (attachInfo != null) {
10806                attachInfo.mHandler.removeCallbacks(action);
10807                attachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
10808                        Choreographer.CALLBACK_ANIMATION, action, null);
10809            } else {
10810                // Assume that post will succeed later
10811                ViewRootImpl.getRunQueue().removeCallbacks(action);
10812            }
10813        }
10814        return true;
10815    }
10816
10817    /**
10818     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
10819     * Use this to invalidate the View from a non-UI thread.</p>
10820     *
10821     * <p>This method can be invoked from outside of the UI thread
10822     * only when this View is attached to a window.</p>
10823     *
10824     * @see #invalidate()
10825     * @see #postInvalidateDelayed(long)
10826     */
10827    public void postInvalidate() {
10828        postInvalidateDelayed(0);
10829    }
10830
10831    /**
10832     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10833     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
10834     *
10835     * <p>This method can be invoked from outside of the UI thread
10836     * only when this View is attached to a window.</p>
10837     *
10838     * @param left The left coordinate of the rectangle to invalidate.
10839     * @param top The top coordinate of the rectangle to invalidate.
10840     * @param right The right coordinate of the rectangle to invalidate.
10841     * @param bottom The bottom coordinate of the rectangle to invalidate.
10842     *
10843     * @see #invalidate(int, int, int, int)
10844     * @see #invalidate(Rect)
10845     * @see #postInvalidateDelayed(long, int, int, int, int)
10846     */
10847    public void postInvalidate(int left, int top, int right, int bottom) {
10848        postInvalidateDelayed(0, left, top, right, bottom);
10849    }
10850
10851    /**
10852     * <p>Cause an invalidate to happen on a subsequent cycle through the event
10853     * loop. Waits for the specified amount of time.</p>
10854     *
10855     * <p>This method can be invoked from outside of the UI thread
10856     * only when this View is attached to a window.</p>
10857     *
10858     * @param delayMilliseconds the duration in milliseconds to delay the
10859     *         invalidation by
10860     *
10861     * @see #invalidate()
10862     * @see #postInvalidate()
10863     */
10864    public void postInvalidateDelayed(long delayMilliseconds) {
10865        // We try only with the AttachInfo because there's no point in invalidating
10866        // if we are not attached to our window
10867        final AttachInfo attachInfo = mAttachInfo;
10868        if (attachInfo != null) {
10869            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
10870        }
10871    }
10872
10873    /**
10874     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
10875     * through the event loop. Waits for the specified amount of time.</p>
10876     *
10877     * <p>This method can be invoked from outside of the UI thread
10878     * only when this View is attached to a window.</p>
10879     *
10880     * @param delayMilliseconds the duration in milliseconds to delay the
10881     *         invalidation by
10882     * @param left The left coordinate of the rectangle to invalidate.
10883     * @param top The top coordinate of the rectangle to invalidate.
10884     * @param right The right coordinate of the rectangle to invalidate.
10885     * @param bottom The bottom coordinate of the rectangle to invalidate.
10886     *
10887     * @see #invalidate(int, int, int, int)
10888     * @see #invalidate(Rect)
10889     * @see #postInvalidate(int, int, int, int)
10890     */
10891    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
10892            int right, int bottom) {
10893
10894        // We try only with the AttachInfo because there's no point in invalidating
10895        // if we are not attached to our window
10896        final AttachInfo attachInfo = mAttachInfo;
10897        if (attachInfo != null) {
10898            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10899            info.target = this;
10900            info.left = left;
10901            info.top = top;
10902            info.right = right;
10903            info.bottom = bottom;
10904
10905            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
10906        }
10907    }
10908
10909    /**
10910     * <p>Cause an invalidate to happen on the next animation time step, typically the
10911     * next display frame.</p>
10912     *
10913     * <p>This method can be invoked from outside of the UI thread
10914     * only when this View is attached to a window.</p>
10915     *
10916     * @see #invalidate()
10917     */
10918    public void postInvalidateOnAnimation() {
10919        // We try only with the AttachInfo because there's no point in invalidating
10920        // if we are not attached to our window
10921        final AttachInfo attachInfo = mAttachInfo;
10922        if (attachInfo != null) {
10923            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
10924        }
10925    }
10926
10927    /**
10928     * <p>Cause an invalidate of the specified area to happen on the next animation
10929     * time step, typically the next display frame.</p>
10930     *
10931     * <p>This method can be invoked from outside of the UI thread
10932     * only when this View is attached to a window.</p>
10933     *
10934     * @param left The left coordinate of the rectangle to invalidate.
10935     * @param top The top coordinate of the rectangle to invalidate.
10936     * @param right The right coordinate of the rectangle to invalidate.
10937     * @param bottom The bottom coordinate of the rectangle to invalidate.
10938     *
10939     * @see #invalidate(int, int, int, int)
10940     * @see #invalidate(Rect)
10941     */
10942    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
10943        // We try only with the AttachInfo because there's no point in invalidating
10944        // if we are not attached to our window
10945        final AttachInfo attachInfo = mAttachInfo;
10946        if (attachInfo != null) {
10947            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain();
10948            info.target = this;
10949            info.left = left;
10950            info.top = top;
10951            info.right = right;
10952            info.bottom = bottom;
10953
10954            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
10955        }
10956    }
10957
10958    /**
10959     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
10960     * This event is sent at most once every
10961     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
10962     */
10963    private void postSendViewScrolledAccessibilityEventCallback() {
10964        if (mSendViewScrolledAccessibilityEvent == null) {
10965            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
10966        }
10967        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
10968            mSendViewScrolledAccessibilityEvent.mIsPending = true;
10969            postDelayed(mSendViewScrolledAccessibilityEvent,
10970                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
10971        }
10972    }
10973
10974    /**
10975     * Called by a parent to request that a child update its values for mScrollX
10976     * and mScrollY if necessary. This will typically be done if the child is
10977     * animating a scroll using a {@link android.widget.Scroller Scroller}
10978     * object.
10979     */
10980    public void computeScroll() {
10981    }
10982
10983    /**
10984     * <p>Indicate whether the horizontal edges are faded when the view is
10985     * scrolled horizontally.</p>
10986     *
10987     * @return true if the horizontal edges should are faded on scroll, false
10988     *         otherwise
10989     *
10990     * @see #setHorizontalFadingEdgeEnabled(boolean)
10991     *
10992     * @attr ref android.R.styleable#View_requiresFadingEdge
10993     */
10994    public boolean isHorizontalFadingEdgeEnabled() {
10995        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
10996    }
10997
10998    /**
10999     * <p>Define whether the horizontal edges should be faded when this view
11000     * is scrolled horizontally.</p>
11001     *
11002     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
11003     *                                    be faded when the view is scrolled
11004     *                                    horizontally
11005     *
11006     * @see #isHorizontalFadingEdgeEnabled()
11007     *
11008     * @attr ref android.R.styleable#View_requiresFadingEdge
11009     */
11010    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
11011        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
11012            if (horizontalFadingEdgeEnabled) {
11013                initScrollCache();
11014            }
11015
11016            mViewFlags ^= FADING_EDGE_HORIZONTAL;
11017        }
11018    }
11019
11020    /**
11021     * <p>Indicate whether the vertical edges are faded when the view is
11022     * scrolled horizontally.</p>
11023     *
11024     * @return true if the vertical edges should are faded on scroll, false
11025     *         otherwise
11026     *
11027     * @see #setVerticalFadingEdgeEnabled(boolean)
11028     *
11029     * @attr ref android.R.styleable#View_requiresFadingEdge
11030     */
11031    public boolean isVerticalFadingEdgeEnabled() {
11032        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
11033    }
11034
11035    /**
11036     * <p>Define whether the vertical edges should be faded when this view
11037     * is scrolled vertically.</p>
11038     *
11039     * @param verticalFadingEdgeEnabled true if the vertical edges should
11040     *                                  be faded when the view is scrolled
11041     *                                  vertically
11042     *
11043     * @see #isVerticalFadingEdgeEnabled()
11044     *
11045     * @attr ref android.R.styleable#View_requiresFadingEdge
11046     */
11047    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
11048        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
11049            if (verticalFadingEdgeEnabled) {
11050                initScrollCache();
11051            }
11052
11053            mViewFlags ^= FADING_EDGE_VERTICAL;
11054        }
11055    }
11056
11057    /**
11058     * Returns the strength, or intensity, of the top faded edge. The strength is
11059     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11060     * returns 0.0 or 1.0 but no value in between.
11061     *
11062     * Subclasses should override this method to provide a smoother fade transition
11063     * when scrolling occurs.
11064     *
11065     * @return the intensity of the top fade as a float between 0.0f and 1.0f
11066     */
11067    protected float getTopFadingEdgeStrength() {
11068        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
11069    }
11070
11071    /**
11072     * Returns the strength, or intensity, of the bottom faded edge. The strength is
11073     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11074     * returns 0.0 or 1.0 but no value in between.
11075     *
11076     * Subclasses should override this method to provide a smoother fade transition
11077     * when scrolling occurs.
11078     *
11079     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
11080     */
11081    protected float getBottomFadingEdgeStrength() {
11082        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
11083                computeVerticalScrollRange() ? 1.0f : 0.0f;
11084    }
11085
11086    /**
11087     * Returns the strength, or intensity, of the left faded edge. The strength is
11088     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11089     * returns 0.0 or 1.0 but no value in between.
11090     *
11091     * Subclasses should override this method to provide a smoother fade transition
11092     * when scrolling occurs.
11093     *
11094     * @return the intensity of the left fade as a float between 0.0f and 1.0f
11095     */
11096    protected float getLeftFadingEdgeStrength() {
11097        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
11098    }
11099
11100    /**
11101     * Returns the strength, or intensity, of the right faded edge. The strength is
11102     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
11103     * returns 0.0 or 1.0 but no value in between.
11104     *
11105     * Subclasses should override this method to provide a smoother fade transition
11106     * when scrolling occurs.
11107     *
11108     * @return the intensity of the right fade as a float between 0.0f and 1.0f
11109     */
11110    protected float getRightFadingEdgeStrength() {
11111        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
11112                computeHorizontalScrollRange() ? 1.0f : 0.0f;
11113    }
11114
11115    /**
11116     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
11117     * scrollbar is not drawn by default.</p>
11118     *
11119     * @return true if the horizontal scrollbar should be painted, false
11120     *         otherwise
11121     *
11122     * @see #setHorizontalScrollBarEnabled(boolean)
11123     */
11124    public boolean isHorizontalScrollBarEnabled() {
11125        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11126    }
11127
11128    /**
11129     * <p>Define whether the horizontal scrollbar should be drawn or not. The
11130     * scrollbar is not drawn by default.</p>
11131     *
11132     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
11133     *                                   be painted
11134     *
11135     * @see #isHorizontalScrollBarEnabled()
11136     */
11137    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
11138        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
11139            mViewFlags ^= SCROLLBARS_HORIZONTAL;
11140            computeOpaqueFlags();
11141            resolvePadding();
11142        }
11143    }
11144
11145    /**
11146     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
11147     * scrollbar is not drawn by default.</p>
11148     *
11149     * @return true if the vertical scrollbar should be painted, false
11150     *         otherwise
11151     *
11152     * @see #setVerticalScrollBarEnabled(boolean)
11153     */
11154    public boolean isVerticalScrollBarEnabled() {
11155        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
11156    }
11157
11158    /**
11159     * <p>Define whether the vertical scrollbar should be drawn or not. The
11160     * scrollbar is not drawn by default.</p>
11161     *
11162     * @param verticalScrollBarEnabled true if the vertical scrollbar should
11163     *                                 be painted
11164     *
11165     * @see #isVerticalScrollBarEnabled()
11166     */
11167    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
11168        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
11169            mViewFlags ^= SCROLLBARS_VERTICAL;
11170            computeOpaqueFlags();
11171            resolvePadding();
11172        }
11173    }
11174
11175    /**
11176     * @hide
11177     */
11178    protected void recomputePadding() {
11179        internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
11180    }
11181
11182    /**
11183     * Define whether scrollbars will fade when the view is not scrolling.
11184     *
11185     * @param fadeScrollbars wheter to enable fading
11186     *
11187     * @attr ref android.R.styleable#View_fadeScrollbars
11188     */
11189    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
11190        initScrollCache();
11191        final ScrollabilityCache scrollabilityCache = mScrollCache;
11192        scrollabilityCache.fadeScrollBars = fadeScrollbars;
11193        if (fadeScrollbars) {
11194            scrollabilityCache.state = ScrollabilityCache.OFF;
11195        } else {
11196            scrollabilityCache.state = ScrollabilityCache.ON;
11197        }
11198    }
11199
11200    /**
11201     *
11202     * Returns true if scrollbars will fade when this view is not scrolling
11203     *
11204     * @return true if scrollbar fading is enabled
11205     *
11206     * @attr ref android.R.styleable#View_fadeScrollbars
11207     */
11208    public boolean isScrollbarFadingEnabled() {
11209        return mScrollCache != null && mScrollCache.fadeScrollBars;
11210    }
11211
11212    /**
11213     *
11214     * Returns the delay before scrollbars fade.
11215     *
11216     * @return the delay before scrollbars fade
11217     *
11218     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11219     */
11220    public int getScrollBarDefaultDelayBeforeFade() {
11221        return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() :
11222                mScrollCache.scrollBarDefaultDelayBeforeFade;
11223    }
11224
11225    /**
11226     * Define the delay before scrollbars fade.
11227     *
11228     * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade
11229     *
11230     * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
11231     */
11232    public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) {
11233        getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade;
11234    }
11235
11236    /**
11237     *
11238     * Returns the scrollbar fade duration.
11239     *
11240     * @return the scrollbar fade duration
11241     *
11242     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11243     */
11244    public int getScrollBarFadeDuration() {
11245        return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() :
11246                mScrollCache.scrollBarFadeDuration;
11247    }
11248
11249    /**
11250     * Define the scrollbar fade duration.
11251     *
11252     * @param scrollBarFadeDuration - the scrollbar fade duration
11253     *
11254     * @attr ref android.R.styleable#View_scrollbarFadeDuration
11255     */
11256    public void setScrollBarFadeDuration(int scrollBarFadeDuration) {
11257        getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration;
11258    }
11259
11260    /**
11261     *
11262     * Returns the scrollbar size.
11263     *
11264     * @return the scrollbar size
11265     *
11266     * @attr ref android.R.styleable#View_scrollbarSize
11267     */
11268    public int getScrollBarSize() {
11269        return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() :
11270                mScrollCache.scrollBarSize;
11271    }
11272
11273    /**
11274     * Define the scrollbar size.
11275     *
11276     * @param scrollBarSize - the scrollbar size
11277     *
11278     * @attr ref android.R.styleable#View_scrollbarSize
11279     */
11280    public void setScrollBarSize(int scrollBarSize) {
11281        getScrollCache().scrollBarSize = scrollBarSize;
11282    }
11283
11284    /**
11285     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
11286     * inset. When inset, they add to the padding of the view. And the scrollbars
11287     * can be drawn inside the padding area or on the edge of the view. For example,
11288     * if a view has a background drawable and you want to draw the scrollbars
11289     * inside the padding specified by the drawable, you can use
11290     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
11291     * appear at the edge of the view, ignoring the padding, then you can use
11292     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
11293     * @param style the style of the scrollbars. Should be one of
11294     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
11295     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
11296     * @see #SCROLLBARS_INSIDE_OVERLAY
11297     * @see #SCROLLBARS_INSIDE_INSET
11298     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11299     * @see #SCROLLBARS_OUTSIDE_INSET
11300     *
11301     * @attr ref android.R.styleable#View_scrollbarStyle
11302     */
11303    public void setScrollBarStyle(int style) {
11304        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
11305            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
11306            computeOpaqueFlags();
11307            resolvePadding();
11308        }
11309    }
11310
11311    /**
11312     * <p>Returns the current scrollbar style.</p>
11313     * @return the current scrollbar style
11314     * @see #SCROLLBARS_INSIDE_OVERLAY
11315     * @see #SCROLLBARS_INSIDE_INSET
11316     * @see #SCROLLBARS_OUTSIDE_OVERLAY
11317     * @see #SCROLLBARS_OUTSIDE_INSET
11318     *
11319     * @attr ref android.R.styleable#View_scrollbarStyle
11320     */
11321    @ViewDebug.ExportedProperty(mapping = {
11322            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
11323            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
11324            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
11325            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
11326    })
11327    public int getScrollBarStyle() {
11328        return mViewFlags & SCROLLBARS_STYLE_MASK;
11329    }
11330
11331    /**
11332     * <p>Compute the horizontal range that the horizontal scrollbar
11333     * represents.</p>
11334     *
11335     * <p>The range is expressed in arbitrary units that must be the same as the
11336     * units used by {@link #computeHorizontalScrollExtent()} and
11337     * {@link #computeHorizontalScrollOffset()}.</p>
11338     *
11339     * <p>The default range is the drawing width of this view.</p>
11340     *
11341     * @return the total horizontal range represented by the horizontal
11342     *         scrollbar
11343     *
11344     * @see #computeHorizontalScrollExtent()
11345     * @see #computeHorizontalScrollOffset()
11346     * @see android.widget.ScrollBarDrawable
11347     */
11348    protected int computeHorizontalScrollRange() {
11349        return getWidth();
11350    }
11351
11352    /**
11353     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
11354     * within the horizontal range. This value is used to compute the position
11355     * of the thumb within the scrollbar's track.</p>
11356     *
11357     * <p>The range is expressed in arbitrary units that must be the same as the
11358     * units used by {@link #computeHorizontalScrollRange()} and
11359     * {@link #computeHorizontalScrollExtent()}.</p>
11360     *
11361     * <p>The default offset is the scroll offset of this view.</p>
11362     *
11363     * @return the horizontal offset of the scrollbar's thumb
11364     *
11365     * @see #computeHorizontalScrollRange()
11366     * @see #computeHorizontalScrollExtent()
11367     * @see android.widget.ScrollBarDrawable
11368     */
11369    protected int computeHorizontalScrollOffset() {
11370        return mScrollX;
11371    }
11372
11373    /**
11374     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
11375     * within the horizontal range. This value is used to compute the length
11376     * of the thumb within the scrollbar's track.</p>
11377     *
11378     * <p>The range is expressed in arbitrary units that must be the same as the
11379     * units used by {@link #computeHorizontalScrollRange()} and
11380     * {@link #computeHorizontalScrollOffset()}.</p>
11381     *
11382     * <p>The default extent is the drawing width of this view.</p>
11383     *
11384     * @return the horizontal extent of the scrollbar's thumb
11385     *
11386     * @see #computeHorizontalScrollRange()
11387     * @see #computeHorizontalScrollOffset()
11388     * @see android.widget.ScrollBarDrawable
11389     */
11390    protected int computeHorizontalScrollExtent() {
11391        return getWidth();
11392    }
11393
11394    /**
11395     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
11396     *
11397     * <p>The range is expressed in arbitrary units that must be the same as the
11398     * units used by {@link #computeVerticalScrollExtent()} and
11399     * {@link #computeVerticalScrollOffset()}.</p>
11400     *
11401     * @return the total vertical range represented by the vertical scrollbar
11402     *
11403     * <p>The default range is the drawing height of this view.</p>
11404     *
11405     * @see #computeVerticalScrollExtent()
11406     * @see #computeVerticalScrollOffset()
11407     * @see android.widget.ScrollBarDrawable
11408     */
11409    protected int computeVerticalScrollRange() {
11410        return getHeight();
11411    }
11412
11413    /**
11414     * <p>Compute the vertical offset of the vertical scrollbar's thumb
11415     * within the horizontal range. This value is used to compute the position
11416     * of the thumb within the scrollbar's track.</p>
11417     *
11418     * <p>The range is expressed in arbitrary units that must be the same as the
11419     * units used by {@link #computeVerticalScrollRange()} and
11420     * {@link #computeVerticalScrollExtent()}.</p>
11421     *
11422     * <p>The default offset is the scroll offset of this view.</p>
11423     *
11424     * @return the vertical offset of the scrollbar's thumb
11425     *
11426     * @see #computeVerticalScrollRange()
11427     * @see #computeVerticalScrollExtent()
11428     * @see android.widget.ScrollBarDrawable
11429     */
11430    protected int computeVerticalScrollOffset() {
11431        return mScrollY;
11432    }
11433
11434    /**
11435     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
11436     * within the vertical range. This value is used to compute the length
11437     * of the thumb within the scrollbar's track.</p>
11438     *
11439     * <p>The range is expressed in arbitrary units that must be the same as the
11440     * units used by {@link #computeVerticalScrollRange()} and
11441     * {@link #computeVerticalScrollOffset()}.</p>
11442     *
11443     * <p>The default extent is the drawing height of this view.</p>
11444     *
11445     * @return the vertical extent of the scrollbar's thumb
11446     *
11447     * @see #computeVerticalScrollRange()
11448     * @see #computeVerticalScrollOffset()
11449     * @see android.widget.ScrollBarDrawable
11450     */
11451    protected int computeVerticalScrollExtent() {
11452        return getHeight();
11453    }
11454
11455    /**
11456     * Check if this view can be scrolled horizontally in a certain direction.
11457     *
11458     * @param direction Negative to check scrolling left, positive to check scrolling right.
11459     * @return true if this view can be scrolled in the specified direction, false otherwise.
11460     */
11461    public boolean canScrollHorizontally(int direction) {
11462        final int offset = computeHorizontalScrollOffset();
11463        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
11464        if (range == 0) return false;
11465        if (direction < 0) {
11466            return offset > 0;
11467        } else {
11468            return offset < range - 1;
11469        }
11470    }
11471
11472    /**
11473     * Check if this view can be scrolled vertically in a certain direction.
11474     *
11475     * @param direction Negative to check scrolling up, positive to check scrolling down.
11476     * @return true if this view can be scrolled in the specified direction, false otherwise.
11477     */
11478    public boolean canScrollVertically(int direction) {
11479        final int offset = computeVerticalScrollOffset();
11480        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
11481        if (range == 0) return false;
11482        if (direction < 0) {
11483            return offset > 0;
11484        } else {
11485            return offset < range - 1;
11486        }
11487    }
11488
11489    /**
11490     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
11491     * scrollbars are painted only if they have been awakened first.</p>
11492     *
11493     * @param canvas the canvas on which to draw the scrollbars
11494     *
11495     * @see #awakenScrollBars(int)
11496     */
11497    protected final void onDrawScrollBars(Canvas canvas) {
11498        // scrollbars are drawn only when the animation is running
11499        final ScrollabilityCache cache = mScrollCache;
11500        if (cache != null) {
11501
11502            int state = cache.state;
11503
11504            if (state == ScrollabilityCache.OFF) {
11505                return;
11506            }
11507
11508            boolean invalidate = false;
11509
11510            if (state == ScrollabilityCache.FADING) {
11511                // We're fading -- get our fade interpolation
11512                if (cache.interpolatorValues == null) {
11513                    cache.interpolatorValues = new float[1];
11514                }
11515
11516                float[] values = cache.interpolatorValues;
11517
11518                // Stops the animation if we're done
11519                if (cache.scrollBarInterpolator.timeToValues(values) ==
11520                        Interpolator.Result.FREEZE_END) {
11521                    cache.state = ScrollabilityCache.OFF;
11522                } else {
11523                    cache.scrollBar.setAlpha(Math.round(values[0]));
11524                }
11525
11526                // This will make the scroll bars inval themselves after
11527                // drawing. We only want this when we're fading so that
11528                // we prevent excessive redraws
11529                invalidate = true;
11530            } else {
11531                // We're just on -- but we may have been fading before so
11532                // reset alpha
11533                cache.scrollBar.setAlpha(255);
11534            }
11535
11536
11537            final int viewFlags = mViewFlags;
11538
11539            final boolean drawHorizontalScrollBar =
11540                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
11541            final boolean drawVerticalScrollBar =
11542                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
11543                && !isVerticalScrollBarHidden();
11544
11545            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
11546                final int width = mRight - mLeft;
11547                final int height = mBottom - mTop;
11548
11549                final ScrollBarDrawable scrollBar = cache.scrollBar;
11550
11551                final int scrollX = mScrollX;
11552                final int scrollY = mScrollY;
11553                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
11554
11555                int left, top, right, bottom;
11556
11557                if (drawHorizontalScrollBar) {
11558                    int size = scrollBar.getSize(false);
11559                    if (size <= 0) {
11560                        size = cache.scrollBarSize;
11561                    }
11562
11563                    scrollBar.setParameters(computeHorizontalScrollRange(),
11564                                            computeHorizontalScrollOffset(),
11565                                            computeHorizontalScrollExtent(), false);
11566                    final int verticalScrollBarGap = drawVerticalScrollBar ?
11567                            getVerticalScrollbarWidth() : 0;
11568                    top = scrollY + height - size - (mUserPaddingBottom & inside);
11569                    left = scrollX + (mPaddingLeft & inside);
11570                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
11571                    bottom = top + size;
11572                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
11573                    if (invalidate) {
11574                        invalidate(left, top, right, bottom);
11575                    }
11576                }
11577
11578                if (drawVerticalScrollBar) {
11579                    int size = scrollBar.getSize(true);
11580                    if (size <= 0) {
11581                        size = cache.scrollBarSize;
11582                    }
11583
11584                    scrollBar.setParameters(computeVerticalScrollRange(),
11585                                            computeVerticalScrollOffset(),
11586                                            computeVerticalScrollExtent(), true);
11587                    int verticalScrollbarPosition = mVerticalScrollbarPosition;
11588                    if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) {
11589                        verticalScrollbarPosition = isLayoutRtl() ?
11590                                SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT;
11591                    }
11592                    switch (verticalScrollbarPosition) {
11593                        default:
11594                        case SCROLLBAR_POSITION_RIGHT:
11595                            left = scrollX + width - size - (mUserPaddingRight & inside);
11596                            break;
11597                        case SCROLLBAR_POSITION_LEFT:
11598                            left = scrollX + (mUserPaddingLeft & inside);
11599                            break;
11600                    }
11601                    top = scrollY + (mPaddingTop & inside);
11602                    right = left + size;
11603                    bottom = scrollY + height - (mUserPaddingBottom & inside);
11604                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
11605                    if (invalidate) {
11606                        invalidate(left, top, right, bottom);
11607                    }
11608                }
11609            }
11610        }
11611    }
11612
11613    /**
11614     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
11615     * FastScroller is visible.
11616     * @return whether to temporarily hide the vertical scrollbar
11617     * @hide
11618     */
11619    protected boolean isVerticalScrollBarHidden() {
11620        return false;
11621    }
11622
11623    /**
11624     * <p>Draw the horizontal scrollbar if
11625     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
11626     *
11627     * @param canvas the canvas on which to draw the scrollbar
11628     * @param scrollBar the scrollbar's drawable
11629     *
11630     * @see #isHorizontalScrollBarEnabled()
11631     * @see #computeHorizontalScrollRange()
11632     * @see #computeHorizontalScrollExtent()
11633     * @see #computeHorizontalScrollOffset()
11634     * @see android.widget.ScrollBarDrawable
11635     * @hide
11636     */
11637    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
11638            int l, int t, int r, int b) {
11639        scrollBar.setBounds(l, t, r, b);
11640        scrollBar.draw(canvas);
11641    }
11642
11643    /**
11644     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
11645     * returns true.</p>
11646     *
11647     * @param canvas the canvas on which to draw the scrollbar
11648     * @param scrollBar the scrollbar's drawable
11649     *
11650     * @see #isVerticalScrollBarEnabled()
11651     * @see #computeVerticalScrollRange()
11652     * @see #computeVerticalScrollExtent()
11653     * @see #computeVerticalScrollOffset()
11654     * @see android.widget.ScrollBarDrawable
11655     * @hide
11656     */
11657    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
11658            int l, int t, int r, int b) {
11659        scrollBar.setBounds(l, t, r, b);
11660        scrollBar.draw(canvas);
11661    }
11662
11663    /**
11664     * Implement this to do your drawing.
11665     *
11666     * @param canvas the canvas on which the background will be drawn
11667     */
11668    protected void onDraw(Canvas canvas) {
11669    }
11670
11671    /*
11672     * Caller is responsible for calling requestLayout if necessary.
11673     * (This allows addViewInLayout to not request a new layout.)
11674     */
11675    void assignParent(ViewParent parent) {
11676        if (mParent == null) {
11677            mParent = parent;
11678        } else if (parent == null) {
11679            mParent = null;
11680        } else {
11681            throw new RuntimeException("view " + this + " being added, but"
11682                    + " it already has a parent");
11683        }
11684    }
11685
11686    /**
11687     * This is called when the view is attached to a window.  At this point it
11688     * has a Surface and will start drawing.  Note that this function is
11689     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
11690     * however it may be called any time before the first onDraw -- including
11691     * before or after {@link #onMeasure(int, int)}.
11692     *
11693     * @see #onDetachedFromWindow()
11694     */
11695    protected void onAttachedToWindow() {
11696        if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) {
11697            mParent.requestTransparentRegion(this);
11698        }
11699
11700        if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
11701            initialAwakenScrollBars();
11702            mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH;
11703        }
11704
11705        jumpDrawablesToCurrentState();
11706
11707        clearAccessibilityFocus();
11708        if (isFocused()) {
11709            InputMethodManager imm = InputMethodManager.peekInstance();
11710            imm.focusIn(this);
11711        }
11712
11713        if (mDisplayList != null) {
11714            mDisplayList.clearDirty();
11715        }
11716    }
11717
11718    /**
11719     * Resolve all RTL related properties.
11720     *
11721     * @hide
11722     */
11723    public void resolveRtlPropertiesIfNeeded() {
11724        if (!needRtlPropertiesResolution()) return;
11725
11726        // Order is important here: LayoutDirection MUST be resolved first
11727        if (!isLayoutDirectionResolved()) {
11728            resolveLayoutDirection();
11729            resolveLayoutParams();
11730        }
11731        // ... then we can resolve the others properties depending on the resolved LayoutDirection.
11732        if (!isTextDirectionResolved()) {
11733            resolveTextDirection();
11734        }
11735        if (!isTextAlignmentResolved()) {
11736            resolveTextAlignment();
11737        }
11738        if (!isPaddingResolved()) {
11739            resolvePadding();
11740        }
11741        if (!isDrawablesResolved()) {
11742            resolveDrawables();
11743        }
11744        onRtlPropertiesChanged(getLayoutDirection());
11745    }
11746
11747    /**
11748     * Reset resolution of all RTL related properties.
11749     *
11750     * @hide
11751     */
11752    public void resetRtlProperties() {
11753        resetResolvedLayoutDirection();
11754        resetResolvedTextDirection();
11755        resetResolvedTextAlignment();
11756        resetResolvedPadding();
11757        resetResolvedDrawables();
11758    }
11759
11760    /**
11761     * @see #onScreenStateChanged(int)
11762     */
11763    void dispatchScreenStateChanged(int screenState) {
11764        onScreenStateChanged(screenState);
11765    }
11766
11767    /**
11768     * This method is called whenever the state of the screen this view is
11769     * attached to changes. A state change will usually occurs when the screen
11770     * turns on or off (whether it happens automatically or the user does it
11771     * manually.)
11772     *
11773     * @param screenState The new state of the screen. Can be either
11774     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
11775     */
11776    public void onScreenStateChanged(int screenState) {
11777    }
11778
11779    /**
11780     * Return true if the application tag in the AndroidManifest has set "supportRtl" to true
11781     */
11782    private boolean hasRtlSupport() {
11783        return mContext.getApplicationInfo().hasRtlSupport();
11784    }
11785
11786    /**
11787     * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
11788     * RTL not supported)
11789     */
11790    private boolean isRtlCompatibilityMode() {
11791        final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
11792        return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport();
11793    }
11794
11795    /**
11796     * @return true if RTL properties need resolution.
11797     */
11798    private boolean needRtlPropertiesResolution() {
11799        return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED;
11800    }
11801
11802    /**
11803     * Called when any RTL property (layout direction or text direction or text alignment) has
11804     * been changed.
11805     *
11806     * Subclasses need to override this method to take care of cached information that depends on the
11807     * resolved layout direction, or to inform child views that inherit their layout direction.
11808     *
11809     * The default implementation does nothing.
11810     *
11811     * @param layoutDirection the direction of the layout
11812     *
11813     * @see #LAYOUT_DIRECTION_LTR
11814     * @see #LAYOUT_DIRECTION_RTL
11815     */
11816    public void onRtlPropertiesChanged(int layoutDirection) {
11817    }
11818
11819    /**
11820     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
11821     * that the parent directionality can and will be resolved before its children.
11822     *
11823     * @return true if resolution has been done, false otherwise.
11824     *
11825     * @hide
11826     */
11827    public boolean resolveLayoutDirection() {
11828        // Clear any previous layout direction resolution
11829        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11830
11831        if (hasRtlSupport()) {
11832            // Set resolved depending on layout direction
11833            switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >>
11834                    PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) {
11835                case LAYOUT_DIRECTION_INHERIT:
11836                    // We cannot resolve yet. LTR is by default and let the resolution happen again
11837                    // later to get the correct resolved value
11838                    if (!canResolveLayoutDirection()) return false;
11839
11840                    // Parent has not yet resolved, LTR is still the default
11841                    if (!mParent.isLayoutDirectionResolved()) return false;
11842
11843                    if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11844                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11845                    }
11846                    break;
11847                case LAYOUT_DIRECTION_RTL:
11848                    mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11849                    break;
11850                case LAYOUT_DIRECTION_LOCALE:
11851                    if((LAYOUT_DIRECTION_RTL ==
11852                            TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) {
11853                        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL;
11854                    }
11855                    break;
11856                default:
11857                    // Nothing to do, LTR by default
11858            }
11859        }
11860
11861        // Set to resolved
11862        mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11863        return true;
11864    }
11865
11866    /**
11867     * Check if layout direction resolution can be done.
11868     *
11869     * @return true if layout direction resolution can be done otherwise return false.
11870     *
11871     * @hide
11872     */
11873    public boolean canResolveLayoutDirection() {
11874        switch (getRawLayoutDirection()) {
11875            case LAYOUT_DIRECTION_INHERIT:
11876                return (mParent != null) && mParent.canResolveLayoutDirection();
11877            default:
11878                return true;
11879        }
11880    }
11881
11882    /**
11883     * Reset the resolved layout direction. Layout direction will be resolved during a call to
11884     * {@link #onMeasure(int, int)}.
11885     *
11886     * @hide
11887     */
11888    public void resetResolvedLayoutDirection() {
11889        // Reset the current resolved bits
11890        mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK;
11891    }
11892
11893    /**
11894     * @return true if the layout direction is inherited.
11895     *
11896     * @hide
11897     */
11898    public boolean isLayoutDirectionInherited() {
11899        return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT);
11900    }
11901
11902    /**
11903     * @return true if layout direction has been resolved.
11904     * @hide
11905     */
11906    public boolean isLayoutDirectionResolved() {
11907        return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED;
11908    }
11909
11910    /**
11911     * Return if padding has been resolved
11912     *
11913     * @hide
11914     */
11915    boolean isPaddingResolved() {
11916        return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED;
11917    }
11918
11919    /**
11920     * Resolve padding depending on layout direction.
11921     *
11922     * @hide
11923     */
11924    public void resolvePadding() {
11925        if (!isRtlCompatibilityMode()) {
11926            // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account.
11927            // If start / end padding are defined, they will be resolved (hence overriding) to
11928            // left / right or right / left depending on the resolved layout direction.
11929            // If start / end padding are not defined, use the left / right ones.
11930            int resolvedLayoutDirection = getLayoutDirection();
11931            // Set user padding to initial values ...
11932            mUserPaddingLeft = mUserPaddingLeftInitial;
11933            mUserPaddingRight = mUserPaddingRightInitial;
11934            // ... then resolve it.
11935            switch (resolvedLayoutDirection) {
11936                case LAYOUT_DIRECTION_RTL:
11937                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11938                        mUserPaddingRight = mUserPaddingStart;
11939                    }
11940                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11941                        mUserPaddingLeft = mUserPaddingEnd;
11942                    }
11943                    break;
11944                case LAYOUT_DIRECTION_LTR:
11945                default:
11946                    if (mUserPaddingStart != UNDEFINED_PADDING) {
11947                        mUserPaddingLeft = mUserPaddingStart;
11948                    }
11949                    if (mUserPaddingEnd != UNDEFINED_PADDING) {
11950                        mUserPaddingRight = mUserPaddingEnd;
11951                    }
11952            }
11953
11954            mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
11955
11956            internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight,
11957                    mUserPaddingBottom);
11958            onRtlPropertiesChanged(resolvedLayoutDirection);
11959        }
11960
11961        mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED;
11962    }
11963
11964    /**
11965     * Reset the resolved layout direction.
11966     *
11967     * @hide
11968     */
11969    public void resetResolvedPadding() {
11970        mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED;
11971    }
11972
11973    /**
11974     * This is called when the view is detached from a window.  At this point it
11975     * no longer has a surface for drawing.
11976     *
11977     * @see #onAttachedToWindow()
11978     */
11979    protected void onDetachedFromWindow() {
11980        mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
11981
11982        removeUnsetPressCallback();
11983        removeLongPressCallback();
11984        removePerformClickCallback();
11985        removeSendViewScrolledAccessibilityEventCallback();
11986
11987        destroyDrawingCache();
11988
11989        destroyLayer(false);
11990
11991        if (mAttachInfo != null) {
11992            if (mDisplayList != null) {
11993                mDisplayList.markDirty();
11994                mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList);
11995            }
11996            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
11997        } else {
11998            // Should never happen
11999            clearDisplayList();
12000        }
12001
12002        mCurrentAnimation = null;
12003
12004        resetAccessibilityStateChanged();
12005    }
12006
12007    /**
12008     * @return The number of times this view has been attached to a window
12009     */
12010    protected int getWindowAttachCount() {
12011        return mWindowAttachCount;
12012    }
12013
12014    /**
12015     * Retrieve a unique token identifying the window this view is attached to.
12016     * @return Return the window's token for use in
12017     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
12018     */
12019    public IBinder getWindowToken() {
12020        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
12021    }
12022
12023    /**
12024     * Retrieve the {@link WindowId} for the window this view is
12025     * currently attached to.
12026     */
12027    public WindowId getWindowId() {
12028        if (mAttachInfo == null) {
12029            return null;
12030        }
12031        if (mAttachInfo.mWindowId == null) {
12032            try {
12033                mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId(
12034                        mAttachInfo.mWindowToken);
12035                mAttachInfo.mWindowId = new WindowId(
12036                        mAttachInfo.mIWindowId);
12037            } catch (RemoteException e) {
12038            }
12039        }
12040        return mAttachInfo.mWindowId;
12041    }
12042
12043    /**
12044     * Retrieve a unique token identifying the top-level "real" window of
12045     * the window that this view is attached to.  That is, this is like
12046     * {@link #getWindowToken}, except if the window this view in is a panel
12047     * window (attached to another containing window), then the token of
12048     * the containing window is returned instead.
12049     *
12050     * @return Returns the associated window token, either
12051     * {@link #getWindowToken()} or the containing window's token.
12052     */
12053    public IBinder getApplicationWindowToken() {
12054        AttachInfo ai = mAttachInfo;
12055        if (ai != null) {
12056            IBinder appWindowToken = ai.mPanelParentWindowToken;
12057            if (appWindowToken == null) {
12058                appWindowToken = ai.mWindowToken;
12059            }
12060            return appWindowToken;
12061        }
12062        return null;
12063    }
12064
12065    /**
12066     * Gets the logical display to which the view's window has been attached.
12067     *
12068     * @return The logical display, or null if the view is not currently attached to a window.
12069     */
12070    public Display getDisplay() {
12071        return mAttachInfo != null ? mAttachInfo.mDisplay : null;
12072    }
12073
12074    /**
12075     * Retrieve private session object this view hierarchy is using to
12076     * communicate with the window manager.
12077     * @return the session object to communicate with the window manager
12078     */
12079    /*package*/ IWindowSession getWindowSession() {
12080        return mAttachInfo != null ? mAttachInfo.mSession : null;
12081    }
12082
12083    /**
12084     * @param info the {@link android.view.View.AttachInfo} to associated with
12085     *        this view
12086     */
12087    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
12088        //System.out.println("Attached! " + this);
12089        mAttachInfo = info;
12090        mWindowAttachCount++;
12091        // We will need to evaluate the drawable state at least once.
12092        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
12093        if (mFloatingTreeObserver != null) {
12094            info.mTreeObserver.merge(mFloatingTreeObserver);
12095            mFloatingTreeObserver = null;
12096        }
12097        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
12098            mAttachInfo.mScrollContainers.add(this);
12099            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
12100        }
12101        performCollectViewAttributes(mAttachInfo, visibility);
12102        onAttachedToWindow();
12103
12104        ListenerInfo li = mListenerInfo;
12105        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12106                li != null ? li.mOnAttachStateChangeListeners : null;
12107        if (listeners != null && listeners.size() > 0) {
12108            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12109            // perform the dispatching. The iterator is a safe guard against listeners that
12110            // could mutate the list by calling the various add/remove methods. This prevents
12111            // the array from being modified while we iterate it.
12112            for (OnAttachStateChangeListener listener : listeners) {
12113                listener.onViewAttachedToWindow(this);
12114            }
12115        }
12116
12117        int vis = info.mWindowVisibility;
12118        if (vis != GONE) {
12119            onWindowVisibilityChanged(vis);
12120        }
12121        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
12122            // If nobody has evaluated the drawable state yet, then do it now.
12123            refreshDrawableState();
12124        }
12125        needGlobalAttributesUpdate(false);
12126    }
12127
12128    void dispatchDetachedFromWindow() {
12129        AttachInfo info = mAttachInfo;
12130        if (info != null) {
12131            int vis = info.mWindowVisibility;
12132            if (vis != GONE) {
12133                onWindowVisibilityChanged(GONE);
12134            }
12135        }
12136
12137        onDetachedFromWindow();
12138
12139        ListenerInfo li = mListenerInfo;
12140        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
12141                li != null ? li.mOnAttachStateChangeListeners : null;
12142        if (listeners != null && listeners.size() > 0) {
12143            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
12144            // perform the dispatching. The iterator is a safe guard against listeners that
12145            // could mutate the list by calling the various add/remove methods. This prevents
12146            // the array from being modified while we iterate it.
12147            for (OnAttachStateChangeListener listener : listeners) {
12148                listener.onViewDetachedFromWindow(this);
12149            }
12150        }
12151
12152        if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) {
12153            mAttachInfo.mScrollContainers.remove(this);
12154            mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED;
12155        }
12156
12157        mAttachInfo = null;
12158    }
12159
12160    /**
12161     * Store this view hierarchy's frozen state into the given container.
12162     *
12163     * @param container The SparseArray in which to save the view's state.
12164     *
12165     * @see #restoreHierarchyState(android.util.SparseArray)
12166     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12167     * @see #onSaveInstanceState()
12168     */
12169    public void saveHierarchyState(SparseArray<Parcelable> container) {
12170        dispatchSaveInstanceState(container);
12171    }
12172
12173    /**
12174     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
12175     * this view and its children. May be overridden to modify how freezing happens to a
12176     * view's children; for example, some views may want to not store state for their children.
12177     *
12178     * @param container The SparseArray in which to save the view's state.
12179     *
12180     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12181     * @see #saveHierarchyState(android.util.SparseArray)
12182     * @see #onSaveInstanceState()
12183     */
12184    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
12185        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
12186            mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12187            Parcelable state = onSaveInstanceState();
12188            if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12189                throw new IllegalStateException(
12190                        "Derived class did not call super.onSaveInstanceState()");
12191            }
12192            if (state != null) {
12193                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
12194                // + ": " + state);
12195                container.put(mID, state);
12196            }
12197        }
12198    }
12199
12200    /**
12201     * Hook allowing a view to generate a representation of its internal state
12202     * that can later be used to create a new instance with that same state.
12203     * This state should only contain information that is not persistent or can
12204     * not be reconstructed later. For example, you will never store your
12205     * current position on screen because that will be computed again when a
12206     * new instance of the view is placed in its view hierarchy.
12207     * <p>
12208     * Some examples of things you may store here: the current cursor position
12209     * in a text view (but usually not the text itself since that is stored in a
12210     * content provider or other persistent storage), the currently selected
12211     * item in a list view.
12212     *
12213     * @return Returns a Parcelable object containing the view's current dynamic
12214     *         state, or null if there is nothing interesting to save. The
12215     *         default implementation returns null.
12216     * @see #onRestoreInstanceState(android.os.Parcelable)
12217     * @see #saveHierarchyState(android.util.SparseArray)
12218     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12219     * @see #setSaveEnabled(boolean)
12220     */
12221    protected Parcelable onSaveInstanceState() {
12222        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12223        return BaseSavedState.EMPTY_STATE;
12224    }
12225
12226    /**
12227     * Restore this view hierarchy's frozen state from the given container.
12228     *
12229     * @param container The SparseArray which holds previously frozen states.
12230     *
12231     * @see #saveHierarchyState(android.util.SparseArray)
12232     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12233     * @see #onRestoreInstanceState(android.os.Parcelable)
12234     */
12235    public void restoreHierarchyState(SparseArray<Parcelable> container) {
12236        dispatchRestoreInstanceState(container);
12237    }
12238
12239    /**
12240     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
12241     * state for this view and its children. May be overridden to modify how restoring
12242     * happens to a view's children; for example, some views may want to not store state
12243     * for their children.
12244     *
12245     * @param container The SparseArray which holds previously saved state.
12246     *
12247     * @see #dispatchSaveInstanceState(android.util.SparseArray)
12248     * @see #restoreHierarchyState(android.util.SparseArray)
12249     * @see #onRestoreInstanceState(android.os.Parcelable)
12250     */
12251    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
12252        if (mID != NO_ID) {
12253            Parcelable state = container.get(mID);
12254            if (state != null) {
12255                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
12256                // + ": " + state);
12257                mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
12258                onRestoreInstanceState(state);
12259                if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) {
12260                    throw new IllegalStateException(
12261                            "Derived class did not call super.onRestoreInstanceState()");
12262                }
12263            }
12264        }
12265    }
12266
12267    /**
12268     * Hook allowing a view to re-apply a representation of its internal state that had previously
12269     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
12270     * null state.
12271     *
12272     * @param state The frozen state that had previously been returned by
12273     *        {@link #onSaveInstanceState}.
12274     *
12275     * @see #onSaveInstanceState()
12276     * @see #restoreHierarchyState(android.util.SparseArray)
12277     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
12278     */
12279    protected void onRestoreInstanceState(Parcelable state) {
12280        mPrivateFlags |= PFLAG_SAVE_STATE_CALLED;
12281        if (state != BaseSavedState.EMPTY_STATE && state != null) {
12282            throw new IllegalArgumentException("Wrong state class, expecting View State but "
12283                    + "received " + state.getClass().toString() + " instead. This usually happens "
12284                    + "when two views of different type have the same id in the same hierarchy. "
12285                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
12286                    + "other views do not use the same id.");
12287        }
12288    }
12289
12290    /**
12291     * <p>Return the time at which the drawing of the view hierarchy started.</p>
12292     *
12293     * @return the drawing start time in milliseconds
12294     */
12295    public long getDrawingTime() {
12296        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
12297    }
12298
12299    /**
12300     * <p>Enables or disables the duplication of the parent's state into this view. When
12301     * duplication is enabled, this view gets its drawable state from its parent rather
12302     * than from its own internal properties.</p>
12303     *
12304     * <p>Note: in the current implementation, setting this property to true after the
12305     * view was added to a ViewGroup might have no effect at all. This property should
12306     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
12307     *
12308     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
12309     * property is enabled, an exception will be thrown.</p>
12310     *
12311     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
12312     * parent, these states should not be affected by this method.</p>
12313     *
12314     * @param enabled True to enable duplication of the parent's drawable state, false
12315     *                to disable it.
12316     *
12317     * @see #getDrawableState()
12318     * @see #isDuplicateParentStateEnabled()
12319     */
12320    public void setDuplicateParentStateEnabled(boolean enabled) {
12321        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
12322    }
12323
12324    /**
12325     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
12326     *
12327     * @return True if this view's drawable state is duplicated from the parent,
12328     *         false otherwise
12329     *
12330     * @see #getDrawableState()
12331     * @see #setDuplicateParentStateEnabled(boolean)
12332     */
12333    public boolean isDuplicateParentStateEnabled() {
12334        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
12335    }
12336
12337    /**
12338     * <p>Specifies the type of layer backing this view. The layer can be
12339     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
12340     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
12341     *
12342     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12343     * instance that controls how the layer is composed on screen. The following
12344     * properties of the paint are taken into account when composing the layer:</p>
12345     * <ul>
12346     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12347     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12348     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12349     * </ul>
12350     *
12351     * <p>If this view has an alpha value set to < 1.0 by calling
12352     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12353     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12354     * equivalent to setting a hardware layer on this view and providing a paint with
12355     * the desired alpha value.</p>
12356     *
12357     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
12358     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
12359     * for more information on when and how to use layers.</p>
12360     *
12361     * @param layerType The type of layer to use with this view, must be one of
12362     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12363     *        {@link #LAYER_TYPE_HARDWARE}
12364     * @param paint The paint used to compose the layer. This argument is optional
12365     *        and can be null. It is ignored when the layer type is
12366     *        {@link #LAYER_TYPE_NONE}
12367     *
12368     * @see #getLayerType()
12369     * @see #LAYER_TYPE_NONE
12370     * @see #LAYER_TYPE_SOFTWARE
12371     * @see #LAYER_TYPE_HARDWARE
12372     * @see #setAlpha(float)
12373     *
12374     * @attr ref android.R.styleable#View_layerType
12375     */
12376    public void setLayerType(int layerType, Paint paint) {
12377        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
12378            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
12379                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
12380        }
12381
12382        if (layerType == mLayerType) {
12383            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
12384                mLayerPaint = paint == null ? new Paint() : paint;
12385                invalidateParentCaches();
12386                invalidate(true);
12387            }
12388            return;
12389        }
12390
12391        // Destroy any previous software drawing cache if needed
12392        switch (mLayerType) {
12393            case LAYER_TYPE_HARDWARE:
12394                destroyLayer(false);
12395                // fall through - non-accelerated views may use software layer mechanism instead
12396            case LAYER_TYPE_SOFTWARE:
12397                destroyDrawingCache();
12398                break;
12399            default:
12400                break;
12401        }
12402
12403        mLayerType = layerType;
12404        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
12405        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
12406        mLocalDirtyRect = layerDisabled ? null : new Rect();
12407
12408        invalidateParentCaches();
12409        invalidate(true);
12410    }
12411
12412    /**
12413     * Updates the {@link Paint} object used with the current layer (used only if the current
12414     * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint
12415     * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time
12416     * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to
12417     * ensure that the view gets redrawn immediately.
12418     *
12419     * <p>A layer is associated with an optional {@link android.graphics.Paint}
12420     * instance that controls how the layer is composed on screen. The following
12421     * properties of the paint are taken into account when composing the layer:</p>
12422     * <ul>
12423     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
12424     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
12425     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
12426     * </ul>
12427     *
12428     * <p>If this view has an alpha value set to < 1.0 by calling
12429     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
12430     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
12431     * equivalent to setting a hardware layer on this view and providing a paint with
12432     * the desired alpha value.</p>
12433     *
12434     * @param paint The paint used to compose the layer. This argument is optional
12435     *        and can be null. It is ignored when the layer type is
12436     *        {@link #LAYER_TYPE_NONE}
12437     *
12438     * @see #setLayerType(int, android.graphics.Paint)
12439     */
12440    public void setLayerPaint(Paint paint) {
12441        int layerType = getLayerType();
12442        if (layerType != LAYER_TYPE_NONE) {
12443            mLayerPaint = paint == null ? new Paint() : paint;
12444            if (layerType == LAYER_TYPE_HARDWARE) {
12445                HardwareLayer layer = getHardwareLayer();
12446                if (layer != null) {
12447                    layer.setLayerPaint(paint);
12448                }
12449                invalidateViewProperty(false, false);
12450            } else {
12451                invalidate();
12452            }
12453        }
12454    }
12455
12456    /**
12457     * Indicates whether this view has a static layer. A view with layer type
12458     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
12459     * dynamic.
12460     */
12461    boolean hasStaticLayer() {
12462        return true;
12463    }
12464
12465    /**
12466     * Indicates what type of layer is currently associated with this view. By default
12467     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
12468     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
12469     * for more information on the different types of layers.
12470     *
12471     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
12472     *         {@link #LAYER_TYPE_HARDWARE}
12473     *
12474     * @see #setLayerType(int, android.graphics.Paint)
12475     * @see #buildLayer()
12476     * @see #LAYER_TYPE_NONE
12477     * @see #LAYER_TYPE_SOFTWARE
12478     * @see #LAYER_TYPE_HARDWARE
12479     */
12480    public int getLayerType() {
12481        return mLayerType;
12482    }
12483
12484    /**
12485     * Forces this view's layer to be created and this view to be rendered
12486     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
12487     * invoking this method will have no effect.
12488     *
12489     * This method can for instance be used to render a view into its layer before
12490     * starting an animation. If this view is complex, rendering into the layer
12491     * before starting the animation will avoid skipping frames.
12492     *
12493     * @throws IllegalStateException If this view is not attached to a window
12494     *
12495     * @see #setLayerType(int, android.graphics.Paint)
12496     */
12497    public void buildLayer() {
12498        if (mLayerType == LAYER_TYPE_NONE) return;
12499
12500        if (mAttachInfo == null) {
12501            throw new IllegalStateException("This view must be attached to a window first");
12502        }
12503
12504        switch (mLayerType) {
12505            case LAYER_TYPE_HARDWARE:
12506                if (mAttachInfo.mHardwareRenderer != null &&
12507                        mAttachInfo.mHardwareRenderer.isEnabled() &&
12508                        mAttachInfo.mHardwareRenderer.validate()) {
12509                    getHardwareLayer();
12510                }
12511                break;
12512            case LAYER_TYPE_SOFTWARE:
12513                buildDrawingCache(true);
12514                break;
12515        }
12516    }
12517
12518    /**
12519     * <p>Returns a hardware layer that can be used to draw this view again
12520     * without executing its draw method.</p>
12521     *
12522     * @return A HardwareLayer ready to render, or null if an error occurred.
12523     */
12524    HardwareLayer getHardwareLayer() {
12525        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
12526                !mAttachInfo.mHardwareRenderer.isEnabled()) {
12527            return null;
12528        }
12529
12530        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
12531
12532        final int width = mRight - mLeft;
12533        final int height = mBottom - mTop;
12534
12535        if (width == 0 || height == 0) {
12536            return null;
12537        }
12538
12539        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
12540            if (mHardwareLayer == null) {
12541                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
12542                        width, height, isOpaque());
12543                mLocalDirtyRect.set(0, 0, width, height);
12544            } else {
12545                if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
12546                    if (mHardwareLayer.resize(width, height)) {
12547                        mLocalDirtyRect.set(0, 0, width, height);
12548                    }
12549                }
12550
12551                // This should not be necessary but applications that change
12552                // the parameters of their background drawable without calling
12553                // this.setBackground(Drawable) can leave the view in a bad state
12554                // (for instance isOpaque() returns true, but the background is
12555                // not opaque.)
12556                computeOpaqueFlags();
12557
12558                final boolean opaque = isOpaque();
12559                if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) {
12560                    mHardwareLayer.setOpaque(opaque);
12561                    mLocalDirtyRect.set(0, 0, width, height);
12562                }
12563            }
12564
12565            // The layer is not valid if the underlying GPU resources cannot be allocated
12566            if (!mHardwareLayer.isValid()) {
12567                return null;
12568            }
12569
12570            mHardwareLayer.setLayerPaint(mLayerPaint);
12571            mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
12572            ViewRootImpl viewRoot = getViewRootImpl();
12573            if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer);
12574
12575            mLocalDirtyRect.setEmpty();
12576        }
12577
12578        return mHardwareLayer;
12579    }
12580
12581    /**
12582     * Destroys this View's hardware layer if possible.
12583     *
12584     * @return True if the layer was destroyed, false otherwise.
12585     *
12586     * @see #setLayerType(int, android.graphics.Paint)
12587     * @see #LAYER_TYPE_HARDWARE
12588     */
12589    boolean destroyLayer(boolean valid) {
12590        if (mHardwareLayer != null) {
12591            AttachInfo info = mAttachInfo;
12592            if (info != null && info.mHardwareRenderer != null &&
12593                    info.mHardwareRenderer.isEnabled() &&
12594                    (valid || info.mHardwareRenderer.validate())) {
12595                mHardwareLayer.destroy();
12596                mHardwareLayer = null;
12597
12598                if (mDisplayList != null) {
12599                    mDisplayList.reset();
12600                }
12601                invalidate(true);
12602                invalidateParentCaches();
12603            }
12604            return true;
12605        }
12606        return false;
12607    }
12608
12609    /**
12610     * Destroys all hardware rendering resources. This method is invoked
12611     * when the system needs to reclaim resources. Upon execution of this
12612     * method, you should free any OpenGL resources created by the view.
12613     *
12614     * Note: you <strong>must</strong> call
12615     * <code>super.destroyHardwareResources()</code> when overriding
12616     * this method.
12617     *
12618     * @hide
12619     */
12620    protected void destroyHardwareResources() {
12621        destroyLayer(true);
12622    }
12623
12624    /**
12625     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
12626     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
12627     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
12628     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
12629     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
12630     * null.</p>
12631     *
12632     * <p>Enabling the drawing cache is similar to
12633     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
12634     * acceleration is turned off. When hardware acceleration is turned on, enabling the
12635     * drawing cache has no effect on rendering because the system uses a different mechanism
12636     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
12637     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
12638     * for information on how to enable software and hardware layers.</p>
12639     *
12640     * <p>This API can be used to manually generate
12641     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
12642     * {@link #getDrawingCache()}.</p>
12643     *
12644     * @param enabled true to enable the drawing cache, false otherwise
12645     *
12646     * @see #isDrawingCacheEnabled()
12647     * @see #getDrawingCache()
12648     * @see #buildDrawingCache()
12649     * @see #setLayerType(int, android.graphics.Paint)
12650     */
12651    public void setDrawingCacheEnabled(boolean enabled) {
12652        mCachingFailed = false;
12653        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
12654    }
12655
12656    /**
12657     * <p>Indicates whether the drawing cache is enabled for this view.</p>
12658     *
12659     * @return true if the drawing cache is enabled
12660     *
12661     * @see #setDrawingCacheEnabled(boolean)
12662     * @see #getDrawingCache()
12663     */
12664    @ViewDebug.ExportedProperty(category = "drawing")
12665    public boolean isDrawingCacheEnabled() {
12666        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
12667    }
12668
12669    /**
12670     * Debugging utility which recursively outputs the dirty state of a view and its
12671     * descendants.
12672     *
12673     * @hide
12674     */
12675    @SuppressWarnings({"UnusedDeclaration"})
12676    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
12677        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) +
12678                ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" +
12679                (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) +
12680                ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")");
12681        if (clear) {
12682            mPrivateFlags &= clearMask;
12683        }
12684        if (this instanceof ViewGroup) {
12685            ViewGroup parent = (ViewGroup) this;
12686            final int count = parent.getChildCount();
12687            for (int i = 0; i < count; i++) {
12688                final View child = parent.getChildAt(i);
12689                child.outputDirtyFlags(indent + "  ", clear, clearMask);
12690            }
12691        }
12692    }
12693
12694    /**
12695     * This method is used by ViewGroup to cause its children to restore or recreate their
12696     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
12697     * to recreate its own display list, which would happen if it went through the normal
12698     * draw/dispatchDraw mechanisms.
12699     *
12700     * @hide
12701     */
12702    protected void dispatchGetDisplayList() {}
12703
12704    /**
12705     * A view that is not attached or hardware accelerated cannot create a display list.
12706     * This method checks these conditions and returns the appropriate result.
12707     *
12708     * @return true if view has the ability to create a display list, false otherwise.
12709     *
12710     * @hide
12711     */
12712    public boolean canHaveDisplayList() {
12713        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
12714    }
12715
12716    /**
12717     * @return The {@link HardwareRenderer} associated with that view or null if
12718     *         hardware rendering is not supported or this view is not attached
12719     *         to a window.
12720     *
12721     * @hide
12722     */
12723    public HardwareRenderer getHardwareRenderer() {
12724        if (mAttachInfo != null) {
12725            return mAttachInfo.mHardwareRenderer;
12726        }
12727        return null;
12728    }
12729
12730    /**
12731     * Returns a DisplayList. If the incoming displayList is null, one will be created.
12732     * Otherwise, the same display list will be returned (after having been rendered into
12733     * along the way, depending on the invalidation state of the view).
12734     *
12735     * @param displayList The previous version of this displayList, could be null.
12736     * @param isLayer Whether the requester of the display list is a layer. If so,
12737     * the view will avoid creating a layer inside the resulting display list.
12738     * @return A new or reused DisplayList object.
12739     */
12740    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
12741        if (!canHaveDisplayList()) {
12742            return null;
12743        }
12744
12745        if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 ||
12746                displayList == null || !displayList.isValid() ||
12747                (!isLayer && mRecreateDisplayList))) {
12748            // Don't need to recreate the display list, just need to tell our
12749            // children to restore/recreate theirs
12750            if (displayList != null && displayList.isValid() &&
12751                    !isLayer && !mRecreateDisplayList) {
12752                mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12753                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12754                dispatchGetDisplayList();
12755
12756                return displayList;
12757            }
12758
12759            if (!isLayer) {
12760                // If we got here, we're recreating it. Mark it as such to ensure that
12761                // we copy in child display lists into ours in drawChild()
12762                mRecreateDisplayList = true;
12763            }
12764            if (displayList == null) {
12765                final String name = getClass().getSimpleName();
12766                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
12767                // If we're creating a new display list, make sure our parent gets invalidated
12768                // since they will need to recreate their display list to account for this
12769                // new child display list.
12770                invalidateParentCaches();
12771            }
12772
12773            boolean caching = false;
12774            int width = mRight - mLeft;
12775            int height = mBottom - mTop;
12776            int layerType = getLayerType();
12777
12778            final HardwareCanvas canvas = displayList.start(width, height);
12779
12780            try {
12781                if (!isLayer && layerType != LAYER_TYPE_NONE) {
12782                    if (layerType == LAYER_TYPE_HARDWARE) {
12783                        final HardwareLayer layer = getHardwareLayer();
12784                        if (layer != null && layer.isValid()) {
12785                            canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
12786                        } else {
12787                            canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint,
12788                                    Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
12789                                            Canvas.CLIP_TO_LAYER_SAVE_FLAG);
12790                        }
12791                        caching = true;
12792                    } else {
12793                        buildDrawingCache(true);
12794                        Bitmap cache = getDrawingCache(true);
12795                        if (cache != null) {
12796                            canvas.drawBitmap(cache, 0, 0, mLayerPaint);
12797                            caching = true;
12798                        }
12799                    }
12800                } else {
12801
12802                    computeScroll();
12803
12804                    canvas.translate(-mScrollX, -mScrollY);
12805                    if (!isLayer) {
12806                        mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12807                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12808                    }
12809
12810                    // Fast path for layouts with no backgrounds
12811                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
12812                        dispatchDraw(canvas);
12813                    } else {
12814                        draw(canvas);
12815                    }
12816                }
12817            } finally {
12818                displayList.end();
12819                displayList.setCaching(caching);
12820                if (isLayer) {
12821                    displayList.setLeftTopRightBottom(0, 0, width, height);
12822                } else {
12823                    setDisplayListProperties(displayList);
12824                }
12825            }
12826        } else if (!isLayer) {
12827            mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID;
12828            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
12829        }
12830
12831        return displayList;
12832    }
12833
12834    /**
12835     * Get the DisplayList for the HardwareLayer
12836     *
12837     * @param layer The HardwareLayer whose DisplayList we want
12838     * @return A DisplayList fopr the specified HardwareLayer
12839     */
12840    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
12841        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
12842        layer.setDisplayList(displayList);
12843        return displayList;
12844    }
12845
12846
12847    /**
12848     * <p>Returns a display list that can be used to draw this view again
12849     * without executing its draw method.</p>
12850     *
12851     * @return A DisplayList ready to replay, or null if caching is not enabled.
12852     *
12853     * @hide
12854     */
12855    public DisplayList getDisplayList() {
12856        mDisplayList = getDisplayList(mDisplayList, false);
12857        return mDisplayList;
12858    }
12859
12860    private void clearDisplayList() {
12861        if (mDisplayList != null) {
12862            mDisplayList.clear();
12863        }
12864    }
12865
12866    /**
12867     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
12868     *
12869     * @return A non-scaled bitmap representing this view or null if cache is disabled.
12870     *
12871     * @see #getDrawingCache(boolean)
12872     */
12873    public Bitmap getDrawingCache() {
12874        return getDrawingCache(false);
12875    }
12876
12877    /**
12878     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
12879     * is null when caching is disabled. If caching is enabled and the cache is not ready,
12880     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
12881     * draw from the cache when the cache is enabled. To benefit from the cache, you must
12882     * request the drawing cache by calling this method and draw it on screen if the
12883     * returned bitmap is not null.</p>
12884     *
12885     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12886     * this method will create a bitmap of the same size as this view. Because this bitmap
12887     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12888     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12889     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12890     * size than the view. This implies that your application must be able to handle this
12891     * size.</p>
12892     *
12893     * @param autoScale Indicates whether the generated bitmap should be scaled based on
12894     *        the current density of the screen when the application is in compatibility
12895     *        mode.
12896     *
12897     * @return A bitmap representing this view or null if cache is disabled.
12898     *
12899     * @see #setDrawingCacheEnabled(boolean)
12900     * @see #isDrawingCacheEnabled()
12901     * @see #buildDrawingCache(boolean)
12902     * @see #destroyDrawingCache()
12903     */
12904    public Bitmap getDrawingCache(boolean autoScale) {
12905        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
12906            return null;
12907        }
12908        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
12909            buildDrawingCache(autoScale);
12910        }
12911        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
12912    }
12913
12914    /**
12915     * <p>Frees the resources used by the drawing cache. If you call
12916     * {@link #buildDrawingCache()} manually without calling
12917     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12918     * should cleanup the cache with this method afterwards.</p>
12919     *
12920     * @see #setDrawingCacheEnabled(boolean)
12921     * @see #buildDrawingCache()
12922     * @see #getDrawingCache()
12923     */
12924    public void destroyDrawingCache() {
12925        if (mDrawingCache != null) {
12926            mDrawingCache.recycle();
12927            mDrawingCache = null;
12928        }
12929        if (mUnscaledDrawingCache != null) {
12930            mUnscaledDrawingCache.recycle();
12931            mUnscaledDrawingCache = null;
12932        }
12933    }
12934
12935    /**
12936     * Setting a solid background color for the drawing cache's bitmaps will improve
12937     * performance and memory usage. Note, though that this should only be used if this
12938     * view will always be drawn on top of a solid color.
12939     *
12940     * @param color The background color to use for the drawing cache's bitmap
12941     *
12942     * @see #setDrawingCacheEnabled(boolean)
12943     * @see #buildDrawingCache()
12944     * @see #getDrawingCache()
12945     */
12946    public void setDrawingCacheBackgroundColor(int color) {
12947        if (color != mDrawingCacheBackgroundColor) {
12948            mDrawingCacheBackgroundColor = color;
12949            mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
12950        }
12951    }
12952
12953    /**
12954     * @see #setDrawingCacheBackgroundColor(int)
12955     *
12956     * @return The background color to used for the drawing cache's bitmap
12957     */
12958    public int getDrawingCacheBackgroundColor() {
12959        return mDrawingCacheBackgroundColor;
12960    }
12961
12962    /**
12963     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
12964     *
12965     * @see #buildDrawingCache(boolean)
12966     */
12967    public void buildDrawingCache() {
12968        buildDrawingCache(false);
12969    }
12970
12971    /**
12972     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
12973     *
12974     * <p>If you call {@link #buildDrawingCache()} manually without calling
12975     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
12976     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
12977     *
12978     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
12979     * this method will create a bitmap of the same size as this view. Because this bitmap
12980     * will be drawn scaled by the parent ViewGroup, the result on screen might show
12981     * scaling artifacts. To avoid such artifacts, you should call this method by setting
12982     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
12983     * size than the view. This implies that your application must be able to handle this
12984     * size.</p>
12985     *
12986     * <p>You should avoid calling this method when hardware acceleration is enabled. If
12987     * you do not need the drawing cache bitmap, calling this method will increase memory
12988     * usage and cause the view to be rendered in software once, thus negatively impacting
12989     * performance.</p>
12990     *
12991     * @see #getDrawingCache()
12992     * @see #destroyDrawingCache()
12993     */
12994    public void buildDrawingCache(boolean autoScale) {
12995        if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ?
12996                mDrawingCache == null : mUnscaledDrawingCache == null)) {
12997            mCachingFailed = false;
12998
12999            int width = mRight - mLeft;
13000            int height = mBottom - mTop;
13001
13002            final AttachInfo attachInfo = mAttachInfo;
13003            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
13004
13005            if (autoScale && scalingRequired) {
13006                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
13007                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
13008            }
13009
13010            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
13011            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
13012            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
13013
13014            final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4);
13015            final long drawingCacheSize =
13016                    ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize();
13017            if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) {
13018                if (width > 0 && height > 0) {
13019                    Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs "
13020                            + projectedBitmapSize + " bytes, only "
13021                            + drawingCacheSize + " available");
13022                }
13023                destroyDrawingCache();
13024                mCachingFailed = true;
13025                return;
13026            }
13027
13028            boolean clear = true;
13029            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
13030
13031            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
13032                Bitmap.Config quality;
13033                if (!opaque) {
13034                    // Never pick ARGB_4444 because it looks awful
13035                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
13036                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
13037                        case DRAWING_CACHE_QUALITY_AUTO:
13038                            quality = Bitmap.Config.ARGB_8888;
13039                            break;
13040                        case DRAWING_CACHE_QUALITY_LOW:
13041                            quality = Bitmap.Config.ARGB_8888;
13042                            break;
13043                        case DRAWING_CACHE_QUALITY_HIGH:
13044                            quality = Bitmap.Config.ARGB_8888;
13045                            break;
13046                        default:
13047                            quality = Bitmap.Config.ARGB_8888;
13048                            break;
13049                    }
13050                } else {
13051                    // Optimization for translucent windows
13052                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
13053                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
13054                }
13055
13056                // Try to cleanup memory
13057                if (bitmap != null) bitmap.recycle();
13058
13059                try {
13060                    bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13061                            width, height, quality);
13062                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
13063                    if (autoScale) {
13064                        mDrawingCache = bitmap;
13065                    } else {
13066                        mUnscaledDrawingCache = bitmap;
13067                    }
13068                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
13069                } catch (OutOfMemoryError e) {
13070                    // If there is not enough memory to create the bitmap cache, just
13071                    // ignore the issue as bitmap caches are not required to draw the
13072                    // view hierarchy
13073                    if (autoScale) {
13074                        mDrawingCache = null;
13075                    } else {
13076                        mUnscaledDrawingCache = null;
13077                    }
13078                    mCachingFailed = true;
13079                    return;
13080                }
13081
13082                clear = drawingCacheBackgroundColor != 0;
13083            }
13084
13085            Canvas canvas;
13086            if (attachInfo != null) {
13087                canvas = attachInfo.mCanvas;
13088                if (canvas == null) {
13089                    canvas = new Canvas();
13090                }
13091                canvas.setBitmap(bitmap);
13092                // Temporarily clobber the cached Canvas in case one of our children
13093                // is also using a drawing cache. Without this, the children would
13094                // steal the canvas by attaching their own bitmap to it and bad, bad
13095                // thing would happen (invisible views, corrupted drawings, etc.)
13096                attachInfo.mCanvas = null;
13097            } else {
13098                // This case should hopefully never or seldom happen
13099                canvas = new Canvas(bitmap);
13100            }
13101
13102            if (clear) {
13103                bitmap.eraseColor(drawingCacheBackgroundColor);
13104            }
13105
13106            computeScroll();
13107            final int restoreCount = canvas.save();
13108
13109            if (autoScale && scalingRequired) {
13110                final float scale = attachInfo.mApplicationScale;
13111                canvas.scale(scale, scale);
13112            }
13113
13114            canvas.translate(-mScrollX, -mScrollY);
13115
13116            mPrivateFlags |= PFLAG_DRAWN;
13117            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
13118                    mLayerType != LAYER_TYPE_NONE) {
13119                mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID;
13120            }
13121
13122            // Fast path for layouts with no backgrounds
13123            if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13124                mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13125                dispatchDraw(canvas);
13126            } else {
13127                draw(canvas);
13128            }
13129
13130            canvas.restoreToCount(restoreCount);
13131            canvas.setBitmap(null);
13132
13133            if (attachInfo != null) {
13134                // Restore the cached Canvas for our siblings
13135                attachInfo.mCanvas = canvas;
13136            }
13137        }
13138    }
13139
13140    /**
13141     * Create a snapshot of the view into a bitmap.  We should probably make
13142     * some form of this public, but should think about the API.
13143     */
13144    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
13145        int width = mRight - mLeft;
13146        int height = mBottom - mTop;
13147
13148        final AttachInfo attachInfo = mAttachInfo;
13149        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
13150        width = (int) ((width * scale) + 0.5f);
13151        height = (int) ((height * scale) + 0.5f);
13152
13153        Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(),
13154                width > 0 ? width : 1, height > 0 ? height : 1, quality);
13155        if (bitmap == null) {
13156            throw new OutOfMemoryError();
13157        }
13158
13159        Resources resources = getResources();
13160        if (resources != null) {
13161            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
13162        }
13163
13164        Canvas canvas;
13165        if (attachInfo != null) {
13166            canvas = attachInfo.mCanvas;
13167            if (canvas == null) {
13168                canvas = new Canvas();
13169            }
13170            canvas.setBitmap(bitmap);
13171            // Temporarily clobber the cached Canvas in case one of our children
13172            // is also using a drawing cache. Without this, the children would
13173            // steal the canvas by attaching their own bitmap to it and bad, bad
13174            // things would happen (invisible views, corrupted drawings, etc.)
13175            attachInfo.mCanvas = null;
13176        } else {
13177            // This case should hopefully never or seldom happen
13178            canvas = new Canvas(bitmap);
13179        }
13180
13181        if ((backgroundColor & 0xff000000) != 0) {
13182            bitmap.eraseColor(backgroundColor);
13183        }
13184
13185        computeScroll();
13186        final int restoreCount = canvas.save();
13187        canvas.scale(scale, scale);
13188        canvas.translate(-mScrollX, -mScrollY);
13189
13190        // Temporarily remove the dirty mask
13191        int flags = mPrivateFlags;
13192        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13193
13194        // Fast path for layouts with no backgrounds
13195        if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13196            dispatchDraw(canvas);
13197        } else {
13198            draw(canvas);
13199        }
13200
13201        mPrivateFlags = flags;
13202
13203        canvas.restoreToCount(restoreCount);
13204        canvas.setBitmap(null);
13205
13206        if (attachInfo != null) {
13207            // Restore the cached Canvas for our siblings
13208            attachInfo.mCanvas = canvas;
13209        }
13210
13211        return bitmap;
13212    }
13213
13214    /**
13215     * Indicates whether this View is currently in edit mode. A View is usually
13216     * in edit mode when displayed within a developer tool. For instance, if
13217     * this View is being drawn by a visual user interface builder, this method
13218     * should return true.
13219     *
13220     * Subclasses should check the return value of this method to provide
13221     * different behaviors if their normal behavior might interfere with the
13222     * host environment. For instance: the class spawns a thread in its
13223     * constructor, the drawing code relies on device-specific features, etc.
13224     *
13225     * This method is usually checked in the drawing code of custom widgets.
13226     *
13227     * @return True if this View is in edit mode, false otherwise.
13228     */
13229    public boolean isInEditMode() {
13230        return false;
13231    }
13232
13233    /**
13234     * If the View draws content inside its padding and enables fading edges,
13235     * it needs to support padding offsets. Padding offsets are added to the
13236     * fading edges to extend the length of the fade so that it covers pixels
13237     * drawn inside the padding.
13238     *
13239     * Subclasses of this class should override this method if they need
13240     * to draw content inside the padding.
13241     *
13242     * @return True if padding offset must be applied, false otherwise.
13243     *
13244     * @see #getLeftPaddingOffset()
13245     * @see #getRightPaddingOffset()
13246     * @see #getTopPaddingOffset()
13247     * @see #getBottomPaddingOffset()
13248     *
13249     * @since CURRENT
13250     */
13251    protected boolean isPaddingOffsetRequired() {
13252        return false;
13253    }
13254
13255    /**
13256     * Amount by which to extend the left fading region. Called only when
13257     * {@link #isPaddingOffsetRequired()} returns true.
13258     *
13259     * @return The left padding offset in pixels.
13260     *
13261     * @see #isPaddingOffsetRequired()
13262     *
13263     * @since CURRENT
13264     */
13265    protected int getLeftPaddingOffset() {
13266        return 0;
13267    }
13268
13269    /**
13270     * Amount by which to extend the right fading region. Called only when
13271     * {@link #isPaddingOffsetRequired()} returns true.
13272     *
13273     * @return The right padding offset in pixels.
13274     *
13275     * @see #isPaddingOffsetRequired()
13276     *
13277     * @since CURRENT
13278     */
13279    protected int getRightPaddingOffset() {
13280        return 0;
13281    }
13282
13283    /**
13284     * Amount by which to extend the top fading region. Called only when
13285     * {@link #isPaddingOffsetRequired()} returns true.
13286     *
13287     * @return The top padding offset in pixels.
13288     *
13289     * @see #isPaddingOffsetRequired()
13290     *
13291     * @since CURRENT
13292     */
13293    protected int getTopPaddingOffset() {
13294        return 0;
13295    }
13296
13297    /**
13298     * Amount by which to extend the bottom fading region. Called only when
13299     * {@link #isPaddingOffsetRequired()} returns true.
13300     *
13301     * @return The bottom padding offset in pixels.
13302     *
13303     * @see #isPaddingOffsetRequired()
13304     *
13305     * @since CURRENT
13306     */
13307    protected int getBottomPaddingOffset() {
13308        return 0;
13309    }
13310
13311    /**
13312     * @hide
13313     * @param offsetRequired
13314     */
13315    protected int getFadeTop(boolean offsetRequired) {
13316        int top = mPaddingTop;
13317        if (offsetRequired) top += getTopPaddingOffset();
13318        return top;
13319    }
13320
13321    /**
13322     * @hide
13323     * @param offsetRequired
13324     */
13325    protected int getFadeHeight(boolean offsetRequired) {
13326        int padding = mPaddingTop;
13327        if (offsetRequired) padding += getTopPaddingOffset();
13328        return mBottom - mTop - mPaddingBottom - padding;
13329    }
13330
13331    /**
13332     * <p>Indicates whether this view is attached to a hardware accelerated
13333     * window or not.</p>
13334     *
13335     * <p>Even if this method returns true, it does not mean that every call
13336     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
13337     * accelerated {@link android.graphics.Canvas}. For instance, if this view
13338     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
13339     * window is hardware accelerated,
13340     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
13341     * return false, and this method will return true.</p>
13342     *
13343     * @return True if the view is attached to a window and the window is
13344     *         hardware accelerated; false in any other case.
13345     */
13346    public boolean isHardwareAccelerated() {
13347        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13348    }
13349
13350    /**
13351     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
13352     * case of an active Animation being run on the view.
13353     */
13354    private boolean drawAnimation(ViewGroup parent, long drawingTime,
13355            Animation a, boolean scalingRequired) {
13356        Transformation invalidationTransform;
13357        final int flags = parent.mGroupFlags;
13358        final boolean initialized = a.isInitialized();
13359        if (!initialized) {
13360            a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight());
13361            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
13362            if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler);
13363            onAnimationStart();
13364        }
13365
13366        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
13367        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
13368            if (parent.mInvalidationTransformation == null) {
13369                parent.mInvalidationTransformation = new Transformation();
13370            }
13371            invalidationTransform = parent.mInvalidationTransformation;
13372            a.getTransformation(drawingTime, invalidationTransform, 1f);
13373        } else {
13374            invalidationTransform = parent.mChildTransformation;
13375        }
13376
13377        if (more) {
13378            if (!a.willChangeBounds()) {
13379                if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) ==
13380                        ViewGroup.FLAG_OPTIMIZE_INVALIDATE) {
13381                    parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED;
13382                } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) {
13383                    // The child need to draw an animation, potentially offscreen, so
13384                    // make sure we do not cancel invalidate requests
13385                    parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13386                    parent.invalidate(mLeft, mTop, mRight, mBottom);
13387                }
13388            } else {
13389                if (parent.mInvalidateRegion == null) {
13390                    parent.mInvalidateRegion = new RectF();
13391                }
13392                final RectF region = parent.mInvalidateRegion;
13393                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
13394                        invalidationTransform);
13395
13396                // The child need to draw an animation, potentially offscreen, so
13397                // make sure we do not cancel invalidate requests
13398                parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
13399
13400                final int left = mLeft + (int) region.left;
13401                final int top = mTop + (int) region.top;
13402                parent.invalidate(left, top, left + (int) (region.width() + .5f),
13403                        top + (int) (region.height() + .5f));
13404            }
13405        }
13406        return more;
13407    }
13408
13409    /**
13410     * This method is called by getDisplayList() when a display list is created or re-rendered.
13411     * It sets or resets the current value of all properties on that display list (resetting is
13412     * necessary when a display list is being re-created, because we need to make sure that
13413     * previously-set transform values
13414     */
13415    void setDisplayListProperties(DisplayList displayList) {
13416        if (displayList != null) {
13417            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
13418            displayList.setHasOverlappingRendering(hasOverlappingRendering());
13419            if (mParent instanceof ViewGroup) {
13420                displayList.setClipChildren(
13421                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
13422            }
13423            float alpha = 1;
13424            if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags &
13425                    ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13426                ViewGroup parentVG = (ViewGroup) mParent;
13427                final boolean hasTransform =
13428                        parentVG.getChildStaticTransformation(this, parentVG.mChildTransformation);
13429                if (hasTransform) {
13430                    Transformation transform = parentVG.mChildTransformation;
13431                    final int transformType = parentVG.mChildTransformation.getTransformationType();
13432                    if (transformType != Transformation.TYPE_IDENTITY) {
13433                        if ((transformType & Transformation.TYPE_ALPHA) != 0) {
13434                            alpha = transform.getAlpha();
13435                        }
13436                        if ((transformType & Transformation.TYPE_MATRIX) != 0) {
13437                            displayList.setMatrix(transform.getMatrix());
13438                        }
13439                    }
13440                }
13441            }
13442            if (mTransformationInfo != null) {
13443                alpha *= mTransformationInfo.mAlpha;
13444                if (alpha < 1) {
13445                    final int multipliedAlpha = (int) (255 * alpha);
13446                    if (onSetAlpha(multipliedAlpha)) {
13447                        alpha = 1;
13448                    }
13449                }
13450                displayList.setTransformationInfo(alpha,
13451                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
13452                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
13453                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
13454                        mTransformationInfo.mScaleY);
13455                if (mTransformationInfo.mCamera == null) {
13456                    mTransformationInfo.mCamera = new Camera();
13457                    mTransformationInfo.matrix3D = new Matrix();
13458                }
13459                displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ());
13460                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) {
13461                    displayList.setPivotX(getPivotX());
13462                    displayList.setPivotY(getPivotY());
13463                }
13464            } else if (alpha < 1) {
13465                displayList.setAlpha(alpha);
13466            }
13467        }
13468    }
13469
13470    /**
13471     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
13472     * This draw() method is an implementation detail and is not intended to be overridden or
13473     * to be called from anywhere else other than ViewGroup.drawChild().
13474     */
13475    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
13476        boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
13477        boolean more = false;
13478        final boolean childHasIdentityMatrix = hasIdentityMatrix();
13479        final int flags = parent.mGroupFlags;
13480
13481        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
13482            parent.mChildTransformation.clear();
13483            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13484        }
13485
13486        Transformation transformToApply = null;
13487        boolean concatMatrix = false;
13488
13489        boolean scalingRequired = false;
13490        boolean caching;
13491        int layerType = getLayerType();
13492
13493        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
13494        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
13495                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
13496            caching = true;
13497            // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList
13498            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
13499        } else {
13500            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
13501        }
13502
13503        final Animation a = getAnimation();
13504        if (a != null) {
13505            more = drawAnimation(parent, drawingTime, a, scalingRequired);
13506            concatMatrix = a.willChangeTransformationMatrix();
13507            if (concatMatrix) {
13508                mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13509            }
13510            transformToApply = parent.mChildTransformation;
13511        } else {
13512            if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) ==
13513                    PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) {
13514                // No longer animating: clear out old animation matrix
13515                mDisplayList.setAnimationMatrix(null);
13516                mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM;
13517            }
13518            if (!useDisplayListProperties &&
13519                    (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
13520                final boolean hasTransform =
13521                        parent.getChildStaticTransformation(this, parent.mChildTransformation);
13522                if (hasTransform) {
13523                    final int transformType = parent.mChildTransformation.getTransformationType();
13524                    transformToApply = transformType != Transformation.TYPE_IDENTITY ?
13525                            parent.mChildTransformation : null;
13526                    concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
13527                }
13528            }
13529        }
13530
13531        concatMatrix |= !childHasIdentityMatrix;
13532
13533        // Sets the flag as early as possible to allow draw() implementations
13534        // to call invalidate() successfully when doing animations
13535        mPrivateFlags |= PFLAG_DRAWN;
13536
13537        if (!concatMatrix &&
13538                (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS |
13539                        ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN &&
13540                canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
13541                (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) {
13542            mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED;
13543            return more;
13544        }
13545        mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED;
13546
13547        if (hardwareAccelerated) {
13548            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
13549            // retain the flag's value temporarily in the mRecreateDisplayList flag
13550            mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED;
13551            mPrivateFlags &= ~PFLAG_INVALIDATED;
13552        }
13553
13554        DisplayList displayList = null;
13555        Bitmap cache = null;
13556        boolean hasDisplayList = false;
13557        if (caching) {
13558            if (!hardwareAccelerated) {
13559                if (layerType != LAYER_TYPE_NONE) {
13560                    layerType = LAYER_TYPE_SOFTWARE;
13561                    buildDrawingCache(true);
13562                }
13563                cache = getDrawingCache(true);
13564            } else {
13565                switch (layerType) {
13566                    case LAYER_TYPE_SOFTWARE:
13567                        if (useDisplayListProperties) {
13568                            hasDisplayList = canHaveDisplayList();
13569                        } else {
13570                            buildDrawingCache(true);
13571                            cache = getDrawingCache(true);
13572                        }
13573                        break;
13574                    case LAYER_TYPE_HARDWARE:
13575                        if (useDisplayListProperties) {
13576                            hasDisplayList = canHaveDisplayList();
13577                        }
13578                        break;
13579                    case LAYER_TYPE_NONE:
13580                        // Delay getting the display list until animation-driven alpha values are
13581                        // set up and possibly passed on to the view
13582                        hasDisplayList = canHaveDisplayList();
13583                        break;
13584                }
13585            }
13586        }
13587        useDisplayListProperties &= hasDisplayList;
13588        if (useDisplayListProperties) {
13589            displayList = getDisplayList();
13590            if (!displayList.isValid()) {
13591                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13592                // to getDisplayList(), the display list will be marked invalid and we should not
13593                // try to use it again.
13594                displayList = null;
13595                hasDisplayList = false;
13596                useDisplayListProperties = false;
13597            }
13598        }
13599
13600        int sx = 0;
13601        int sy = 0;
13602        if (!hasDisplayList) {
13603            computeScroll();
13604            sx = mScrollX;
13605            sy = mScrollY;
13606        }
13607
13608        final boolean hasNoCache = cache == null || hasDisplayList;
13609        final boolean offsetForScroll = cache == null && !hasDisplayList &&
13610                layerType != LAYER_TYPE_HARDWARE;
13611
13612        int restoreTo = -1;
13613        if (!useDisplayListProperties || transformToApply != null) {
13614            restoreTo = canvas.save();
13615        }
13616        if (offsetForScroll) {
13617            canvas.translate(mLeft - sx, mTop - sy);
13618        } else {
13619            if (!useDisplayListProperties) {
13620                canvas.translate(mLeft, mTop);
13621            }
13622            if (scalingRequired) {
13623                if (useDisplayListProperties) {
13624                    // TODO: Might not need this if we put everything inside the DL
13625                    restoreTo = canvas.save();
13626                }
13627                // mAttachInfo cannot be null, otherwise scalingRequired == false
13628                final float scale = 1.0f / mAttachInfo.mApplicationScale;
13629                canvas.scale(scale, scale);
13630            }
13631        }
13632
13633        float alpha = useDisplayListProperties ? 1 : getAlpha();
13634        if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() ||
13635                (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13636            if (transformToApply != null || !childHasIdentityMatrix) {
13637                int transX = 0;
13638                int transY = 0;
13639
13640                if (offsetForScroll) {
13641                    transX = -sx;
13642                    transY = -sy;
13643                }
13644
13645                if (transformToApply != null) {
13646                    if (concatMatrix) {
13647                        if (useDisplayListProperties) {
13648                            displayList.setAnimationMatrix(transformToApply.getMatrix());
13649                        } else {
13650                            // Undo the scroll translation, apply the transformation matrix,
13651                            // then redo the scroll translate to get the correct result.
13652                            canvas.translate(-transX, -transY);
13653                            canvas.concat(transformToApply.getMatrix());
13654                            canvas.translate(transX, transY);
13655                        }
13656                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13657                    }
13658
13659                    float transformAlpha = transformToApply.getAlpha();
13660                    if (transformAlpha < 1) {
13661                        alpha *= transformAlpha;
13662                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13663                    }
13664                }
13665
13666                if (!childHasIdentityMatrix && !useDisplayListProperties) {
13667                    canvas.translate(-transX, -transY);
13668                    canvas.concat(getMatrix());
13669                    canvas.translate(transX, transY);
13670                }
13671            }
13672
13673            // Deal with alpha if it is or used to be <1
13674            if (alpha < 1 ||
13675                    (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) {
13676                if (alpha < 1) {
13677                    mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13678                } else {
13679                    mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA;
13680                }
13681                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
13682                if (hasNoCache) {
13683                    final int multipliedAlpha = (int) (255 * alpha);
13684                    if (!onSetAlpha(multipliedAlpha)) {
13685                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13686                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
13687                                layerType != LAYER_TYPE_NONE) {
13688                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
13689                        }
13690                        if (useDisplayListProperties) {
13691                            displayList.setAlpha(alpha * getAlpha());
13692                        } else  if (layerType == LAYER_TYPE_NONE) {
13693                            final int scrollX = hasDisplayList ? 0 : sx;
13694                            final int scrollY = hasDisplayList ? 0 : sy;
13695                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
13696                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
13697                        }
13698                    } else {
13699                        // Alpha is handled by the child directly, clobber the layer's alpha
13700                        mPrivateFlags |= PFLAG_ALPHA_SET;
13701                    }
13702                }
13703            }
13704        } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13705            onSetAlpha(255);
13706            mPrivateFlags &= ~PFLAG_ALPHA_SET;
13707        }
13708
13709        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
13710                !useDisplayListProperties && layerType == LAYER_TYPE_NONE) {
13711            if (offsetForScroll) {
13712                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
13713            } else {
13714                if (!scalingRequired || cache == null) {
13715                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
13716                } else {
13717                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
13718                }
13719            }
13720        }
13721
13722        if (!useDisplayListProperties && hasDisplayList) {
13723            displayList = getDisplayList();
13724            if (!displayList.isValid()) {
13725                // Uncommon, but possible. If a view is removed from the hierarchy during the call
13726                // to getDisplayList(), the display list will be marked invalid and we should not
13727                // try to use it again.
13728                displayList = null;
13729                hasDisplayList = false;
13730            }
13731        }
13732
13733        if (hasNoCache) {
13734            boolean layerRendered = false;
13735            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
13736                final HardwareLayer layer = getHardwareLayer();
13737                if (layer != null && layer.isValid()) {
13738                    mLayerPaint.setAlpha((int) (alpha * 255));
13739                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
13740                    layerRendered = true;
13741                } else {
13742                    final int scrollX = hasDisplayList ? 0 : sx;
13743                    final int scrollY = hasDisplayList ? 0 : sy;
13744                    canvas.saveLayer(scrollX, scrollY,
13745                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
13746                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
13747                }
13748            }
13749
13750            if (!layerRendered) {
13751                if (!hasDisplayList) {
13752                    // Fast path for layouts with no backgrounds
13753                    if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
13754                        mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13755                        dispatchDraw(canvas);
13756                    } else {
13757                        draw(canvas);
13758                    }
13759                } else {
13760                    mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13761                    ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags);
13762                }
13763            }
13764        } else if (cache != null) {
13765            mPrivateFlags &= ~PFLAG_DIRTY_MASK;
13766            Paint cachePaint;
13767
13768            if (layerType == LAYER_TYPE_NONE) {
13769                cachePaint = parent.mCachePaint;
13770                if (cachePaint == null) {
13771                    cachePaint = new Paint();
13772                    cachePaint.setDither(false);
13773                    parent.mCachePaint = cachePaint;
13774                }
13775                if (alpha < 1) {
13776                    cachePaint.setAlpha((int) (alpha * 255));
13777                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13778                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
13779                    cachePaint.setAlpha(255);
13780                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
13781                }
13782            } else {
13783                cachePaint = mLayerPaint;
13784                cachePaint.setAlpha((int) (alpha * 255));
13785            }
13786            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
13787        }
13788
13789        if (restoreTo >= 0) {
13790            canvas.restoreToCount(restoreTo);
13791        }
13792
13793        if (a != null && !more) {
13794            if (!hardwareAccelerated && !a.getFillAfter()) {
13795                onSetAlpha(255);
13796            }
13797            parent.finishAnimatingView(this, a);
13798        }
13799
13800        if (more && hardwareAccelerated) {
13801            // invalidation is the trigger to recreate display lists, so if we're using
13802            // display lists to render, force an invalidate to allow the animation to
13803            // continue drawing another frame
13804            parent.invalidate(true);
13805            if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) {
13806                // alpha animations should cause the child to recreate its display list
13807                invalidate(true);
13808            }
13809        }
13810
13811        mRecreateDisplayList = false;
13812
13813        return more;
13814    }
13815
13816    /**
13817     * Manually render this view (and all of its children) to the given Canvas.
13818     * The view must have already done a full layout before this function is
13819     * called.  When implementing a view, implement
13820     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
13821     * If you do need to override this method, call the superclass version.
13822     *
13823     * @param canvas The Canvas to which the View is rendered.
13824     */
13825    public void draw(Canvas canvas) {
13826        final int privateFlags = mPrivateFlags;
13827        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
13828                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
13829        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
13830
13831        /*
13832         * Draw traversal performs several drawing steps which must be executed
13833         * in the appropriate order:
13834         *
13835         *      1. Draw the background
13836         *      2. If necessary, save the canvas' layers to prepare for fading
13837         *      3. Draw view's content
13838         *      4. Draw children
13839         *      5. If necessary, draw the fading edges and restore layers
13840         *      6. Draw decorations (scrollbars for instance)
13841         */
13842
13843        // Step 1, draw the background, if needed
13844        int saveCount;
13845
13846        if (!dirtyOpaque) {
13847            final Drawable background = mBackground;
13848            if (background != null) {
13849                final int scrollX = mScrollX;
13850                final int scrollY = mScrollY;
13851
13852                if (mBackgroundSizeChanged) {
13853                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
13854                    mBackgroundSizeChanged = false;
13855                }
13856
13857                if ((scrollX | scrollY) == 0) {
13858                    background.draw(canvas);
13859                } else {
13860                    canvas.translate(scrollX, scrollY);
13861                    background.draw(canvas);
13862                    canvas.translate(-scrollX, -scrollY);
13863                }
13864            }
13865        }
13866
13867        // skip step 2 & 5 if possible (common case)
13868        final int viewFlags = mViewFlags;
13869        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
13870        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
13871        if (!verticalEdges && !horizontalEdges) {
13872            // Step 3, draw the content
13873            if (!dirtyOpaque) onDraw(canvas);
13874
13875            // Step 4, draw the children
13876            dispatchDraw(canvas);
13877
13878            // Step 6, draw decorations (scrollbars)
13879            onDrawScrollBars(canvas);
13880
13881            // we're done...
13882            return;
13883        }
13884
13885        /*
13886         * Here we do the full fledged routine...
13887         * (this is an uncommon case where speed matters less,
13888         * this is why we repeat some of the tests that have been
13889         * done above)
13890         */
13891
13892        boolean drawTop = false;
13893        boolean drawBottom = false;
13894        boolean drawLeft = false;
13895        boolean drawRight = false;
13896
13897        float topFadeStrength = 0.0f;
13898        float bottomFadeStrength = 0.0f;
13899        float leftFadeStrength = 0.0f;
13900        float rightFadeStrength = 0.0f;
13901
13902        // Step 2, save the canvas' layers
13903        int paddingLeft = mPaddingLeft;
13904
13905        final boolean offsetRequired = isPaddingOffsetRequired();
13906        if (offsetRequired) {
13907            paddingLeft += getLeftPaddingOffset();
13908        }
13909
13910        int left = mScrollX + paddingLeft;
13911        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
13912        int top = mScrollY + getFadeTop(offsetRequired);
13913        int bottom = top + getFadeHeight(offsetRequired);
13914
13915        if (offsetRequired) {
13916            right += getRightPaddingOffset();
13917            bottom += getBottomPaddingOffset();
13918        }
13919
13920        final ScrollabilityCache scrollabilityCache = mScrollCache;
13921        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
13922        int length = (int) fadeHeight;
13923
13924        // clip the fade length if top and bottom fades overlap
13925        // overlapping fades produce odd-looking artifacts
13926        if (verticalEdges && (top + length > bottom - length)) {
13927            length = (bottom - top) / 2;
13928        }
13929
13930        // also clip horizontal fades if necessary
13931        if (horizontalEdges && (left + length > right - length)) {
13932            length = (right - left) / 2;
13933        }
13934
13935        if (verticalEdges) {
13936            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
13937            drawTop = topFadeStrength * fadeHeight > 1.0f;
13938            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
13939            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
13940        }
13941
13942        if (horizontalEdges) {
13943            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
13944            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
13945            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
13946            drawRight = rightFadeStrength * fadeHeight > 1.0f;
13947        }
13948
13949        saveCount = canvas.getSaveCount();
13950
13951        int solidColor = getSolidColor();
13952        if (solidColor == 0) {
13953            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
13954
13955            if (drawTop) {
13956                canvas.saveLayer(left, top, right, top + length, null, flags);
13957            }
13958
13959            if (drawBottom) {
13960                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
13961            }
13962
13963            if (drawLeft) {
13964                canvas.saveLayer(left, top, left + length, bottom, null, flags);
13965            }
13966
13967            if (drawRight) {
13968                canvas.saveLayer(right - length, top, right, bottom, null, flags);
13969            }
13970        } else {
13971            scrollabilityCache.setFadeColor(solidColor);
13972        }
13973
13974        // Step 3, draw the content
13975        if (!dirtyOpaque) onDraw(canvas);
13976
13977        // Step 4, draw the children
13978        dispatchDraw(canvas);
13979
13980        // Step 5, draw the fade effect and restore layers
13981        final Paint p = scrollabilityCache.paint;
13982        final Matrix matrix = scrollabilityCache.matrix;
13983        final Shader fade = scrollabilityCache.shader;
13984
13985        if (drawTop) {
13986            matrix.setScale(1, fadeHeight * topFadeStrength);
13987            matrix.postTranslate(left, top);
13988            fade.setLocalMatrix(matrix);
13989            canvas.drawRect(left, top, right, top + length, p);
13990        }
13991
13992        if (drawBottom) {
13993            matrix.setScale(1, fadeHeight * bottomFadeStrength);
13994            matrix.postRotate(180);
13995            matrix.postTranslate(left, bottom);
13996            fade.setLocalMatrix(matrix);
13997            canvas.drawRect(left, bottom - length, right, bottom, p);
13998        }
13999
14000        if (drawLeft) {
14001            matrix.setScale(1, fadeHeight * leftFadeStrength);
14002            matrix.postRotate(-90);
14003            matrix.postTranslate(left, top);
14004            fade.setLocalMatrix(matrix);
14005            canvas.drawRect(left, top, left + length, bottom, p);
14006        }
14007
14008        if (drawRight) {
14009            matrix.setScale(1, fadeHeight * rightFadeStrength);
14010            matrix.postRotate(90);
14011            matrix.postTranslate(right, top);
14012            fade.setLocalMatrix(matrix);
14013            canvas.drawRect(right - length, top, right, bottom, p);
14014        }
14015
14016        canvas.restoreToCount(saveCount);
14017
14018        // Step 6, draw decorations (scrollbars)
14019        onDrawScrollBars(canvas);
14020    }
14021
14022    /**
14023     * Override this if your view is known to always be drawn on top of a solid color background,
14024     * and needs to draw fading edges. Returning a non-zero color enables the view system to
14025     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
14026     * should be set to 0xFF.
14027     *
14028     * @see #setVerticalFadingEdgeEnabled(boolean)
14029     * @see #setHorizontalFadingEdgeEnabled(boolean)
14030     *
14031     * @return The known solid color background for this view, or 0 if the color may vary
14032     */
14033    @ViewDebug.ExportedProperty(category = "drawing")
14034    public int getSolidColor() {
14035        return 0;
14036    }
14037
14038    /**
14039     * Build a human readable string representation of the specified view flags.
14040     *
14041     * @param flags the view flags to convert to a string
14042     * @return a String representing the supplied flags
14043     */
14044    private static String printFlags(int flags) {
14045        String output = "";
14046        int numFlags = 0;
14047        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
14048            output += "TAKES_FOCUS";
14049            numFlags++;
14050        }
14051
14052        switch (flags & VISIBILITY_MASK) {
14053        case INVISIBLE:
14054            if (numFlags > 0) {
14055                output += " ";
14056            }
14057            output += "INVISIBLE";
14058            // USELESS HERE numFlags++;
14059            break;
14060        case GONE:
14061            if (numFlags > 0) {
14062                output += " ";
14063            }
14064            output += "GONE";
14065            // USELESS HERE numFlags++;
14066            break;
14067        default:
14068            break;
14069        }
14070        return output;
14071    }
14072
14073    /**
14074     * Build a human readable string representation of the specified private
14075     * view flags.
14076     *
14077     * @param privateFlags the private view flags to convert to a string
14078     * @return a String representing the supplied flags
14079     */
14080    private static String printPrivateFlags(int privateFlags) {
14081        String output = "";
14082        int numFlags = 0;
14083
14084        if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) {
14085            output += "WANTS_FOCUS";
14086            numFlags++;
14087        }
14088
14089        if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) {
14090            if (numFlags > 0) {
14091                output += " ";
14092            }
14093            output += "FOCUSED";
14094            numFlags++;
14095        }
14096
14097        if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) {
14098            if (numFlags > 0) {
14099                output += " ";
14100            }
14101            output += "SELECTED";
14102            numFlags++;
14103        }
14104
14105        if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) {
14106            if (numFlags > 0) {
14107                output += " ";
14108            }
14109            output += "IS_ROOT_NAMESPACE";
14110            numFlags++;
14111        }
14112
14113        if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) {
14114            if (numFlags > 0) {
14115                output += " ";
14116            }
14117            output += "HAS_BOUNDS";
14118            numFlags++;
14119        }
14120
14121        if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) {
14122            if (numFlags > 0) {
14123                output += " ";
14124            }
14125            output += "DRAWN";
14126            // USELESS HERE numFlags++;
14127        }
14128        return output;
14129    }
14130
14131    /**
14132     * <p>Indicates whether or not this view's layout will be requested during
14133     * the next hierarchy layout pass.</p>
14134     *
14135     * @return true if the layout will be forced during next layout pass
14136     */
14137    public boolean isLayoutRequested() {
14138        return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
14139    }
14140
14141    /**
14142     * Return true if o is a ViewGroup that is laying out using optical bounds.
14143     * @hide
14144     */
14145    public static boolean isLayoutModeOptical(Object o) {
14146        return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical();
14147    }
14148
14149    private boolean setOpticalFrame(int left, int top, int right, int bottom) {
14150        Insets parentInsets = mParent instanceof View ?
14151                ((View) mParent).getOpticalInsets() : Insets.NONE;
14152        Insets childInsets = getOpticalInsets();
14153        return setFrame(
14154                left   + parentInsets.left - childInsets.left,
14155                top    + parentInsets.top  - childInsets.top,
14156                right  + parentInsets.left + childInsets.right,
14157                bottom + parentInsets.top  + childInsets.bottom);
14158    }
14159
14160    /**
14161     * Assign a size and position to a view and all of its
14162     * descendants
14163     *
14164     * <p>This is the second phase of the layout mechanism.
14165     * (The first is measuring). In this phase, each parent calls
14166     * layout on all of its children to position them.
14167     * This is typically done using the child measurements
14168     * that were stored in the measure pass().</p>
14169     *
14170     * <p>Derived classes should not override this method.
14171     * Derived classes with children should override
14172     * onLayout. In that method, they should
14173     * call layout on each of their children.</p>
14174     *
14175     * @param l Left position, relative to parent
14176     * @param t Top position, relative to parent
14177     * @param r Right position, relative to parent
14178     * @param b Bottom position, relative to parent
14179     */
14180    @SuppressWarnings({"unchecked"})
14181    public void layout(int l, int t, int r, int b) {
14182        int oldL = mLeft;
14183        int oldT = mTop;
14184        int oldB = mBottom;
14185        int oldR = mRight;
14186        boolean changed = isLayoutModeOptical(mParent) ?
14187                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
14188        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
14189            onLayout(changed, l, t, r, b);
14190            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;
14191
14192            ListenerInfo li = mListenerInfo;
14193            if (li != null && li.mOnLayoutChangeListeners != null) {
14194                ArrayList<OnLayoutChangeListener> listenersCopy =
14195                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
14196                int numListeners = listenersCopy.size();
14197                for (int i = 0; i < numListeners; ++i) {
14198                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
14199                }
14200            }
14201        }
14202        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
14203    }
14204
14205    /**
14206     * Called from layout when this view should
14207     * assign a size and position to each of its children.
14208     *
14209     * Derived classes with children should override
14210     * this method and call layout on each of
14211     * their children.
14212     * @param changed This is a new size or position for this view
14213     * @param left Left position, relative to parent
14214     * @param top Top position, relative to parent
14215     * @param right Right position, relative to parent
14216     * @param bottom Bottom position, relative to parent
14217     */
14218    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
14219    }
14220
14221    /**
14222     * Assign a size and position to this view.
14223     *
14224     * This is called from layout.
14225     *
14226     * @param left Left position, relative to parent
14227     * @param top Top position, relative to parent
14228     * @param right Right position, relative to parent
14229     * @param bottom Bottom position, relative to parent
14230     * @return true if the new size and position are different than the
14231     *         previous ones
14232     * {@hide}
14233     */
14234    protected boolean setFrame(int left, int top, int right, int bottom) {
14235        boolean changed = false;
14236
14237        if (DBG) {
14238            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
14239                    + right + "," + bottom + ")");
14240        }
14241
14242        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
14243            changed = true;
14244
14245            // Remember our drawn bit
14246            int drawn = mPrivateFlags & PFLAG_DRAWN;
14247
14248            int oldWidth = mRight - mLeft;
14249            int oldHeight = mBottom - mTop;
14250            int newWidth = right - left;
14251            int newHeight = bottom - top;
14252            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
14253
14254            // Invalidate our old position
14255            invalidate(sizeChanged);
14256
14257            mLeft = left;
14258            mTop = top;
14259            mRight = right;
14260            mBottom = bottom;
14261            if (mDisplayList != null) {
14262                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
14263            }
14264
14265            mPrivateFlags |= PFLAG_HAS_BOUNDS;
14266
14267
14268            if (sizeChanged) {
14269                if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) {
14270                    // A change in dimension means an auto-centered pivot point changes, too
14271                    if (mTransformationInfo != null) {
14272                        mTransformationInfo.mMatrixDirty = true;
14273                    }
14274                }
14275                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
14276            }
14277
14278            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
14279                // If we are visible, force the DRAWN bit to on so that
14280                // this invalidate will go through (at least to our parent).
14281                // This is because someone may have invalidated this view
14282                // before this call to setFrame came in, thereby clearing
14283                // the DRAWN bit.
14284                mPrivateFlags |= PFLAG_DRAWN;
14285                invalidate(sizeChanged);
14286                // parent display list may need to be recreated based on a change in the bounds
14287                // of any child
14288                invalidateParentCaches();
14289            }
14290
14291            // Reset drawn bit to original value (invalidate turns it off)
14292            mPrivateFlags |= drawn;
14293
14294            mBackgroundSizeChanged = true;
14295        }
14296        return changed;
14297    }
14298
14299    /**
14300     * Finalize inflating a view from XML.  This is called as the last phase
14301     * of inflation, after all child views have been added.
14302     *
14303     * <p>Even if the subclass overrides onFinishInflate, they should always be
14304     * sure to call the super method, so that we get called.
14305     */
14306    protected void onFinishInflate() {
14307    }
14308
14309    /**
14310     * Returns the resources associated with this view.
14311     *
14312     * @return Resources object.
14313     */
14314    public Resources getResources() {
14315        return mResources;
14316    }
14317
14318    /**
14319     * Invalidates the specified Drawable.
14320     *
14321     * @param drawable the drawable to invalidate
14322     */
14323    public void invalidateDrawable(Drawable drawable) {
14324        if (verifyDrawable(drawable)) {
14325            final Rect dirty = drawable.getBounds();
14326            final int scrollX = mScrollX;
14327            final int scrollY = mScrollY;
14328
14329            invalidate(dirty.left + scrollX, dirty.top + scrollY,
14330                    dirty.right + scrollX, dirty.bottom + scrollY);
14331        }
14332    }
14333
14334    /**
14335     * Schedules an action on a drawable to occur at a specified time.
14336     *
14337     * @param who the recipient of the action
14338     * @param what the action to run on the drawable
14339     * @param when the time at which the action must occur. Uses the
14340     *        {@link SystemClock#uptimeMillis} timebase.
14341     */
14342    public void scheduleDrawable(Drawable who, Runnable what, long when) {
14343        if (verifyDrawable(who) && what != null) {
14344            final long delay = when - SystemClock.uptimeMillis();
14345            if (mAttachInfo != null) {
14346                mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed(
14347                        Choreographer.CALLBACK_ANIMATION, what, who,
14348                        Choreographer.subtractFrameDelay(delay));
14349            } else {
14350                ViewRootImpl.getRunQueue().postDelayed(what, delay);
14351            }
14352        }
14353    }
14354
14355    /**
14356     * Cancels a scheduled action on a drawable.
14357     *
14358     * @param who the recipient of the action
14359     * @param what the action to cancel
14360     */
14361    public void unscheduleDrawable(Drawable who, Runnable what) {
14362        if (verifyDrawable(who) && what != null) {
14363            if (mAttachInfo != null) {
14364                mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14365                        Choreographer.CALLBACK_ANIMATION, what, who);
14366            } else {
14367                ViewRootImpl.getRunQueue().removeCallbacks(what);
14368            }
14369        }
14370    }
14371
14372    /**
14373     * Unschedule any events associated with the given Drawable.  This can be
14374     * used when selecting a new Drawable into a view, so that the previous
14375     * one is completely unscheduled.
14376     *
14377     * @param who The Drawable to unschedule.
14378     *
14379     * @see #drawableStateChanged
14380     */
14381    public void unscheduleDrawable(Drawable who) {
14382        if (mAttachInfo != null && who != null) {
14383            mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
14384                    Choreographer.CALLBACK_ANIMATION, null, who);
14385        }
14386    }
14387
14388    /**
14389     * Resolve the Drawables depending on the layout direction. This is implicitly supposing
14390     * that the View directionality can and will be resolved before its Drawables.
14391     *
14392     * Will call {@link View#onResolveDrawables} when resolution is done.
14393     *
14394     * @hide
14395     */
14396    protected void resolveDrawables() {
14397        if (canResolveLayoutDirection()) {
14398            if (mBackground != null) {
14399                mBackground.setLayoutDirection(getLayoutDirection());
14400            }
14401            mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED;
14402            onResolveDrawables(getLayoutDirection());
14403        }
14404    }
14405
14406    /**
14407     * Called when layout direction has been resolved.
14408     *
14409     * The default implementation does nothing.
14410     *
14411     * @param layoutDirection The resolved layout direction.
14412     *
14413     * @see #LAYOUT_DIRECTION_LTR
14414     * @see #LAYOUT_DIRECTION_RTL
14415     *
14416     * @hide
14417     */
14418    public void onResolveDrawables(int layoutDirection) {
14419    }
14420
14421    /**
14422     * @hide
14423     */
14424    protected void resetResolvedDrawables() {
14425        mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED;
14426    }
14427
14428    private boolean isDrawablesResolved() {
14429        return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED;
14430    }
14431
14432    /**
14433     * If your view subclass is displaying its own Drawable objects, it should
14434     * override this function and return true for any Drawable it is
14435     * displaying.  This allows animations for those drawables to be
14436     * scheduled.
14437     *
14438     * <p>Be sure to call through to the super class when overriding this
14439     * function.
14440     *
14441     * @param who The Drawable to verify.  Return true if it is one you are
14442     *            displaying, else return the result of calling through to the
14443     *            super class.
14444     *
14445     * @return boolean If true than the Drawable is being displayed in the
14446     *         view; else false and it is not allowed to animate.
14447     *
14448     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
14449     * @see #drawableStateChanged()
14450     */
14451    protected boolean verifyDrawable(Drawable who) {
14452        return who == mBackground;
14453    }
14454
14455    /**
14456     * This function is called whenever the state of the view changes in such
14457     * a way that it impacts the state of drawables being shown.
14458     *
14459     * <p>Be sure to call through to the superclass when overriding this
14460     * function.
14461     *
14462     * @see Drawable#setState(int[])
14463     */
14464    protected void drawableStateChanged() {
14465        Drawable d = mBackground;
14466        if (d != null && d.isStateful()) {
14467            d.setState(getDrawableState());
14468        }
14469    }
14470
14471    /**
14472     * Call this to force a view to update its drawable state. This will cause
14473     * drawableStateChanged to be called on this view. Views that are interested
14474     * in the new state should call getDrawableState.
14475     *
14476     * @see #drawableStateChanged
14477     * @see #getDrawableState
14478     */
14479    public void refreshDrawableState() {
14480        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
14481        drawableStateChanged();
14482
14483        ViewParent parent = mParent;
14484        if (parent != null) {
14485            parent.childDrawableStateChanged(this);
14486        }
14487    }
14488
14489    /**
14490     * Return an array of resource IDs of the drawable states representing the
14491     * current state of the view.
14492     *
14493     * @return The current drawable state
14494     *
14495     * @see Drawable#setState(int[])
14496     * @see #drawableStateChanged()
14497     * @see #onCreateDrawableState(int)
14498     */
14499    public final int[] getDrawableState() {
14500        if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) {
14501            return mDrawableState;
14502        } else {
14503            mDrawableState = onCreateDrawableState(0);
14504            mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY;
14505            return mDrawableState;
14506        }
14507    }
14508
14509    /**
14510     * Generate the new {@link android.graphics.drawable.Drawable} state for
14511     * this view. This is called by the view
14512     * system when the cached Drawable state is determined to be invalid.  To
14513     * retrieve the current state, you should use {@link #getDrawableState}.
14514     *
14515     * @param extraSpace if non-zero, this is the number of extra entries you
14516     * would like in the returned array in which you can place your own
14517     * states.
14518     *
14519     * @return Returns an array holding the current {@link Drawable} state of
14520     * the view.
14521     *
14522     * @see #mergeDrawableStates(int[], int[])
14523     */
14524    protected int[] onCreateDrawableState(int extraSpace) {
14525        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
14526                mParent instanceof View) {
14527            return ((View) mParent).onCreateDrawableState(extraSpace);
14528        }
14529
14530        int[] drawableState;
14531
14532        int privateFlags = mPrivateFlags;
14533
14534        int viewStateIndex = 0;
14535        if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
14536        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
14537        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
14538        if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
14539        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
14540        if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
14541        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
14542                HardwareRenderer.isAvailable()) {
14543            // This is set if HW acceleration is requested, even if the current
14544            // process doesn't allow it.  This is just to allow app preview
14545            // windows to better match their app.
14546            viewStateIndex |= VIEW_STATE_ACCELERATED;
14547        }
14548        if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
14549
14550        final int privateFlags2 = mPrivateFlags2;
14551        if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
14552        if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
14553
14554        drawableState = VIEW_STATE_SETS[viewStateIndex];
14555
14556        //noinspection ConstantIfStatement
14557        if (false) {
14558            Log.i("View", "drawableStateIndex=" + viewStateIndex);
14559            Log.i("View", toString()
14560                    + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0)
14561                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
14562                    + " fo=" + hasFocus()
14563                    + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0)
14564                    + " wf=" + hasWindowFocus()
14565                    + ": " + Arrays.toString(drawableState));
14566        }
14567
14568        if (extraSpace == 0) {
14569            return drawableState;
14570        }
14571
14572        final int[] fullState;
14573        if (drawableState != null) {
14574            fullState = new int[drawableState.length + extraSpace];
14575            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
14576        } else {
14577            fullState = new int[extraSpace];
14578        }
14579
14580        return fullState;
14581    }
14582
14583    /**
14584     * Merge your own state values in <var>additionalState</var> into the base
14585     * state values <var>baseState</var> that were returned by
14586     * {@link #onCreateDrawableState(int)}.
14587     *
14588     * @param baseState The base state values returned by
14589     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
14590     * own additional state values.
14591     *
14592     * @param additionalState The additional state values you would like
14593     * added to <var>baseState</var>; this array is not modified.
14594     *
14595     * @return As a convenience, the <var>baseState</var> array you originally
14596     * passed into the function is returned.
14597     *
14598     * @see #onCreateDrawableState(int)
14599     */
14600    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
14601        final int N = baseState.length;
14602        int i = N - 1;
14603        while (i >= 0 && baseState[i] == 0) {
14604            i--;
14605        }
14606        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
14607        return baseState;
14608    }
14609
14610    /**
14611     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
14612     * on all Drawable objects associated with this view.
14613     */
14614    public void jumpDrawablesToCurrentState() {
14615        if (mBackground != null) {
14616            mBackground.jumpToCurrentState();
14617        }
14618    }
14619
14620    /**
14621     * Sets the background color for this view.
14622     * @param color the color of the background
14623     */
14624    @RemotableViewMethod
14625    public void setBackgroundColor(int color) {
14626        if (mBackground instanceof ColorDrawable) {
14627            ((ColorDrawable) mBackground.mutate()).setColor(color);
14628            computeOpaqueFlags();
14629            mBackgroundResource = 0;
14630        } else {
14631            setBackground(new ColorDrawable(color));
14632        }
14633    }
14634
14635    /**
14636     * Set the background to a given resource. The resource should refer to
14637     * a Drawable object or 0 to remove the background.
14638     * @param resid The identifier of the resource.
14639     *
14640     * @attr ref android.R.styleable#View_background
14641     */
14642    @RemotableViewMethod
14643    public void setBackgroundResource(int resid) {
14644        if (resid != 0 && resid == mBackgroundResource) {
14645            return;
14646        }
14647
14648        Drawable d= null;
14649        if (resid != 0) {
14650            d = mResources.getDrawable(resid);
14651        }
14652        setBackground(d);
14653
14654        mBackgroundResource = resid;
14655    }
14656
14657    /**
14658     * Set the background to a given Drawable, or remove the background. If the
14659     * background has padding, this View's padding is set to the background's
14660     * padding. However, when a background is removed, this View's padding isn't
14661     * touched. If setting the padding is desired, please use
14662     * {@link #setPadding(int, int, int, int)}.
14663     *
14664     * @param background The Drawable to use as the background, or null to remove the
14665     *        background
14666     */
14667    public void setBackground(Drawable background) {
14668        //noinspection deprecation
14669        setBackgroundDrawable(background);
14670    }
14671
14672    /**
14673     * @deprecated use {@link #setBackground(Drawable)} instead
14674     */
14675    @Deprecated
14676    public void setBackgroundDrawable(Drawable background) {
14677        computeOpaqueFlags();
14678
14679        if (background == mBackground) {
14680            return;
14681        }
14682
14683        boolean requestLayout = false;
14684
14685        mBackgroundResource = 0;
14686
14687        /*
14688         * Regardless of whether we're setting a new background or not, we want
14689         * to clear the previous drawable.
14690         */
14691        if (mBackground != null) {
14692            mBackground.setCallback(null);
14693            unscheduleDrawable(mBackground);
14694        }
14695
14696        if (background != null) {
14697            Rect padding = sThreadLocal.get();
14698            if (padding == null) {
14699                padding = new Rect();
14700                sThreadLocal.set(padding);
14701            }
14702            resetResolvedDrawables();
14703            background.setLayoutDirection(getLayoutDirection());
14704            if (background.getPadding(padding)) {
14705                resetResolvedPadding();
14706                switch (background.getLayoutDirection()) {
14707                    case LAYOUT_DIRECTION_RTL:
14708                        mUserPaddingLeftInitial = padding.right;
14709                        mUserPaddingRightInitial = padding.left;
14710                        internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);
14711                        break;
14712                    case LAYOUT_DIRECTION_LTR:
14713                    default:
14714                        mUserPaddingLeftInitial = padding.left;
14715                        mUserPaddingRightInitial = padding.right;
14716                        internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);
14717                }
14718            }
14719
14720            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
14721            // if it has a different minimum size, we should layout again
14722            if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() ||
14723                    mBackground.getMinimumWidth() != background.getMinimumWidth()) {
14724                requestLayout = true;
14725            }
14726
14727            background.setCallback(this);
14728            if (background.isStateful()) {
14729                background.setState(getDrawableState());
14730            }
14731            background.setVisible(getVisibility() == VISIBLE, false);
14732            mBackground = background;
14733
14734            if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {
14735                mPrivateFlags &= ~PFLAG_SKIP_DRAW;
14736                mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND;
14737                requestLayout = true;
14738            }
14739        } else {
14740            /* Remove the background */
14741            mBackground = null;
14742
14743            if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) {
14744                /*
14745                 * This view ONLY drew the background before and we're removing
14746                 * the background, so now it won't draw anything
14747                 * (hence we SKIP_DRAW)
14748                 */
14749                mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND;
14750                mPrivateFlags |= PFLAG_SKIP_DRAW;
14751            }
14752
14753            /*
14754             * When the background is set, we try to apply its padding to this
14755             * View. When the background is removed, we don't touch this View's
14756             * padding. This is noted in the Javadocs. Hence, we don't need to
14757             * requestLayout(), the invalidate() below is sufficient.
14758             */
14759
14760            // The old background's minimum size could have affected this
14761            // View's layout, so let's requestLayout
14762            requestLayout = true;
14763        }
14764
14765        computeOpaqueFlags();
14766
14767        if (requestLayout) {
14768            requestLayout();
14769        }
14770
14771        mBackgroundSizeChanged = true;
14772        invalidate(true);
14773    }
14774
14775    /**
14776     * Gets the background drawable
14777     *
14778     * @return The drawable used as the background for this view, if any.
14779     *
14780     * @see #setBackground(Drawable)
14781     *
14782     * @attr ref android.R.styleable#View_background
14783     */
14784    public Drawable getBackground() {
14785        return mBackground;
14786    }
14787
14788    /**
14789     * Sets the padding. The view may add on the space required to display
14790     * the scrollbars, depending on the style and visibility of the scrollbars.
14791     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
14792     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
14793     * from the values set in this call.
14794     *
14795     * @attr ref android.R.styleable#View_padding
14796     * @attr ref android.R.styleable#View_paddingBottom
14797     * @attr ref android.R.styleable#View_paddingLeft
14798     * @attr ref android.R.styleable#View_paddingRight
14799     * @attr ref android.R.styleable#View_paddingTop
14800     * @param left the left padding in pixels
14801     * @param top the top padding in pixels
14802     * @param right the right padding in pixels
14803     * @param bottom the bottom padding in pixels
14804     */
14805    public void setPadding(int left, int top, int right, int bottom) {
14806        resetResolvedPadding();
14807
14808        mUserPaddingStart = UNDEFINED_PADDING;
14809        mUserPaddingEnd = UNDEFINED_PADDING;
14810
14811        mUserPaddingLeftInitial = left;
14812        mUserPaddingRightInitial = right;
14813
14814        internalSetPadding(left, top, right, bottom);
14815    }
14816
14817    /**
14818     * @hide
14819     */
14820    protected void internalSetPadding(int left, int top, int right, int bottom) {
14821        mUserPaddingLeft = left;
14822        mUserPaddingRight = right;
14823        mUserPaddingBottom = bottom;
14824
14825        final int viewFlags = mViewFlags;
14826        boolean changed = false;
14827
14828        // Common case is there are no scroll bars.
14829        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
14830            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
14831                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
14832                        ? 0 : getVerticalScrollbarWidth();
14833                switch (mVerticalScrollbarPosition) {
14834                    case SCROLLBAR_POSITION_DEFAULT:
14835                        if (isLayoutRtl()) {
14836                            left += offset;
14837                        } else {
14838                            right += offset;
14839                        }
14840                        break;
14841                    case SCROLLBAR_POSITION_RIGHT:
14842                        right += offset;
14843                        break;
14844                    case SCROLLBAR_POSITION_LEFT:
14845                        left += offset;
14846                        break;
14847                }
14848            }
14849            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
14850                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
14851                        ? 0 : getHorizontalScrollbarHeight();
14852            }
14853        }
14854
14855        if (mPaddingLeft != left) {
14856            changed = true;
14857            mPaddingLeft = left;
14858        }
14859        if (mPaddingTop != top) {
14860            changed = true;
14861            mPaddingTop = top;
14862        }
14863        if (mPaddingRight != right) {
14864            changed = true;
14865            mPaddingRight = right;
14866        }
14867        if (mPaddingBottom != bottom) {
14868            changed = true;
14869            mPaddingBottom = bottom;
14870        }
14871
14872        if (changed) {
14873            requestLayout();
14874        }
14875    }
14876
14877    /**
14878     * Sets the relative padding. The view may add on the space required to display
14879     * the scrollbars, depending on the style and visibility of the scrollbars.
14880     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
14881     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
14882     * from the values set in this call.
14883     *
14884     * @attr ref android.R.styleable#View_padding
14885     * @attr ref android.R.styleable#View_paddingBottom
14886     * @attr ref android.R.styleable#View_paddingStart
14887     * @attr ref android.R.styleable#View_paddingEnd
14888     * @attr ref android.R.styleable#View_paddingTop
14889     * @param start the start padding in pixels
14890     * @param top the top padding in pixels
14891     * @param end the end padding in pixels
14892     * @param bottom the bottom padding in pixels
14893     */
14894    public void setPaddingRelative(int start, int top, int end, int bottom) {
14895        resetResolvedPadding();
14896
14897        mUserPaddingStart = start;
14898        mUserPaddingEnd = end;
14899
14900        switch(getLayoutDirection()) {
14901            case LAYOUT_DIRECTION_RTL:
14902                mUserPaddingLeftInitial = end;
14903                mUserPaddingRightInitial = start;
14904                internalSetPadding(end, top, start, bottom);
14905                break;
14906            case LAYOUT_DIRECTION_LTR:
14907            default:
14908                mUserPaddingLeftInitial = start;
14909                mUserPaddingRightInitial = end;
14910                internalSetPadding(start, top, end, bottom);
14911        }
14912    }
14913
14914    /**
14915     * Returns the top padding of this view.
14916     *
14917     * @return the top padding in pixels
14918     */
14919    public int getPaddingTop() {
14920        return mPaddingTop;
14921    }
14922
14923    /**
14924     * Returns the bottom padding of this view. If there are inset and enabled
14925     * scrollbars, this value may include the space required to display the
14926     * scrollbars as well.
14927     *
14928     * @return the bottom padding in pixels
14929     */
14930    public int getPaddingBottom() {
14931        return mPaddingBottom;
14932    }
14933
14934    /**
14935     * Returns the left padding of this view. If there are inset and enabled
14936     * scrollbars, this value may include the space required to display the
14937     * scrollbars as well.
14938     *
14939     * @return the left padding in pixels
14940     */
14941    public int getPaddingLeft() {
14942        if (!isPaddingResolved()) {
14943            resolvePadding();
14944        }
14945        return mPaddingLeft;
14946    }
14947
14948    /**
14949     * Returns the start padding of this view depending on its resolved layout direction.
14950     * If there are inset and enabled scrollbars, this value may include the space
14951     * required to display the scrollbars as well.
14952     *
14953     * @return the start padding in pixels
14954     */
14955    public int getPaddingStart() {
14956        if (!isPaddingResolved()) {
14957            resolvePadding();
14958        }
14959        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14960                mPaddingRight : mPaddingLeft;
14961    }
14962
14963    /**
14964     * Returns the right padding of this view. If there are inset and enabled
14965     * scrollbars, this value may include the space required to display the
14966     * scrollbars as well.
14967     *
14968     * @return the right padding in pixels
14969     */
14970    public int getPaddingRight() {
14971        if (!isPaddingResolved()) {
14972            resolvePadding();
14973        }
14974        return mPaddingRight;
14975    }
14976
14977    /**
14978     * Returns the end padding of this view depending on its resolved layout direction.
14979     * If there are inset and enabled scrollbars, this value may include the space
14980     * required to display the scrollbars as well.
14981     *
14982     * @return the end padding in pixels
14983     */
14984    public int getPaddingEnd() {
14985        if (!isPaddingResolved()) {
14986            resolvePadding();
14987        }
14988        return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
14989                mPaddingLeft : mPaddingRight;
14990    }
14991
14992    /**
14993     * Return if the padding as been set thru relative values
14994     * {@link #setPaddingRelative(int, int, int, int)} or thru
14995     * @attr ref android.R.styleable#View_paddingStart or
14996     * @attr ref android.R.styleable#View_paddingEnd
14997     *
14998     * @return true if the padding is relative or false if it is not.
14999     */
15000    public boolean isPaddingRelative() {
15001        return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING);
15002    }
15003
15004    Insets computeOpticalInsets() {
15005        return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets();
15006    }
15007
15008    /**
15009     * @hide
15010     */
15011    public void resetPaddingToInitialValues() {
15012        if (isRtlCompatibilityMode()) {
15013            mPaddingLeft = mUserPaddingLeftInitial;
15014            mPaddingRight = mUserPaddingRightInitial;
15015            return;
15016        }
15017        if (isLayoutRtl()) {
15018            mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial;
15019            mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial;
15020        } else {
15021            mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial;
15022            mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial;
15023        }
15024    }
15025
15026    /**
15027     * @hide
15028     */
15029    public Insets getOpticalInsets() {
15030        if (mLayoutInsets == null) {
15031            mLayoutInsets = computeOpticalInsets();
15032        }
15033        return mLayoutInsets;
15034    }
15035
15036    /**
15037     * Changes the selection state of this view. A view can be selected or not.
15038     * Note that selection is not the same as focus. Views are typically
15039     * selected in the context of an AdapterView like ListView or GridView;
15040     * the selected view is the view that is highlighted.
15041     *
15042     * @param selected true if the view must be selected, false otherwise
15043     */
15044    public void setSelected(boolean selected) {
15045        if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) {
15046            mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0);
15047            if (!selected) resetPressedState();
15048            invalidate(true);
15049            refreshDrawableState();
15050            dispatchSetSelected(selected);
15051            if (AccessibilityManager.getInstance(mContext).isEnabled()) {
15052                notifyAccessibilityStateChanged();
15053            }
15054        }
15055    }
15056
15057    /**
15058     * Dispatch setSelected to all of this View's children.
15059     *
15060     * @see #setSelected(boolean)
15061     *
15062     * @param selected The new selected state
15063     */
15064    protected void dispatchSetSelected(boolean selected) {
15065    }
15066
15067    /**
15068     * Indicates the selection state of this view.
15069     *
15070     * @return true if the view is selected, false otherwise
15071     */
15072    @ViewDebug.ExportedProperty
15073    public boolean isSelected() {
15074        return (mPrivateFlags & PFLAG_SELECTED) != 0;
15075    }
15076
15077    /**
15078     * Changes the activated state of this view. A view can be activated or not.
15079     * Note that activation is not the same as selection.  Selection is
15080     * a transient property, representing the view (hierarchy) the user is
15081     * currently interacting with.  Activation is a longer-term state that the
15082     * user can move views in and out of.  For example, in a list view with
15083     * single or multiple selection enabled, the views in the current selection
15084     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
15085     * here.)  The activated state is propagated down to children of the view it
15086     * is set on.
15087     *
15088     * @param activated true if the view must be activated, false otherwise
15089     */
15090    public void setActivated(boolean activated) {
15091        if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) {
15092            mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0);
15093            invalidate(true);
15094            refreshDrawableState();
15095            dispatchSetActivated(activated);
15096        }
15097    }
15098
15099    /**
15100     * Dispatch setActivated to all of this View's children.
15101     *
15102     * @see #setActivated(boolean)
15103     *
15104     * @param activated The new activated state
15105     */
15106    protected void dispatchSetActivated(boolean activated) {
15107    }
15108
15109    /**
15110     * Indicates the activation state of this view.
15111     *
15112     * @return true if the view is activated, false otherwise
15113     */
15114    @ViewDebug.ExportedProperty
15115    public boolean isActivated() {
15116        return (mPrivateFlags & PFLAG_ACTIVATED) != 0;
15117    }
15118
15119    /**
15120     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
15121     * observer can be used to get notifications when global events, like
15122     * layout, happen.
15123     *
15124     * The returned ViewTreeObserver observer is not guaranteed to remain
15125     * valid for the lifetime of this View. If the caller of this method keeps
15126     * a long-lived reference to ViewTreeObserver, it should always check for
15127     * the return value of {@link ViewTreeObserver#isAlive()}.
15128     *
15129     * @return The ViewTreeObserver for this view's hierarchy.
15130     */
15131    public ViewTreeObserver getViewTreeObserver() {
15132        if (mAttachInfo != null) {
15133            return mAttachInfo.mTreeObserver;
15134        }
15135        if (mFloatingTreeObserver == null) {
15136            mFloatingTreeObserver = new ViewTreeObserver();
15137        }
15138        return mFloatingTreeObserver;
15139    }
15140
15141    /**
15142     * <p>Finds the topmost view in the current view hierarchy.</p>
15143     *
15144     * @return the topmost view containing this view
15145     */
15146    public View getRootView() {
15147        if (mAttachInfo != null) {
15148            final View v = mAttachInfo.mRootView;
15149            if (v != null) {
15150                return v;
15151            }
15152        }
15153
15154        View parent = this;
15155
15156        while (parent.mParent != null && parent.mParent instanceof View) {
15157            parent = (View) parent.mParent;
15158        }
15159
15160        return parent;
15161    }
15162
15163    /**
15164     * <p>Computes the coordinates of this view on the screen. The argument
15165     * must be an array of two integers. After the method returns, the array
15166     * contains the x and y location in that order.</p>
15167     *
15168     * @param location an array of two integers in which to hold the coordinates
15169     */
15170    public void getLocationOnScreen(int[] location) {
15171        getLocationInWindow(location);
15172
15173        final AttachInfo info = mAttachInfo;
15174        if (info != null) {
15175            location[0] += info.mWindowLeft;
15176            location[1] += info.mWindowTop;
15177        }
15178    }
15179
15180    /**
15181     * <p>Computes the coordinates of this view in its window. The argument
15182     * must be an array of two integers. After the method returns, the array
15183     * contains the x and y location in that order.</p>
15184     *
15185     * @param location an array of two integers in which to hold the coordinates
15186     */
15187    public void getLocationInWindow(int[] location) {
15188        if (location == null || location.length < 2) {
15189            throw new IllegalArgumentException("location must be an array of two integers");
15190        }
15191
15192        if (mAttachInfo == null) {
15193            // When the view is not attached to a window, this method does not make sense
15194            location[0] = location[1] = 0;
15195            return;
15196        }
15197
15198        float[] position = mAttachInfo.mTmpTransformLocation;
15199        position[0] = position[1] = 0.0f;
15200
15201        if (!hasIdentityMatrix()) {
15202            getMatrix().mapPoints(position);
15203        }
15204
15205        position[0] += mLeft;
15206        position[1] += mTop;
15207
15208        ViewParent viewParent = mParent;
15209        while (viewParent instanceof View) {
15210            final View view = (View) viewParent;
15211
15212            position[0] -= view.mScrollX;
15213            position[1] -= view.mScrollY;
15214
15215            if (!view.hasIdentityMatrix()) {
15216                view.getMatrix().mapPoints(position);
15217            }
15218
15219            position[0] += view.mLeft;
15220            position[1] += view.mTop;
15221
15222            viewParent = view.mParent;
15223         }
15224
15225        if (viewParent instanceof ViewRootImpl) {
15226            // *cough*
15227            final ViewRootImpl vr = (ViewRootImpl) viewParent;
15228            position[1] -= vr.mCurScrollY;
15229        }
15230
15231        location[0] = (int) (position[0] + 0.5f);
15232        location[1] = (int) (position[1] + 0.5f);
15233    }
15234
15235    /**
15236     * {@hide}
15237     * @param id the id of the view to be found
15238     * @return the view of the specified id, null if cannot be found
15239     */
15240    protected View findViewTraversal(int id) {
15241        if (id == mID) {
15242            return this;
15243        }
15244        return null;
15245    }
15246
15247    /**
15248     * {@hide}
15249     * @param tag the tag of the view to be found
15250     * @return the view of specified tag, null if cannot be found
15251     */
15252    protected View findViewWithTagTraversal(Object tag) {
15253        if (tag != null && tag.equals(mTag)) {
15254            return this;
15255        }
15256        return null;
15257    }
15258
15259    /**
15260     * {@hide}
15261     * @param predicate The predicate to evaluate.
15262     * @param childToSkip If not null, ignores this child during the recursive traversal.
15263     * @return The first view that matches the predicate or null.
15264     */
15265    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
15266        if (predicate.apply(this)) {
15267            return this;
15268        }
15269        return null;
15270    }
15271
15272    /**
15273     * Look for a child view with the given id.  If this view has the given
15274     * id, return this view.
15275     *
15276     * @param id The id to search for.
15277     * @return The view that has the given id in the hierarchy or null
15278     */
15279    public final View findViewById(int id) {
15280        if (id < 0) {
15281            return null;
15282        }
15283        return findViewTraversal(id);
15284    }
15285
15286    /**
15287     * Finds a view by its unuque and stable accessibility id.
15288     *
15289     * @param accessibilityId The searched accessibility id.
15290     * @return The found view.
15291     */
15292    final View findViewByAccessibilityId(int accessibilityId) {
15293        if (accessibilityId < 0) {
15294            return null;
15295        }
15296        return findViewByAccessibilityIdTraversal(accessibilityId);
15297    }
15298
15299    /**
15300     * Performs the traversal to find a view by its unuque and stable accessibility id.
15301     *
15302     * <strong>Note:</strong>This method does not stop at the root namespace
15303     * boundary since the user can touch the screen at an arbitrary location
15304     * potentially crossing the root namespace bounday which will send an
15305     * accessibility event to accessibility services and they should be able
15306     * to obtain the event source. Also accessibility ids are guaranteed to be
15307     * unique in the window.
15308     *
15309     * @param accessibilityId The accessibility id.
15310     * @return The found view.
15311     */
15312    View findViewByAccessibilityIdTraversal(int accessibilityId) {
15313        if (getAccessibilityViewId() == accessibilityId) {
15314            return this;
15315        }
15316        return null;
15317    }
15318
15319    /**
15320     * Look for a child view with the given tag.  If this view has the given
15321     * tag, return this view.
15322     *
15323     * @param tag The tag to search for, using "tag.equals(getTag())".
15324     * @return The View that has the given tag in the hierarchy or null
15325     */
15326    public final View findViewWithTag(Object tag) {
15327        if (tag == null) {
15328            return null;
15329        }
15330        return findViewWithTagTraversal(tag);
15331    }
15332
15333    /**
15334     * {@hide}
15335     * Look for a child view that matches the specified predicate.
15336     * If this view matches the predicate, return this view.
15337     *
15338     * @param predicate The predicate to evaluate.
15339     * @return The first view that matches the predicate or null.
15340     */
15341    public final View findViewByPredicate(Predicate<View> predicate) {
15342        return findViewByPredicateTraversal(predicate, null);
15343    }
15344
15345    /**
15346     * {@hide}
15347     * Look for a child view that matches the specified predicate,
15348     * starting with the specified view and its descendents and then
15349     * recusively searching the ancestors and siblings of that view
15350     * until this view is reached.
15351     *
15352     * This method is useful in cases where the predicate does not match
15353     * a single unique view (perhaps multiple views use the same id)
15354     * and we are trying to find the view that is "closest" in scope to the
15355     * starting view.
15356     *
15357     * @param start The view to start from.
15358     * @param predicate The predicate to evaluate.
15359     * @return The first view that matches the predicate or null.
15360     */
15361    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
15362        View childToSkip = null;
15363        for (;;) {
15364            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
15365            if (view != null || start == this) {
15366                return view;
15367            }
15368
15369            ViewParent parent = start.getParent();
15370            if (parent == null || !(parent instanceof View)) {
15371                return null;
15372            }
15373
15374            childToSkip = start;
15375            start = (View) parent;
15376        }
15377    }
15378
15379    /**
15380     * Sets the identifier for this view. The identifier does not have to be
15381     * unique in this view's hierarchy. The identifier should be a positive
15382     * number.
15383     *
15384     * @see #NO_ID
15385     * @see #getId()
15386     * @see #findViewById(int)
15387     *
15388     * @param id a number used to identify the view
15389     *
15390     * @attr ref android.R.styleable#View_id
15391     */
15392    public void setId(int id) {
15393        mID = id;
15394        if (mID == View.NO_ID && mLabelForId != View.NO_ID) {
15395            mID = generateViewId();
15396        }
15397    }
15398
15399    /**
15400     * {@hide}
15401     *
15402     * @param isRoot true if the view belongs to the root namespace, false
15403     *        otherwise
15404     */
15405    public void setIsRootNamespace(boolean isRoot) {
15406        if (isRoot) {
15407            mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE;
15408        } else {
15409            mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE;
15410        }
15411    }
15412
15413    /**
15414     * {@hide}
15415     *
15416     * @return true if the view belongs to the root namespace, false otherwise
15417     */
15418    public boolean isRootNamespace() {
15419        return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0;
15420    }
15421
15422    /**
15423     * Returns this view's identifier.
15424     *
15425     * @return a positive integer used to identify the view or {@link #NO_ID}
15426     *         if the view has no ID
15427     *
15428     * @see #setId(int)
15429     * @see #findViewById(int)
15430     * @attr ref android.R.styleable#View_id
15431     */
15432    @ViewDebug.CapturedViewProperty
15433    public int getId() {
15434        return mID;
15435    }
15436
15437    /**
15438     * Returns this view's tag.
15439     *
15440     * @return the Object stored in this view as a tag
15441     *
15442     * @see #setTag(Object)
15443     * @see #getTag(int)
15444     */
15445    @ViewDebug.ExportedProperty
15446    public Object getTag() {
15447        return mTag;
15448    }
15449
15450    /**
15451     * Sets the tag associated with this view. A tag can be used to mark
15452     * a view in its hierarchy and does not have to be unique within the
15453     * hierarchy. Tags can also be used to store data within a view without
15454     * resorting to another data structure.
15455     *
15456     * @param tag an Object to tag the view with
15457     *
15458     * @see #getTag()
15459     * @see #setTag(int, Object)
15460     */
15461    public void setTag(final Object tag) {
15462        mTag = tag;
15463    }
15464
15465    /**
15466     * Returns the tag associated with this view and the specified key.
15467     *
15468     * @param key The key identifying the tag
15469     *
15470     * @return the Object stored in this view as a tag
15471     *
15472     * @see #setTag(int, Object)
15473     * @see #getTag()
15474     */
15475    public Object getTag(int key) {
15476        if (mKeyedTags != null) return mKeyedTags.get(key);
15477        return null;
15478    }
15479
15480    /**
15481     * Sets a tag associated with this view and a key. A tag can be used
15482     * to mark a view in its hierarchy and does not have to be unique within
15483     * the hierarchy. Tags can also be used to store data within a view
15484     * without resorting to another data structure.
15485     *
15486     * The specified key should be an id declared in the resources of the
15487     * application to ensure it is unique (see the <a
15488     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
15489     * Keys identified as belonging to
15490     * the Android framework or not associated with any package will cause
15491     * an {@link IllegalArgumentException} to be thrown.
15492     *
15493     * @param key The key identifying the tag
15494     * @param tag An Object to tag the view with
15495     *
15496     * @throws IllegalArgumentException If they specified key is not valid
15497     *
15498     * @see #setTag(Object)
15499     * @see #getTag(int)
15500     */
15501    public void setTag(int key, final Object tag) {
15502        // If the package id is 0x00 or 0x01, it's either an undefined package
15503        // or a framework id
15504        if ((key >>> 24) < 2) {
15505            throw new IllegalArgumentException("The key must be an application-specific "
15506                    + "resource id.");
15507        }
15508
15509        setKeyedTag(key, tag);
15510    }
15511
15512    /**
15513     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
15514     * framework id.
15515     *
15516     * @hide
15517     */
15518    public void setTagInternal(int key, Object tag) {
15519        if ((key >>> 24) != 0x1) {
15520            throw new IllegalArgumentException("The key must be a framework-specific "
15521                    + "resource id.");
15522        }
15523
15524        setKeyedTag(key, tag);
15525    }
15526
15527    private void setKeyedTag(int key, Object tag) {
15528        if (mKeyedTags == null) {
15529            mKeyedTags = new SparseArray<Object>();
15530        }
15531
15532        mKeyedTags.put(key, tag);
15533    }
15534
15535    /**
15536     * Prints information about this view in the log output, with the tag
15537     * {@link #VIEW_LOG_TAG}.
15538     *
15539     * @hide
15540     */
15541    public void debug() {
15542        debug(0);
15543    }
15544
15545    /**
15546     * Prints information about this view in the log output, with the tag
15547     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
15548     * indentation defined by the <code>depth</code>.
15549     *
15550     * @param depth the indentation level
15551     *
15552     * @hide
15553     */
15554    protected void debug(int depth) {
15555        String output = debugIndent(depth - 1);
15556
15557        output += "+ " + this;
15558        int id = getId();
15559        if (id != -1) {
15560            output += " (id=" + id + ")";
15561        }
15562        Object tag = getTag();
15563        if (tag != null) {
15564            output += " (tag=" + tag + ")";
15565        }
15566        Log.d(VIEW_LOG_TAG, output);
15567
15568        if ((mPrivateFlags & PFLAG_FOCUSED) != 0) {
15569            output = debugIndent(depth) + " FOCUSED";
15570            Log.d(VIEW_LOG_TAG, output);
15571        }
15572
15573        output = debugIndent(depth);
15574        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
15575                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
15576                + "} ";
15577        Log.d(VIEW_LOG_TAG, output);
15578
15579        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
15580                || mPaddingBottom != 0) {
15581            output = debugIndent(depth);
15582            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
15583                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
15584            Log.d(VIEW_LOG_TAG, output);
15585        }
15586
15587        output = debugIndent(depth);
15588        output += "mMeasureWidth=" + mMeasuredWidth +
15589                " mMeasureHeight=" + mMeasuredHeight;
15590        Log.d(VIEW_LOG_TAG, output);
15591
15592        output = debugIndent(depth);
15593        if (mLayoutParams == null) {
15594            output += "BAD! no layout params";
15595        } else {
15596            output = mLayoutParams.debug(output);
15597        }
15598        Log.d(VIEW_LOG_TAG, output);
15599
15600        output = debugIndent(depth);
15601        output += "flags={";
15602        output += View.printFlags(mViewFlags);
15603        output += "}";
15604        Log.d(VIEW_LOG_TAG, output);
15605
15606        output = debugIndent(depth);
15607        output += "privateFlags={";
15608        output += View.printPrivateFlags(mPrivateFlags);
15609        output += "}";
15610        Log.d(VIEW_LOG_TAG, output);
15611    }
15612
15613    /**
15614     * Creates a string of whitespaces used for indentation.
15615     *
15616     * @param depth the indentation level
15617     * @return a String containing (depth * 2 + 3) * 2 white spaces
15618     *
15619     * @hide
15620     */
15621    protected static String debugIndent(int depth) {
15622        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
15623        for (int i = 0; i < (depth * 2) + 3; i++) {
15624            spaces.append(' ').append(' ');
15625        }
15626        return spaces.toString();
15627    }
15628
15629    /**
15630     * <p>Return the offset of the widget's text baseline from the widget's top
15631     * boundary. If this widget does not support baseline alignment, this
15632     * method returns -1. </p>
15633     *
15634     * @return the offset of the baseline within the widget's bounds or -1
15635     *         if baseline alignment is not supported
15636     */
15637    @ViewDebug.ExportedProperty(category = "layout")
15638    public int getBaseline() {
15639        return -1;
15640    }
15641
15642    /**
15643     * Returns whether the view hierarchy is currently undergoing a layout pass. This
15644     * information is useful to avoid situations such as calling {@link #requestLayout()} during
15645     * a layout pass.
15646     *
15647     * @return whether the view hierarchy is currently undergoing a layout pass
15648     */
15649    public boolean isInLayout() {
15650        ViewRootImpl viewRoot = getViewRootImpl();
15651        return (viewRoot != null && viewRoot.isInLayout());
15652    }
15653
15654    /**
15655     * Call this when something has changed which has invalidated the
15656     * layout of this view. This will schedule a layout pass of the view
15657     * tree. This should not be called while the view hierarchy is currently in a layout
15658     * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the
15659     * end of the current layout pass (and then layout will run again) or after the current
15660     * frame is drawn and the next layout occurs.
15661     *
15662     * <p>Subclasses which override this method should call the superclass method to
15663     * handle possible request-during-layout errors correctly.</p>
15664     */
15665    public void requestLayout() {
15666        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
15667            // Only trigger request-during-layout logic if this is the view requesting it,
15668            // not the views in its parent hierarchy
15669            ViewRootImpl viewRoot = getViewRootImpl();
15670            if (viewRoot != null && viewRoot.isInLayout()) {
15671                if (!viewRoot.requestLayoutDuringLayout(this)) {
15672                    return;
15673                }
15674            }
15675            mAttachInfo.mViewRequestingLayout = this;
15676        }
15677
15678        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15679        mPrivateFlags |= PFLAG_INVALIDATED;
15680
15681        if (mParent != null && !mParent.isLayoutRequested()) {
15682            mParent.requestLayout();
15683        }
15684        if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
15685            mAttachInfo.mViewRequestingLayout = null;
15686        }
15687    }
15688
15689    /**
15690     * Forces this view to be laid out during the next layout pass.
15691     * This method does not call requestLayout() or forceLayout()
15692     * on the parent.
15693     */
15694    public void forceLayout() {
15695        mPrivateFlags |= PFLAG_FORCE_LAYOUT;
15696        mPrivateFlags |= PFLAG_INVALIDATED;
15697    }
15698
15699    /**
15700     * <p>
15701     * This is called to find out how big a view should be. The parent
15702     * supplies constraint information in the width and height parameters.
15703     * </p>
15704     *
15705     * <p>
15706     * The actual measurement work of a view is performed in
15707     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
15708     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
15709     * </p>
15710     *
15711     *
15712     * @param widthMeasureSpec Horizontal space requirements as imposed by the
15713     *        parent
15714     * @param heightMeasureSpec Vertical space requirements as imposed by the
15715     *        parent
15716     *
15717     * @see #onMeasure(int, int)
15718     */
15719    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
15720        boolean optical = isLayoutModeOptical(this);
15721        if (optical != isLayoutModeOptical(mParent)) {
15722            Insets insets = getOpticalInsets();
15723            int oWidth  = insets.left + insets.right;
15724            int oHeight = insets.top  + insets.bottom;
15725            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
15726            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
15727        }
15728        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
15729                widthMeasureSpec != mOldWidthMeasureSpec ||
15730                heightMeasureSpec != mOldHeightMeasureSpec) {
15731
15732            // first clears the measured dimension flag
15733            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
15734
15735            resolveRtlPropertiesIfNeeded();
15736
15737            // measure ourselves, this should set the measured dimension flag back
15738            onMeasure(widthMeasureSpec, heightMeasureSpec);
15739
15740            // flag not set, setMeasuredDimension() was not invoked, we raise
15741            // an exception to warn the developer
15742            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
15743                throw new IllegalStateException("onMeasure() did not set the"
15744                        + " measured dimension by calling"
15745                        + " setMeasuredDimension()");
15746            }
15747
15748            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
15749        }
15750
15751        mOldWidthMeasureSpec = widthMeasureSpec;
15752        mOldHeightMeasureSpec = heightMeasureSpec;
15753    }
15754
15755    /**
15756     * <p>
15757     * Measure the view and its content to determine the measured width and the
15758     * measured height. This method is invoked by {@link #measure(int, int)} and
15759     * should be overriden by subclasses to provide accurate and efficient
15760     * measurement of their contents.
15761     * </p>
15762     *
15763     * <p>
15764     * <strong>CONTRACT:</strong> When overriding this method, you
15765     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
15766     * measured width and height of this view. Failure to do so will trigger an
15767     * <code>IllegalStateException</code>, thrown by
15768     * {@link #measure(int, int)}. Calling the superclass'
15769     * {@link #onMeasure(int, int)} is a valid use.
15770     * </p>
15771     *
15772     * <p>
15773     * The base class implementation of measure defaults to the background size,
15774     * unless a larger size is allowed by the MeasureSpec. Subclasses should
15775     * override {@link #onMeasure(int, int)} to provide better measurements of
15776     * their content.
15777     * </p>
15778     *
15779     * <p>
15780     * If this method is overridden, it is the subclass's responsibility to make
15781     * sure the measured height and width are at least the view's minimum height
15782     * and width ({@link #getSuggestedMinimumHeight()} and
15783     * {@link #getSuggestedMinimumWidth()}).
15784     * </p>
15785     *
15786     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
15787     *                         The requirements are encoded with
15788     *                         {@link android.view.View.MeasureSpec}.
15789     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
15790     *                         The requirements are encoded with
15791     *                         {@link android.view.View.MeasureSpec}.
15792     *
15793     * @see #getMeasuredWidth()
15794     * @see #getMeasuredHeight()
15795     * @see #setMeasuredDimension(int, int)
15796     * @see #getSuggestedMinimumHeight()
15797     * @see #getSuggestedMinimumWidth()
15798     * @see android.view.View.MeasureSpec#getMode(int)
15799     * @see android.view.View.MeasureSpec#getSize(int)
15800     */
15801    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
15802        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
15803                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
15804    }
15805
15806    /**
15807     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
15808     * measured width and measured height. Failing to do so will trigger an
15809     * exception at measurement time.</p>
15810     *
15811     * @param measuredWidth The measured width of this view.  May be a complex
15812     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15813     * {@link #MEASURED_STATE_TOO_SMALL}.
15814     * @param measuredHeight The measured height of this view.  May be a complex
15815     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
15816     * {@link #MEASURED_STATE_TOO_SMALL}.
15817     */
15818    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
15819        boolean optical = isLayoutModeOptical(this);
15820        if (optical != isLayoutModeOptical(mParent)) {
15821            Insets insets = getOpticalInsets();
15822            int opticalWidth  = insets.left + insets.right;
15823            int opticalHeight = insets.top  + insets.bottom;
15824
15825            measuredWidth  += optical ? opticalWidth  : -opticalWidth;
15826            measuredHeight += optical ? opticalHeight : -opticalHeight;
15827        }
15828        mMeasuredWidth = measuredWidth;
15829        mMeasuredHeight = measuredHeight;
15830
15831        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
15832    }
15833
15834    /**
15835     * Merge two states as returned by {@link #getMeasuredState()}.
15836     * @param curState The current state as returned from a view or the result
15837     * of combining multiple views.
15838     * @param newState The new view state to combine.
15839     * @return Returns a new integer reflecting the combination of the two
15840     * states.
15841     */
15842    public static int combineMeasuredStates(int curState, int newState) {
15843        return curState | newState;
15844    }
15845
15846    /**
15847     * Version of {@link #resolveSizeAndState(int, int, int)}
15848     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
15849     */
15850    public static int resolveSize(int size, int measureSpec) {
15851        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
15852    }
15853
15854    /**
15855     * Utility to reconcile a desired size and state, with constraints imposed
15856     * by a MeasureSpec.  Will take the desired size, unless a different size
15857     * is imposed by the constraints.  The returned value is a compound integer,
15858     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
15859     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
15860     * size is smaller than the size the view wants to be.
15861     *
15862     * @param size How big the view wants to be
15863     * @param measureSpec Constraints imposed by the parent
15864     * @return Size information bit mask as defined by
15865     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
15866     */
15867    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
15868        int result = size;
15869        int specMode = MeasureSpec.getMode(measureSpec);
15870        int specSize =  MeasureSpec.getSize(measureSpec);
15871        switch (specMode) {
15872        case MeasureSpec.UNSPECIFIED:
15873            result = size;
15874            break;
15875        case MeasureSpec.AT_MOST:
15876            if (specSize < size) {
15877                result = specSize | MEASURED_STATE_TOO_SMALL;
15878            } else {
15879                result = size;
15880            }
15881            break;
15882        case MeasureSpec.EXACTLY:
15883            result = specSize;
15884            break;
15885        }
15886        return result | (childMeasuredState&MEASURED_STATE_MASK);
15887    }
15888
15889    /**
15890     * Utility to return a default size. Uses the supplied size if the
15891     * MeasureSpec imposed no constraints. Will get larger if allowed
15892     * by the MeasureSpec.
15893     *
15894     * @param size Default size for this view
15895     * @param measureSpec Constraints imposed by the parent
15896     * @return The size this view should be.
15897     */
15898    public static int getDefaultSize(int size, int measureSpec) {
15899        int result = size;
15900        int specMode = MeasureSpec.getMode(measureSpec);
15901        int specSize = MeasureSpec.getSize(measureSpec);
15902
15903        switch (specMode) {
15904        case MeasureSpec.UNSPECIFIED:
15905            result = size;
15906            break;
15907        case MeasureSpec.AT_MOST:
15908        case MeasureSpec.EXACTLY:
15909            result = specSize;
15910            break;
15911        }
15912        return result;
15913    }
15914
15915    /**
15916     * Returns the suggested minimum height that the view should use. This
15917     * returns the maximum of the view's minimum height
15918     * and the background's minimum height
15919     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
15920     * <p>
15921     * When being used in {@link #onMeasure(int, int)}, the caller should still
15922     * ensure the returned height is within the requirements of the parent.
15923     *
15924     * @return The suggested minimum height of the view.
15925     */
15926    protected int getSuggestedMinimumHeight() {
15927        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
15928
15929    }
15930
15931    /**
15932     * Returns the suggested minimum width that the view should use. This
15933     * returns the maximum of the view's minimum width)
15934     * and the background's minimum width
15935     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
15936     * <p>
15937     * When being used in {@link #onMeasure(int, int)}, the caller should still
15938     * ensure the returned width is within the requirements of the parent.
15939     *
15940     * @return The suggested minimum width of the view.
15941     */
15942    protected int getSuggestedMinimumWidth() {
15943        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
15944    }
15945
15946    /**
15947     * Returns the minimum height of the view.
15948     *
15949     * @return the minimum height the view will try to be.
15950     *
15951     * @see #setMinimumHeight(int)
15952     *
15953     * @attr ref android.R.styleable#View_minHeight
15954     */
15955    public int getMinimumHeight() {
15956        return mMinHeight;
15957    }
15958
15959    /**
15960     * Sets the minimum height of the view. It is not guaranteed the view will
15961     * be able to achieve this minimum height (for example, if its parent layout
15962     * constrains it with less available height).
15963     *
15964     * @param minHeight The minimum height the view will try to be.
15965     *
15966     * @see #getMinimumHeight()
15967     *
15968     * @attr ref android.R.styleable#View_minHeight
15969     */
15970    public void setMinimumHeight(int minHeight) {
15971        mMinHeight = minHeight;
15972        requestLayout();
15973    }
15974
15975    /**
15976     * Returns the minimum width of the view.
15977     *
15978     * @return the minimum width the view will try to be.
15979     *
15980     * @see #setMinimumWidth(int)
15981     *
15982     * @attr ref android.R.styleable#View_minWidth
15983     */
15984    public int getMinimumWidth() {
15985        return mMinWidth;
15986    }
15987
15988    /**
15989     * Sets the minimum width of the view. It is not guaranteed the view will
15990     * be able to achieve this minimum width (for example, if its parent layout
15991     * constrains it with less available width).
15992     *
15993     * @param minWidth The minimum width the view will try to be.
15994     *
15995     * @see #getMinimumWidth()
15996     *
15997     * @attr ref android.R.styleable#View_minWidth
15998     */
15999    public void setMinimumWidth(int minWidth) {
16000        mMinWidth = minWidth;
16001        requestLayout();
16002
16003    }
16004
16005    /**
16006     * Get the animation currently associated with this view.
16007     *
16008     * @return The animation that is currently playing or
16009     *         scheduled to play for this view.
16010     */
16011    public Animation getAnimation() {
16012        return mCurrentAnimation;
16013    }
16014
16015    /**
16016     * Start the specified animation now.
16017     *
16018     * @param animation the animation to start now
16019     */
16020    public void startAnimation(Animation animation) {
16021        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
16022        setAnimation(animation);
16023        invalidateParentCaches();
16024        invalidate(true);
16025    }
16026
16027    /**
16028     * Cancels any animations for this view.
16029     */
16030    public void clearAnimation() {
16031        if (mCurrentAnimation != null) {
16032            mCurrentAnimation.detach();
16033        }
16034        mCurrentAnimation = null;
16035        invalidateParentIfNeeded();
16036    }
16037
16038    /**
16039     * Sets the next animation to play for this view.
16040     * If you want the animation to play immediately, use
16041     * {@link #startAnimation(android.view.animation.Animation)} instead.
16042     * This method provides allows fine-grained
16043     * control over the start time and invalidation, but you
16044     * must make sure that 1) the animation has a start time set, and
16045     * 2) the view's parent (which controls animations on its children)
16046     * will be invalidated when the animation is supposed to
16047     * start.
16048     *
16049     * @param animation The next animation, or null.
16050     */
16051    public void setAnimation(Animation animation) {
16052        mCurrentAnimation = animation;
16053
16054        if (animation != null) {
16055            // If the screen is off assume the animation start time is now instead of
16056            // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time
16057            // would cause the animation to start when the screen turns back on
16058            if (mAttachInfo != null && !mAttachInfo.mScreenOn &&
16059                    animation.getStartTime() == Animation.START_ON_FIRST_FRAME) {
16060                animation.setStartTime(AnimationUtils.currentAnimationTimeMillis());
16061            }
16062            animation.reset();
16063        }
16064    }
16065
16066    /**
16067     * Invoked by a parent ViewGroup to notify the start of the animation
16068     * currently associated with this view. If you override this method,
16069     * always call super.onAnimationStart();
16070     *
16071     * @see #setAnimation(android.view.animation.Animation)
16072     * @see #getAnimation()
16073     */
16074    protected void onAnimationStart() {
16075        mPrivateFlags |= PFLAG_ANIMATION_STARTED;
16076    }
16077
16078    /**
16079     * Invoked by a parent ViewGroup to notify the end of the animation
16080     * currently associated with this view. If you override this method,
16081     * always call super.onAnimationEnd();
16082     *
16083     * @see #setAnimation(android.view.animation.Animation)
16084     * @see #getAnimation()
16085     */
16086    protected void onAnimationEnd() {
16087        mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
16088    }
16089
16090    /**
16091     * Invoked if there is a Transform that involves alpha. Subclass that can
16092     * draw themselves with the specified alpha should return true, and then
16093     * respect that alpha when their onDraw() is called. If this returns false
16094     * then the view may be redirected to draw into an offscreen buffer to
16095     * fulfill the request, which will look fine, but may be slower than if the
16096     * subclass handles it internally. The default implementation returns false.
16097     *
16098     * @param alpha The alpha (0..255) to apply to the view's drawing
16099     * @return true if the view can draw with the specified alpha.
16100     */
16101    protected boolean onSetAlpha(int alpha) {
16102        return false;
16103    }
16104
16105    /**
16106     * This is used by the RootView to perform an optimization when
16107     * the view hierarchy contains one or several SurfaceView.
16108     * SurfaceView is always considered transparent, but its children are not,
16109     * therefore all View objects remove themselves from the global transparent
16110     * region (passed as a parameter to this function).
16111     *
16112     * @param region The transparent region for this ViewAncestor (window).
16113     *
16114     * @return Returns true if the effective visibility of the view at this
16115     * point is opaque, regardless of the transparent region; returns false
16116     * if it is possible for underlying windows to be seen behind the view.
16117     *
16118     * {@hide}
16119     */
16120    public boolean gatherTransparentRegion(Region region) {
16121        final AttachInfo attachInfo = mAttachInfo;
16122        if (region != null && attachInfo != null) {
16123            final int pflags = mPrivateFlags;
16124            if ((pflags & PFLAG_SKIP_DRAW) == 0) {
16125                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
16126                // remove it from the transparent region.
16127                final int[] location = attachInfo.mTransparentLocation;
16128                getLocationInWindow(location);
16129                region.op(location[0], location[1], location[0] + mRight - mLeft,
16130                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
16131            } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) {
16132                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
16133                // exists, so we remove the background drawable's non-transparent
16134                // parts from this transparent region.
16135                applyDrawableToTransparentRegion(mBackground, region);
16136            }
16137        }
16138        return true;
16139    }
16140
16141    /**
16142     * Play a sound effect for this view.
16143     *
16144     * <p>The framework will play sound effects for some built in actions, such as
16145     * clicking, but you may wish to play these effects in your widget,
16146     * for instance, for internal navigation.
16147     *
16148     * <p>The sound effect will only be played if sound effects are enabled by the user, and
16149     * {@link #isSoundEffectsEnabled()} is true.
16150     *
16151     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
16152     */
16153    public void playSoundEffect(int soundConstant) {
16154        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
16155            return;
16156        }
16157        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
16158    }
16159
16160    /**
16161     * BZZZTT!!1!
16162     *
16163     * <p>Provide haptic feedback to the user for this view.
16164     *
16165     * <p>The framework will provide haptic feedback for some built in actions,
16166     * such as long presses, but you may wish to provide feedback for your
16167     * own widget.
16168     *
16169     * <p>The feedback will only be performed if
16170     * {@link #isHapticFeedbackEnabled()} is true.
16171     *
16172     * @param feedbackConstant One of the constants defined in
16173     * {@link HapticFeedbackConstants}
16174     */
16175    public boolean performHapticFeedback(int feedbackConstant) {
16176        return performHapticFeedback(feedbackConstant, 0);
16177    }
16178
16179    /**
16180     * BZZZTT!!1!
16181     *
16182     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
16183     *
16184     * @param feedbackConstant One of the constants defined in
16185     * {@link HapticFeedbackConstants}
16186     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
16187     */
16188    public boolean performHapticFeedback(int feedbackConstant, int flags) {
16189        if (mAttachInfo == null) {
16190            return false;
16191        }
16192        //noinspection SimplifiableIfStatement
16193        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
16194                && !isHapticFeedbackEnabled()) {
16195            return false;
16196        }
16197        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
16198                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
16199    }
16200
16201    /**
16202     * Request that the visibility of the status bar or other screen/window
16203     * decorations be changed.
16204     *
16205     * <p>This method is used to put the over device UI into temporary modes
16206     * where the user's attention is focused more on the application content,
16207     * by dimming or hiding surrounding system affordances.  This is typically
16208     * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY
16209     * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content
16210     * to be placed behind the action bar (and with these flags other system
16211     * affordances) so that smooth transitions between hiding and showing them
16212     * can be done.
16213     *
16214     * <p>Two representative examples of the use of system UI visibility is
16215     * implementing a content browsing application (like a magazine reader)
16216     * and a video playing application.
16217     *
16218     * <p>The first code shows a typical implementation of a View in a content
16219     * browsing application.  In this implementation, the application goes
16220     * into a content-oriented mode by hiding the status bar and action bar,
16221     * and putting the navigation elements into lights out mode.  The user can
16222     * then interact with content while in this mode.  Such an application should
16223     * provide an easy way for the user to toggle out of the mode (such as to
16224     * check information in the status bar or access notifications).  In the
16225     * implementation here, this is done simply by tapping on the content.
16226     *
16227     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java
16228     *      content}
16229     *
16230     * <p>This second code sample shows a typical implementation of a View
16231     * in a video playing application.  In this situation, while the video is
16232     * playing the application would like to go into a complete full-screen mode,
16233     * to use as much of the display as possible for the video.  When in this state
16234     * the user can not interact with the application; the system intercepts
16235     * touching on the screen to pop the UI out of full screen mode.  See
16236     * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code.
16237     *
16238     * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java
16239     *      content}
16240     *
16241     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16242     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16243     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16244     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16245     */
16246    public void setSystemUiVisibility(int visibility) {
16247        if (visibility != mSystemUiVisibility) {
16248            mSystemUiVisibility = visibility;
16249            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16250                mParent.recomputeViewAttributes(this);
16251            }
16252        }
16253    }
16254
16255    /**
16256     * Returns the last {@link #setSystemUiVisibility(int) that this view has requested.
16257     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
16258     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN},
16259     * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION},
16260     * and {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.
16261     */
16262    public int getSystemUiVisibility() {
16263        return mSystemUiVisibility;
16264    }
16265
16266    /**
16267     * Returns the current system UI visibility that is currently set for
16268     * the entire window.  This is the combination of the
16269     * {@link #setSystemUiVisibility(int)} values supplied by all of the
16270     * views in the window.
16271     */
16272    public int getWindowSystemUiVisibility() {
16273        return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0;
16274    }
16275
16276    /**
16277     * Override to find out when the window's requested system UI visibility
16278     * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}.
16279     * This is different from the callbacks recieved through
16280     * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)}
16281     * in that this is only telling you about the local request of the window,
16282     * not the actual values applied by the system.
16283     */
16284    public void onWindowSystemUiVisibilityChanged(int visible) {
16285    }
16286
16287    /**
16288     * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down
16289     * the view hierarchy.
16290     */
16291    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
16292        onWindowSystemUiVisibilityChanged(visible);
16293    }
16294
16295    /**
16296     * Set a listener to receive callbacks when the visibility of the system bar changes.
16297     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
16298     */
16299    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
16300        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
16301        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
16302            mParent.recomputeViewAttributes(this);
16303        }
16304    }
16305
16306    /**
16307     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
16308     * the view hierarchy.
16309     */
16310    public void dispatchSystemUiVisibilityChanged(int visibility) {
16311        ListenerInfo li = mListenerInfo;
16312        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
16313            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
16314                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
16315        }
16316    }
16317
16318    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
16319        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
16320        if (val != mSystemUiVisibility) {
16321            setSystemUiVisibility(val);
16322            return true;
16323        }
16324        return false;
16325    }
16326
16327    /** @hide */
16328    public void setDisabledSystemUiVisibility(int flags) {
16329        if (mAttachInfo != null) {
16330            if (mAttachInfo.mDisabledSystemUiVisibility != flags) {
16331                mAttachInfo.mDisabledSystemUiVisibility = flags;
16332                if (mParent != null) {
16333                    mParent.recomputeViewAttributes(this);
16334                }
16335            }
16336        }
16337    }
16338
16339    /**
16340     * Creates an image that the system displays during the drag and drop
16341     * operation. This is called a &quot;drag shadow&quot;. The default implementation
16342     * for a DragShadowBuilder based on a View returns an image that has exactly the same
16343     * appearance as the given View. The default also positions the center of the drag shadow
16344     * directly under the touch point. If no View is provided (the constructor with no parameters
16345     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
16346     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
16347     * default is an invisible drag shadow.
16348     * <p>
16349     * You are not required to use the View you provide to the constructor as the basis of the
16350     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
16351     * anything you want as the drag shadow.
16352     * </p>
16353     * <p>
16354     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
16355     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
16356     *  size and position of the drag shadow. It uses this data to construct a
16357     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
16358     *  so that your application can draw the shadow image in the Canvas.
16359     * </p>
16360     *
16361     * <div class="special reference">
16362     * <h3>Developer Guides</h3>
16363     * <p>For a guide to implementing drag and drop features, read the
16364     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
16365     * </div>
16366     */
16367    public static class DragShadowBuilder {
16368        private final WeakReference<View> mView;
16369
16370        /**
16371         * Constructs a shadow image builder based on a View. By default, the resulting drag
16372         * shadow will have the same appearance and dimensions as the View, with the touch point
16373         * over the center of the View.
16374         * @param view A View. Any View in scope can be used.
16375         */
16376        public DragShadowBuilder(View view) {
16377            mView = new WeakReference<View>(view);
16378        }
16379
16380        /**
16381         * Construct a shadow builder object with no associated View.  This
16382         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
16383         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
16384         * to supply the drag shadow's dimensions and appearance without
16385         * reference to any View object. If they are not overridden, then the result is an
16386         * invisible drag shadow.
16387         */
16388        public DragShadowBuilder() {
16389            mView = new WeakReference<View>(null);
16390        }
16391
16392        /**
16393         * Returns the View object that had been passed to the
16394         * {@link #View.DragShadowBuilder(View)}
16395         * constructor.  If that View parameter was {@code null} or if the
16396         * {@link #View.DragShadowBuilder()}
16397         * constructor was used to instantiate the builder object, this method will return
16398         * null.
16399         *
16400         * @return The View object associate with this builder object.
16401         */
16402        @SuppressWarnings({"JavadocReference"})
16403        final public View getView() {
16404            return mView.get();
16405        }
16406
16407        /**
16408         * Provides the metrics for the shadow image. These include the dimensions of
16409         * the shadow image, and the point within that shadow that should
16410         * be centered under the touch location while dragging.
16411         * <p>
16412         * The default implementation sets the dimensions of the shadow to be the
16413         * same as the dimensions of the View itself and centers the shadow under
16414         * the touch point.
16415         * </p>
16416         *
16417         * @param shadowSize A {@link android.graphics.Point} containing the width and height
16418         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
16419         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
16420         * image.
16421         *
16422         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
16423         * shadow image that should be underneath the touch point during the drag and drop
16424         * operation. Your application must set {@link android.graphics.Point#x} to the
16425         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
16426         */
16427        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
16428            final View view = mView.get();
16429            if (view != null) {
16430                shadowSize.set(view.getWidth(), view.getHeight());
16431                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
16432            } else {
16433                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
16434            }
16435        }
16436
16437        /**
16438         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
16439         * based on the dimensions it received from the
16440         * {@link #onProvideShadowMetrics(Point, Point)} callback.
16441         *
16442         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
16443         */
16444        public void onDrawShadow(Canvas canvas) {
16445            final View view = mView.get();
16446            if (view != null) {
16447                view.draw(canvas);
16448            } else {
16449                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
16450            }
16451        }
16452    }
16453
16454    /**
16455     * Starts a drag and drop operation. When your application calls this method, it passes a
16456     * {@link android.view.View.DragShadowBuilder} object to the system. The
16457     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
16458     * to get metrics for the drag shadow, and then calls the object's
16459     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
16460     * <p>
16461     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
16462     *  drag events to all the View objects in your application that are currently visible. It does
16463     *  this either by calling the View object's drag listener (an implementation of
16464     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
16465     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
16466     *  Both are passed a {@link android.view.DragEvent} object that has a
16467     *  {@link android.view.DragEvent#getAction()} value of
16468     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
16469     * </p>
16470     * <p>
16471     * Your application can invoke startDrag() on any attached View object. The View object does not
16472     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
16473     * be related to the View the user selected for dragging.
16474     * </p>
16475     * @param data A {@link android.content.ClipData} object pointing to the data to be
16476     * transferred by the drag and drop operation.
16477     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
16478     * drag shadow.
16479     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
16480     * drop operation. This Object is put into every DragEvent object sent by the system during the
16481     * current drag.
16482     * <p>
16483     * myLocalState is a lightweight mechanism for the sending information from the dragged View
16484     * to the target Views. For example, it can contain flags that differentiate between a
16485     * a copy operation and a move operation.
16486     * </p>
16487     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
16488     * so the parameter should be set to 0.
16489     * @return {@code true} if the method completes successfully, or
16490     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
16491     * do a drag, and so no drag operation is in progress.
16492     */
16493    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
16494            Object myLocalState, int flags) {
16495        if (ViewDebug.DEBUG_DRAG) {
16496            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
16497        }
16498        boolean okay = false;
16499
16500        Point shadowSize = new Point();
16501        Point shadowTouchPoint = new Point();
16502        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
16503
16504        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
16505                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
16506            throw new IllegalStateException("Drag shadow dimensions must not be negative");
16507        }
16508
16509        if (ViewDebug.DEBUG_DRAG) {
16510            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
16511                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
16512        }
16513        Surface surface = new Surface();
16514        try {
16515            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
16516                    flags, shadowSize.x, shadowSize.y, surface);
16517            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
16518                    + " surface=" + surface);
16519            if (token != null) {
16520                Canvas canvas = surface.lockCanvas(null);
16521                try {
16522                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
16523                    shadowBuilder.onDrawShadow(canvas);
16524                } finally {
16525                    surface.unlockCanvasAndPost(canvas);
16526                }
16527
16528                final ViewRootImpl root = getViewRootImpl();
16529
16530                // Cache the local state object for delivery with DragEvents
16531                root.setLocalDragState(myLocalState);
16532
16533                // repurpose 'shadowSize' for the last touch point
16534                root.getLastTouchPoint(shadowSize);
16535
16536                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
16537                        shadowSize.x, shadowSize.y,
16538                        shadowTouchPoint.x, shadowTouchPoint.y, data);
16539                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
16540
16541                // Off and running!  Release our local surface instance; the drag
16542                // shadow surface is now managed by the system process.
16543                surface.release();
16544            }
16545        } catch (Exception e) {
16546            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
16547            surface.destroy();
16548        }
16549
16550        return okay;
16551    }
16552
16553    /**
16554     * Handles drag events sent by the system following a call to
16555     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
16556     *<p>
16557     * When the system calls this method, it passes a
16558     * {@link android.view.DragEvent} object. A call to
16559     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
16560     * in DragEvent. The method uses these to determine what is happening in the drag and drop
16561     * operation.
16562     * @param event The {@link android.view.DragEvent} sent by the system.
16563     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
16564     * in DragEvent, indicating the type of drag event represented by this object.
16565     * @return {@code true} if the method was successful, otherwise {@code false}.
16566     * <p>
16567     *  The method should return {@code true} in response to an action type of
16568     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
16569     *  operation.
16570     * </p>
16571     * <p>
16572     *  The method should also return {@code true} in response to an action type of
16573     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
16574     *  {@code false} if it didn't.
16575     * </p>
16576     */
16577    public boolean onDragEvent(DragEvent event) {
16578        return false;
16579    }
16580
16581    /**
16582     * Detects if this View is enabled and has a drag event listener.
16583     * If both are true, then it calls the drag event listener with the
16584     * {@link android.view.DragEvent} it received. If the drag event listener returns
16585     * {@code true}, then dispatchDragEvent() returns {@code true}.
16586     * <p>
16587     * For all other cases, the method calls the
16588     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
16589     * method and returns its result.
16590     * </p>
16591     * <p>
16592     * This ensures that a drag event is always consumed, even if the View does not have a drag
16593     * event listener. However, if the View has a listener and the listener returns true, then
16594     * onDragEvent() is not called.
16595     * </p>
16596     */
16597    public boolean dispatchDragEvent(DragEvent event) {
16598        //noinspection SimplifiableIfStatement
16599        ListenerInfo li = mListenerInfo;
16600        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
16601                && li.mOnDragListener.onDrag(this, event)) {
16602            return true;
16603        }
16604        return onDragEvent(event);
16605    }
16606
16607    boolean canAcceptDrag() {
16608        return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0;
16609    }
16610
16611    /**
16612     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
16613     * it is ever exposed at all.
16614     * @hide
16615     */
16616    public void onCloseSystemDialogs(String reason) {
16617    }
16618
16619    /**
16620     * Given a Drawable whose bounds have been set to draw into this view,
16621     * update a Region being computed for
16622     * {@link #gatherTransparentRegion(android.graphics.Region)} so
16623     * that any non-transparent parts of the Drawable are removed from the
16624     * given transparent region.
16625     *
16626     * @param dr The Drawable whose transparency is to be applied to the region.
16627     * @param region A Region holding the current transparency information,
16628     * where any parts of the region that are set are considered to be
16629     * transparent.  On return, this region will be modified to have the
16630     * transparency information reduced by the corresponding parts of the
16631     * Drawable that are not transparent.
16632     * {@hide}
16633     */
16634    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
16635        if (DBG) {
16636            Log.i("View", "Getting transparent region for: " + this);
16637        }
16638        final Region r = dr.getTransparentRegion();
16639        final Rect db = dr.getBounds();
16640        final AttachInfo attachInfo = mAttachInfo;
16641        if (r != null && attachInfo != null) {
16642            final int w = getRight()-getLeft();
16643            final int h = getBottom()-getTop();
16644            if (db.left > 0) {
16645                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
16646                r.op(0, 0, db.left, h, Region.Op.UNION);
16647            }
16648            if (db.right < w) {
16649                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
16650                r.op(db.right, 0, w, h, Region.Op.UNION);
16651            }
16652            if (db.top > 0) {
16653                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
16654                r.op(0, 0, w, db.top, Region.Op.UNION);
16655            }
16656            if (db.bottom < h) {
16657                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
16658                r.op(0, db.bottom, w, h, Region.Op.UNION);
16659            }
16660            final int[] location = attachInfo.mTransparentLocation;
16661            getLocationInWindow(location);
16662            r.translate(location[0], location[1]);
16663            region.op(r, Region.Op.INTERSECT);
16664        } else {
16665            region.op(db, Region.Op.DIFFERENCE);
16666        }
16667    }
16668
16669    private void checkForLongClick(int delayOffset) {
16670        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
16671            mHasPerformedLongPress = false;
16672
16673            if (mPendingCheckForLongPress == null) {
16674                mPendingCheckForLongPress = new CheckForLongPress();
16675            }
16676            mPendingCheckForLongPress.rememberWindowAttachCount();
16677            postDelayed(mPendingCheckForLongPress,
16678                    ViewConfiguration.getLongPressTimeout() - delayOffset);
16679        }
16680    }
16681
16682    /**
16683     * Inflate a view from an XML resource.  This convenience method wraps the {@link
16684     * LayoutInflater} class, which provides a full range of options for view inflation.
16685     *
16686     * @param context The Context object for your activity or application.
16687     * @param resource The resource ID to inflate
16688     * @param root A view group that will be the parent.  Used to properly inflate the
16689     * layout_* parameters.
16690     * @see LayoutInflater
16691     */
16692    public static View inflate(Context context, int resource, ViewGroup root) {
16693        LayoutInflater factory = LayoutInflater.from(context);
16694        return factory.inflate(resource, root);
16695    }
16696
16697    /**
16698     * Scroll the view with standard behavior for scrolling beyond the normal
16699     * content boundaries. Views that call this method should override
16700     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
16701     * results of an over-scroll operation.
16702     *
16703     * Views can use this method to handle any touch or fling-based scrolling.
16704     *
16705     * @param deltaX Change in X in pixels
16706     * @param deltaY Change in Y in pixels
16707     * @param scrollX Current X scroll value in pixels before applying deltaX
16708     * @param scrollY Current Y scroll value in pixels before applying deltaY
16709     * @param scrollRangeX Maximum content scroll range along the X axis
16710     * @param scrollRangeY Maximum content scroll range along the Y axis
16711     * @param maxOverScrollX Number of pixels to overscroll by in either direction
16712     *          along the X axis.
16713     * @param maxOverScrollY Number of pixels to overscroll by in either direction
16714     *          along the Y axis.
16715     * @param isTouchEvent true if this scroll operation is the result of a touch event.
16716     * @return true if scrolling was clamped to an over-scroll boundary along either
16717     *          axis, false otherwise.
16718     */
16719    @SuppressWarnings({"UnusedParameters"})
16720    protected boolean overScrollBy(int deltaX, int deltaY,
16721            int scrollX, int scrollY,
16722            int scrollRangeX, int scrollRangeY,
16723            int maxOverScrollX, int maxOverScrollY,
16724            boolean isTouchEvent) {
16725        final int overScrollMode = mOverScrollMode;
16726        final boolean canScrollHorizontal =
16727                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
16728        final boolean canScrollVertical =
16729                computeVerticalScrollRange() > computeVerticalScrollExtent();
16730        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
16731                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
16732        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
16733                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
16734
16735        int newScrollX = scrollX + deltaX;
16736        if (!overScrollHorizontal) {
16737            maxOverScrollX = 0;
16738        }
16739
16740        int newScrollY = scrollY + deltaY;
16741        if (!overScrollVertical) {
16742            maxOverScrollY = 0;
16743        }
16744
16745        // Clamp values if at the limits and record
16746        final int left = -maxOverScrollX;
16747        final int right = maxOverScrollX + scrollRangeX;
16748        final int top = -maxOverScrollY;
16749        final int bottom = maxOverScrollY + scrollRangeY;
16750
16751        boolean clampedX = false;
16752        if (newScrollX > right) {
16753            newScrollX = right;
16754            clampedX = true;
16755        } else if (newScrollX < left) {
16756            newScrollX = left;
16757            clampedX = true;
16758        }
16759
16760        boolean clampedY = false;
16761        if (newScrollY > bottom) {
16762            newScrollY = bottom;
16763            clampedY = true;
16764        } else if (newScrollY < top) {
16765            newScrollY = top;
16766            clampedY = true;
16767        }
16768
16769        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
16770
16771        return clampedX || clampedY;
16772    }
16773
16774    /**
16775     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
16776     * respond to the results of an over-scroll operation.
16777     *
16778     * @param scrollX New X scroll value in pixels
16779     * @param scrollY New Y scroll value in pixels
16780     * @param clampedX True if scrollX was clamped to an over-scroll boundary
16781     * @param clampedY True if scrollY was clamped to an over-scroll boundary
16782     */
16783    protected void onOverScrolled(int scrollX, int scrollY,
16784            boolean clampedX, boolean clampedY) {
16785        // Intentionally empty.
16786    }
16787
16788    /**
16789     * Returns the over-scroll mode for this view. The result will be
16790     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16791     * (allow over-scrolling only if the view content is larger than the container),
16792     * or {@link #OVER_SCROLL_NEVER}.
16793     *
16794     * @return This view's over-scroll mode.
16795     */
16796    public int getOverScrollMode() {
16797        return mOverScrollMode;
16798    }
16799
16800    /**
16801     * Set the over-scroll mode for this view. Valid over-scroll modes are
16802     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
16803     * (allow over-scrolling only if the view content is larger than the container),
16804     * or {@link #OVER_SCROLL_NEVER}.
16805     *
16806     * Setting the over-scroll mode of a view will have an effect only if the
16807     * view is capable of scrolling.
16808     *
16809     * @param overScrollMode The new over-scroll mode for this view.
16810     */
16811    public void setOverScrollMode(int overScrollMode) {
16812        if (overScrollMode != OVER_SCROLL_ALWAYS &&
16813                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
16814                overScrollMode != OVER_SCROLL_NEVER) {
16815            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
16816        }
16817        mOverScrollMode = overScrollMode;
16818    }
16819
16820    /**
16821     * Gets a scale factor that determines the distance the view should scroll
16822     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
16823     * @return The vertical scroll scale factor.
16824     * @hide
16825     */
16826    protected float getVerticalScrollFactor() {
16827        if (mVerticalScrollFactor == 0) {
16828            TypedValue outValue = new TypedValue();
16829            if (!mContext.getTheme().resolveAttribute(
16830                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
16831                throw new IllegalStateException(
16832                        "Expected theme to define listPreferredItemHeight.");
16833            }
16834            mVerticalScrollFactor = outValue.getDimension(
16835                    mContext.getResources().getDisplayMetrics());
16836        }
16837        return mVerticalScrollFactor;
16838    }
16839
16840    /**
16841     * Gets a scale factor that determines the distance the view should scroll
16842     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
16843     * @return The horizontal scroll scale factor.
16844     * @hide
16845     */
16846    protected float getHorizontalScrollFactor() {
16847        // TODO: Should use something else.
16848        return getVerticalScrollFactor();
16849    }
16850
16851    /**
16852     * Return the value specifying the text direction or policy that was set with
16853     * {@link #setTextDirection(int)}.
16854     *
16855     * @return the defined text direction. It can be one of:
16856     *
16857     * {@link #TEXT_DIRECTION_INHERIT},
16858     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16859     * {@link #TEXT_DIRECTION_ANY_RTL},
16860     * {@link #TEXT_DIRECTION_LTR},
16861     * {@link #TEXT_DIRECTION_RTL},
16862     * {@link #TEXT_DIRECTION_LOCALE}
16863     *
16864     * @attr ref android.R.styleable#View_textDirection
16865     *
16866     * @hide
16867     */
16868    @ViewDebug.ExportedProperty(category = "text", mapping = {
16869            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
16870            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
16871            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
16872            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
16873            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
16874            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
16875    })
16876    public int getRawTextDirection() {
16877        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT;
16878    }
16879
16880    /**
16881     * Set the text direction.
16882     *
16883     * @param textDirection the direction to set. Should be one of:
16884     *
16885     * {@link #TEXT_DIRECTION_INHERIT},
16886     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16887     * {@link #TEXT_DIRECTION_ANY_RTL},
16888     * {@link #TEXT_DIRECTION_LTR},
16889     * {@link #TEXT_DIRECTION_RTL},
16890     * {@link #TEXT_DIRECTION_LOCALE}
16891     *
16892     * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution
16893     * proceeds up the parent chain of the view to get the value. If there is no parent, then it will
16894     * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}.
16895     *
16896     * @attr ref android.R.styleable#View_textDirection
16897     */
16898    public void setTextDirection(int textDirection) {
16899        if (getRawTextDirection() != textDirection) {
16900            // Reset the current text direction and the resolved one
16901            mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
16902            resetResolvedTextDirection();
16903            // Set the new text direction
16904            mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK);
16905            // Do resolution
16906            resolveTextDirection();
16907            // Notify change
16908            onRtlPropertiesChanged(getLayoutDirection());
16909            // Refresh
16910            requestLayout();
16911            invalidate(true);
16912        }
16913    }
16914
16915    /**
16916     * Return the resolved text direction.
16917     *
16918     * @return the resolved text direction. Returns one of:
16919     *
16920     * {@link #TEXT_DIRECTION_FIRST_STRONG}
16921     * {@link #TEXT_DIRECTION_ANY_RTL},
16922     * {@link #TEXT_DIRECTION_LTR},
16923     * {@link #TEXT_DIRECTION_RTL},
16924     * {@link #TEXT_DIRECTION_LOCALE}
16925     *
16926     * @attr ref android.R.styleable#View_textDirection
16927     */
16928    public int getTextDirection() {
16929        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT;
16930    }
16931
16932    /**
16933     * Resolve the text direction.
16934     *
16935     * @return true if resolution has been done, false otherwise.
16936     *
16937     * @hide
16938     */
16939    public boolean resolveTextDirection() {
16940        // Reset any previous text direction resolution
16941        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
16942
16943        if (hasRtlSupport()) {
16944            // Set resolved text direction flag depending on text direction flag
16945            final int textDirection = getRawTextDirection();
16946            switch(textDirection) {
16947                case TEXT_DIRECTION_INHERIT:
16948                    if (!canResolveTextDirection()) {
16949                        // We cannot do the resolution if there is no parent, so use the default one
16950                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16951                        // Resolution will need to happen again later
16952                        return false;
16953                    }
16954
16955                    // Parent has not yet resolved, so we still return the default
16956                    if (!mParent.isTextDirectionResolved()) {
16957                        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16958                        // Resolution will need to happen again later
16959                        return false;
16960                    }
16961
16962                    // Set current resolved direction to the same value as the parent's one
16963                    final int parentResolvedDirection = mParent.getTextDirection();
16964                    switch (parentResolvedDirection) {
16965                        case TEXT_DIRECTION_FIRST_STRONG:
16966                        case TEXT_DIRECTION_ANY_RTL:
16967                        case TEXT_DIRECTION_LTR:
16968                        case TEXT_DIRECTION_RTL:
16969                        case TEXT_DIRECTION_LOCALE:
16970                            mPrivateFlags2 |=
16971                                    (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16972                            break;
16973                        default:
16974                            // Default resolved direction is "first strong" heuristic
16975                            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16976                    }
16977                    break;
16978                case TEXT_DIRECTION_FIRST_STRONG:
16979                case TEXT_DIRECTION_ANY_RTL:
16980                case TEXT_DIRECTION_LTR:
16981                case TEXT_DIRECTION_RTL:
16982                case TEXT_DIRECTION_LOCALE:
16983                    // Resolved direction is the same as text direction
16984                    mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT);
16985                    break;
16986                default:
16987                    // Default resolved direction is "first strong" heuristic
16988                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16989            }
16990        } else {
16991            // Default resolved direction is "first strong" heuristic
16992            mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
16993        }
16994
16995        // Set to resolved
16996        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED;
16997        return true;
16998    }
16999
17000    /**
17001     * Check if text direction resolution can be done.
17002     *
17003     * @return true if text direction resolution can be done otherwise return false.
17004     *
17005     * @hide
17006     */
17007    public boolean canResolveTextDirection() {
17008        switch (getRawTextDirection()) {
17009            case TEXT_DIRECTION_INHERIT:
17010                return (mParent != null) && mParent.canResolveTextDirection();
17011            default:
17012                return true;
17013        }
17014    }
17015
17016    /**
17017     * Reset resolved text direction. Text direction will be resolved during a call to
17018     * {@link #onMeasure(int, int)}.
17019     *
17020     * @hide
17021     */
17022    public void resetResolvedTextDirection() {
17023        // Reset any previous text direction resolution
17024        mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK);
17025        // Set to default value
17026        mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT;
17027    }
17028
17029    /**
17030     * @return true if text direction is inherited.
17031     *
17032     * @hide
17033     */
17034    public boolean isTextDirectionInherited() {
17035        return (getRawTextDirection() == TEXT_DIRECTION_INHERIT);
17036    }
17037
17038    /**
17039     * @return true if text direction is resolved.
17040     *
17041     * @hide
17042     */
17043    public boolean isTextDirectionResolved() {
17044        return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED;
17045    }
17046
17047    /**
17048     * Return the value specifying the text alignment or policy that was set with
17049     * {@link #setTextAlignment(int)}.
17050     *
17051     * @return the defined text alignment. It can be one of:
17052     *
17053     * {@link #TEXT_ALIGNMENT_INHERIT},
17054     * {@link #TEXT_ALIGNMENT_GRAVITY},
17055     * {@link #TEXT_ALIGNMENT_CENTER},
17056     * {@link #TEXT_ALIGNMENT_TEXT_START},
17057     * {@link #TEXT_ALIGNMENT_TEXT_END},
17058     * {@link #TEXT_ALIGNMENT_VIEW_START},
17059     * {@link #TEXT_ALIGNMENT_VIEW_END}
17060     *
17061     * @attr ref android.R.styleable#View_textAlignment
17062     *
17063     * @hide
17064     */
17065    @ViewDebug.ExportedProperty(category = "text", mapping = {
17066            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17067            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17068            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17069            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17070            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17071            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17072            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17073    })
17074    public int getRawTextAlignment() {
17075        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT;
17076    }
17077
17078    /**
17079     * Set the text alignment.
17080     *
17081     * @param textAlignment The text alignment to set. Should be one of
17082     *
17083     * {@link #TEXT_ALIGNMENT_INHERIT},
17084     * {@link #TEXT_ALIGNMENT_GRAVITY},
17085     * {@link #TEXT_ALIGNMENT_CENTER},
17086     * {@link #TEXT_ALIGNMENT_TEXT_START},
17087     * {@link #TEXT_ALIGNMENT_TEXT_END},
17088     * {@link #TEXT_ALIGNMENT_VIEW_START},
17089     * {@link #TEXT_ALIGNMENT_VIEW_END}
17090     *
17091     * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution
17092     * proceeds up the parent chain of the view to get the value. If there is no parent, then it
17093     * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}.
17094     *
17095     * @attr ref android.R.styleable#View_textAlignment
17096     */
17097    public void setTextAlignment(int textAlignment) {
17098        if (textAlignment != getRawTextAlignment()) {
17099            // Reset the current and resolved text alignment
17100            mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
17101            resetResolvedTextAlignment();
17102            // Set the new text alignment
17103            mPrivateFlags2 |=
17104                    ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK);
17105            // Do resolution
17106            resolveTextAlignment();
17107            // Notify change
17108            onRtlPropertiesChanged(getLayoutDirection());
17109            // Refresh
17110            requestLayout();
17111            invalidate(true);
17112        }
17113    }
17114
17115    /**
17116     * Return the resolved text alignment.
17117     *
17118     * @return the resolved text alignment. Returns one of:
17119     *
17120     * {@link #TEXT_ALIGNMENT_GRAVITY},
17121     * {@link #TEXT_ALIGNMENT_CENTER},
17122     * {@link #TEXT_ALIGNMENT_TEXT_START},
17123     * {@link #TEXT_ALIGNMENT_TEXT_END},
17124     * {@link #TEXT_ALIGNMENT_VIEW_START},
17125     * {@link #TEXT_ALIGNMENT_VIEW_END}
17126     *
17127     * @attr ref android.R.styleable#View_textAlignment
17128     */
17129    @ViewDebug.ExportedProperty(category = "text", mapping = {
17130            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"),
17131            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"),
17132            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"),
17133            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"),
17134            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"),
17135            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"),
17136            @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END")
17137    })
17138    public int getTextAlignment() {
17139        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >>
17140                PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT;
17141    }
17142
17143    /**
17144     * Resolve the text alignment.
17145     *
17146     * @return true if resolution has been done, false otherwise.
17147     *
17148     * @hide
17149     */
17150    public boolean resolveTextAlignment() {
17151        // Reset any previous text alignment resolution
17152        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17153
17154        if (hasRtlSupport()) {
17155            // Set resolved text alignment flag depending on text alignment flag
17156            final int textAlignment = getRawTextAlignment();
17157            switch (textAlignment) {
17158                case TEXT_ALIGNMENT_INHERIT:
17159                    // Check if we can resolve the text alignment
17160                    if (!canResolveTextAlignment()) {
17161                        // We cannot do the resolution if there is no parent so use the default
17162                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17163                        // Resolution will need to happen again later
17164                        return false;
17165                    }
17166
17167                    // Parent has not yet resolved, so we still return the default
17168                    if (!mParent.isTextAlignmentResolved()) {
17169                        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17170                        // Resolution will need to happen again later
17171                        return false;
17172                    }
17173
17174                    final int parentResolvedTextAlignment = mParent.getTextAlignment();
17175                    switch (parentResolvedTextAlignment) {
17176                        case TEXT_ALIGNMENT_GRAVITY:
17177                        case TEXT_ALIGNMENT_TEXT_START:
17178                        case TEXT_ALIGNMENT_TEXT_END:
17179                        case TEXT_ALIGNMENT_CENTER:
17180                        case TEXT_ALIGNMENT_VIEW_START:
17181                        case TEXT_ALIGNMENT_VIEW_END:
17182                            // Resolved text alignment is the same as the parent resolved
17183                            // text alignment
17184                            mPrivateFlags2 |=
17185                                    (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17186                            break;
17187                        default:
17188                            // Use default resolved text alignment
17189                            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17190                    }
17191                    break;
17192                case TEXT_ALIGNMENT_GRAVITY:
17193                case TEXT_ALIGNMENT_TEXT_START:
17194                case TEXT_ALIGNMENT_TEXT_END:
17195                case TEXT_ALIGNMENT_CENTER:
17196                case TEXT_ALIGNMENT_VIEW_START:
17197                case TEXT_ALIGNMENT_VIEW_END:
17198                    // Resolved text alignment is the same as text alignment
17199                    mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT);
17200                    break;
17201                default:
17202                    // Use default resolved text alignment
17203                    mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17204            }
17205        } else {
17206            // Use default resolved text alignment
17207            mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17208        }
17209
17210        // Set the resolved
17211        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17212        return true;
17213    }
17214
17215    /**
17216     * Check if text alignment resolution can be done.
17217     *
17218     * @return true if text alignment resolution can be done otherwise return false.
17219     *
17220     * @hide
17221     */
17222    public boolean canResolveTextAlignment() {
17223        switch (getRawTextAlignment()) {
17224            case TEXT_DIRECTION_INHERIT:
17225                return (mParent != null) && mParent.canResolveTextAlignment();
17226            default:
17227                return true;
17228        }
17229    }
17230
17231    /**
17232     * Reset resolved text alignment. Text alignment will be resolved during a call to
17233     * {@link #onMeasure(int, int)}.
17234     *
17235     * @hide
17236     */
17237    public void resetResolvedTextAlignment() {
17238        // Reset any previous text alignment resolution
17239        mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK);
17240        // Set to default
17241        mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT;
17242    }
17243
17244    /**
17245     * @return true if text alignment is inherited.
17246     *
17247     * @hide
17248     */
17249    public boolean isTextAlignmentInherited() {
17250        return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT);
17251    }
17252
17253    /**
17254     * @return true if text alignment is resolved.
17255     *
17256     * @hide
17257     */
17258    public boolean isTextAlignmentResolved() {
17259        return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED;
17260    }
17261
17262    /**
17263     * Generate a value suitable for use in {@link #setId(int)}.
17264     * This value will not collide with ID values generated at build time by aapt for R.id.
17265     *
17266     * @return a generated ID value
17267     */
17268    public static int generateViewId() {
17269        for (;;) {
17270            final int result = sNextGeneratedId.get();
17271            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
17272            int newValue = result + 1;
17273            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
17274            if (sNextGeneratedId.compareAndSet(result, newValue)) {
17275                return result;
17276            }
17277        }
17278    }
17279
17280    //
17281    // Properties
17282    //
17283    /**
17284     * A Property wrapper around the <code>alpha</code> functionality handled by the
17285     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
17286     */
17287    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
17288        @Override
17289        public void setValue(View object, float value) {
17290            object.setAlpha(value);
17291        }
17292
17293        @Override
17294        public Float get(View object) {
17295            return object.getAlpha();
17296        }
17297    };
17298
17299    /**
17300     * A Property wrapper around the <code>translationX</code> functionality handled by the
17301     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
17302     */
17303    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
17304        @Override
17305        public void setValue(View object, float value) {
17306            object.setTranslationX(value);
17307        }
17308
17309                @Override
17310        public Float get(View object) {
17311            return object.getTranslationX();
17312        }
17313    };
17314
17315    /**
17316     * A Property wrapper around the <code>translationY</code> functionality handled by the
17317     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
17318     */
17319    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
17320        @Override
17321        public void setValue(View object, float value) {
17322            object.setTranslationY(value);
17323        }
17324
17325        @Override
17326        public Float get(View object) {
17327            return object.getTranslationY();
17328        }
17329    };
17330
17331    /**
17332     * A Property wrapper around the <code>x</code> functionality handled by the
17333     * {@link View#setX(float)} and {@link View#getX()} methods.
17334     */
17335    public static final Property<View, Float> X = new FloatProperty<View>("x") {
17336        @Override
17337        public void setValue(View object, float value) {
17338            object.setX(value);
17339        }
17340
17341        @Override
17342        public Float get(View object) {
17343            return object.getX();
17344        }
17345    };
17346
17347    /**
17348     * A Property wrapper around the <code>y</code> functionality handled by the
17349     * {@link View#setY(float)} and {@link View#getY()} methods.
17350     */
17351    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
17352        @Override
17353        public void setValue(View object, float value) {
17354            object.setY(value);
17355        }
17356
17357        @Override
17358        public Float get(View object) {
17359            return object.getY();
17360        }
17361    };
17362
17363    /**
17364     * A Property wrapper around the <code>rotation</code> functionality handled by the
17365     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
17366     */
17367    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
17368        @Override
17369        public void setValue(View object, float value) {
17370            object.setRotation(value);
17371        }
17372
17373        @Override
17374        public Float get(View object) {
17375            return object.getRotation();
17376        }
17377    };
17378
17379    /**
17380     * A Property wrapper around the <code>rotationX</code> functionality handled by the
17381     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
17382     */
17383    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
17384        @Override
17385        public void setValue(View object, float value) {
17386            object.setRotationX(value);
17387        }
17388
17389        @Override
17390        public Float get(View object) {
17391            return object.getRotationX();
17392        }
17393    };
17394
17395    /**
17396     * A Property wrapper around the <code>rotationY</code> functionality handled by the
17397     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
17398     */
17399    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
17400        @Override
17401        public void setValue(View object, float value) {
17402            object.setRotationY(value);
17403        }
17404
17405        @Override
17406        public Float get(View object) {
17407            return object.getRotationY();
17408        }
17409    };
17410
17411    /**
17412     * A Property wrapper around the <code>scaleX</code> functionality handled by the
17413     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
17414     */
17415    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
17416        @Override
17417        public void setValue(View object, float value) {
17418            object.setScaleX(value);
17419        }
17420
17421        @Override
17422        public Float get(View object) {
17423            return object.getScaleX();
17424        }
17425    };
17426
17427    /**
17428     * A Property wrapper around the <code>scaleY</code> functionality handled by the
17429     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
17430     */
17431    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
17432        @Override
17433        public void setValue(View object, float value) {
17434            object.setScaleY(value);
17435        }
17436
17437        @Override
17438        public Float get(View object) {
17439            return object.getScaleY();
17440        }
17441    };
17442
17443    /**
17444     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
17445     * Each MeasureSpec represents a requirement for either the width or the height.
17446     * A MeasureSpec is comprised of a size and a mode. There are three possible
17447     * modes:
17448     * <dl>
17449     * <dt>UNSPECIFIED</dt>
17450     * <dd>
17451     * The parent has not imposed any constraint on the child. It can be whatever size
17452     * it wants.
17453     * </dd>
17454     *
17455     * <dt>EXACTLY</dt>
17456     * <dd>
17457     * The parent has determined an exact size for the child. The child is going to be
17458     * given those bounds regardless of how big it wants to be.
17459     * </dd>
17460     *
17461     * <dt>AT_MOST</dt>
17462     * <dd>
17463     * The child can be as large as it wants up to the specified size.
17464     * </dd>
17465     * </dl>
17466     *
17467     * MeasureSpecs are implemented as ints to reduce object allocation. This class
17468     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
17469     */
17470    public static class MeasureSpec {
17471        private static final int MODE_SHIFT = 30;
17472        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
17473
17474        /**
17475         * Measure specification mode: The parent has not imposed any constraint
17476         * on the child. It can be whatever size it wants.
17477         */
17478        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
17479
17480        /**
17481         * Measure specification mode: The parent has determined an exact size
17482         * for the child. The child is going to be given those bounds regardless
17483         * of how big it wants to be.
17484         */
17485        public static final int EXACTLY     = 1 << MODE_SHIFT;
17486
17487        /**
17488         * Measure specification mode: The child can be as large as it wants up
17489         * to the specified size.
17490         */
17491        public static final int AT_MOST     = 2 << MODE_SHIFT;
17492
17493        /**
17494         * Creates a measure specification based on the supplied size and mode.
17495         *
17496         * The mode must always be one of the following:
17497         * <ul>
17498         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
17499         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
17500         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
17501         * </ul>
17502         *
17503         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
17504         * implementation was such that the order of arguments did not matter
17505         * and overflow in either value could impact the resulting MeasureSpec.
17506         * {@link android.widget.RelativeLayout} was affected by this bug.
17507         * Apps targeting API levels greater than 17 will get the fixed, more strict
17508         * behavior.</p>
17509         *
17510         * @param size the size of the measure specification
17511         * @param mode the mode of the measure specification
17512         * @return the measure specification based on size and mode
17513         */
17514        public static int makeMeasureSpec(int size, int mode) {
17515            if (sUseBrokenMakeMeasureSpec) {
17516                return size + mode;
17517            } else {
17518                return (size & ~MODE_MASK) | (mode & MODE_MASK);
17519            }
17520        }
17521
17522        /**
17523         * Extracts the mode from the supplied measure specification.
17524         *
17525         * @param measureSpec the measure specification to extract the mode from
17526         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
17527         *         {@link android.view.View.MeasureSpec#AT_MOST} or
17528         *         {@link android.view.View.MeasureSpec#EXACTLY}
17529         */
17530        public static int getMode(int measureSpec) {
17531            return (measureSpec & MODE_MASK);
17532        }
17533
17534        /**
17535         * Extracts the size from the supplied measure specification.
17536         *
17537         * @param measureSpec the measure specification to extract the size from
17538         * @return the size in pixels defined in the supplied measure specification
17539         */
17540        public static int getSize(int measureSpec) {
17541            return (measureSpec & ~MODE_MASK);
17542        }
17543
17544        static int adjust(int measureSpec, int delta) {
17545            return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec));
17546        }
17547
17548        /**
17549         * Returns a String representation of the specified measure
17550         * specification.
17551         *
17552         * @param measureSpec the measure specification to convert to a String
17553         * @return a String with the following format: "MeasureSpec: MODE SIZE"
17554         */
17555        public static String toString(int measureSpec) {
17556            int mode = getMode(measureSpec);
17557            int size = getSize(measureSpec);
17558
17559            StringBuilder sb = new StringBuilder("MeasureSpec: ");
17560
17561            if (mode == UNSPECIFIED)
17562                sb.append("UNSPECIFIED ");
17563            else if (mode == EXACTLY)
17564                sb.append("EXACTLY ");
17565            else if (mode == AT_MOST)
17566                sb.append("AT_MOST ");
17567            else
17568                sb.append(mode).append(" ");
17569
17570            sb.append(size);
17571            return sb.toString();
17572        }
17573    }
17574
17575    class CheckForLongPress implements Runnable {
17576
17577        private int mOriginalWindowAttachCount;
17578
17579        public void run() {
17580            if (isPressed() && (mParent != null)
17581                    && mOriginalWindowAttachCount == mWindowAttachCount) {
17582                if (performLongClick()) {
17583                    mHasPerformedLongPress = true;
17584                }
17585            }
17586        }
17587
17588        public void rememberWindowAttachCount() {
17589            mOriginalWindowAttachCount = mWindowAttachCount;
17590        }
17591    }
17592
17593    private final class CheckForTap implements Runnable {
17594        public void run() {
17595            mPrivateFlags &= ~PFLAG_PREPRESSED;
17596            setPressed(true);
17597            checkForLongClick(ViewConfiguration.getTapTimeout());
17598        }
17599    }
17600
17601    private final class PerformClick implements Runnable {
17602        public void run() {
17603            performClick();
17604        }
17605    }
17606
17607    /** @hide */
17608    public void hackTurnOffWindowResizeAnim(boolean off) {
17609        mAttachInfo.mTurnOffWindowResizeAnim = off;
17610    }
17611
17612    /**
17613     * This method returns a ViewPropertyAnimator object, which can be used to animate
17614     * specific properties on this View.
17615     *
17616     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
17617     */
17618    public ViewPropertyAnimator animate() {
17619        if (mAnimator == null) {
17620            mAnimator = new ViewPropertyAnimator(this);
17621        }
17622        return mAnimator;
17623    }
17624
17625    /**
17626     * Interface definition for a callback to be invoked when a hardware key event is
17627     * dispatched to this view. The callback will be invoked before the key event is
17628     * given to the view. This is only useful for hardware keyboards; a software input
17629     * method has no obligation to trigger this listener.
17630     */
17631    public interface OnKeyListener {
17632        /**
17633         * Called when a hardware key is dispatched to a view. This allows listeners to
17634         * get a chance to respond before the target view.
17635         * <p>Key presses in software keyboards will generally NOT trigger this method,
17636         * although some may elect to do so in some situations. Do not assume a
17637         * software input method has to be key-based; even if it is, it may use key presses
17638         * in a different way than you expect, so there is no way to reliably catch soft
17639         * input key presses.
17640         *
17641         * @param v The view the key has been dispatched to.
17642         * @param keyCode The code for the physical key that was pressed
17643         * @param event The KeyEvent object containing full information about
17644         *        the event.
17645         * @return True if the listener has consumed the event, false otherwise.
17646         */
17647        boolean onKey(View v, int keyCode, KeyEvent event);
17648    }
17649
17650    /**
17651     * Interface definition for a callback to be invoked when a touch event is
17652     * dispatched to this view. The callback will be invoked before the touch
17653     * event is given to the view.
17654     */
17655    public interface OnTouchListener {
17656        /**
17657         * Called when a touch event is dispatched to a view. This allows listeners to
17658         * get a chance to respond before the target view.
17659         *
17660         * @param v The view the touch event has been dispatched to.
17661         * @param event The MotionEvent object containing full information about
17662         *        the event.
17663         * @return True if the listener has consumed the event, false otherwise.
17664         */
17665        boolean onTouch(View v, MotionEvent event);
17666    }
17667
17668    /**
17669     * Interface definition for a callback to be invoked when a hover event is
17670     * dispatched to this view. The callback will be invoked before the hover
17671     * event is given to the view.
17672     */
17673    public interface OnHoverListener {
17674        /**
17675         * Called when a hover event is dispatched to a view. This allows listeners to
17676         * get a chance to respond before the target view.
17677         *
17678         * @param v The view the hover event has been dispatched to.
17679         * @param event The MotionEvent object containing full information about
17680         *        the event.
17681         * @return True if the listener has consumed the event, false otherwise.
17682         */
17683        boolean onHover(View v, MotionEvent event);
17684    }
17685
17686    /**
17687     * Interface definition for a callback to be invoked when a generic motion event is
17688     * dispatched to this view. The callback will be invoked before the generic motion
17689     * event is given to the view.
17690     */
17691    public interface OnGenericMotionListener {
17692        /**
17693         * Called when a generic motion event is dispatched to a view. This allows listeners to
17694         * get a chance to respond before the target view.
17695         *
17696         * @param v The view the generic motion event has been dispatched to.
17697         * @param event The MotionEvent object containing full information about
17698         *        the event.
17699         * @return True if the listener has consumed the event, false otherwise.
17700         */
17701        boolean onGenericMotion(View v, MotionEvent event);
17702    }
17703
17704    /**
17705     * Interface definition for a callback to be invoked when a view has been clicked and held.
17706     */
17707    public interface OnLongClickListener {
17708        /**
17709         * Called when a view has been clicked and held.
17710         *
17711         * @param v The view that was clicked and held.
17712         *
17713         * @return true if the callback consumed the long click, false otherwise.
17714         */
17715        boolean onLongClick(View v);
17716    }
17717
17718    /**
17719     * Interface definition for a callback to be invoked when a drag is being dispatched
17720     * to this view.  The callback will be invoked before the hosting view's own
17721     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
17722     * onDrag(event) behavior, it should return 'false' from this callback.
17723     *
17724     * <div class="special reference">
17725     * <h3>Developer Guides</h3>
17726     * <p>For a guide to implementing drag and drop features, read the
17727     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
17728     * </div>
17729     */
17730    public interface OnDragListener {
17731        /**
17732         * Called when a drag event is dispatched to a view. This allows listeners
17733         * to get a chance to override base View behavior.
17734         *
17735         * @param v The View that received the drag event.
17736         * @param event The {@link android.view.DragEvent} object for the drag event.
17737         * @return {@code true} if the drag event was handled successfully, or {@code false}
17738         * if the drag event was not handled. Note that {@code false} will trigger the View
17739         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
17740         */
17741        boolean onDrag(View v, DragEvent event);
17742    }
17743
17744    /**
17745     * Interface definition for a callback to be invoked when the focus state of
17746     * a view changed.
17747     */
17748    public interface OnFocusChangeListener {
17749        /**
17750         * Called when the focus state of a view has changed.
17751         *
17752         * @param v The view whose state has changed.
17753         * @param hasFocus The new focus state of v.
17754         */
17755        void onFocusChange(View v, boolean hasFocus);
17756    }
17757
17758    /**
17759     * Interface definition for a callback to be invoked when a view is clicked.
17760     */
17761    public interface OnClickListener {
17762        /**
17763         * Called when a view has been clicked.
17764         *
17765         * @param v The view that was clicked.
17766         */
17767        void onClick(View v);
17768    }
17769
17770    /**
17771     * Interface definition for a callback to be invoked when the context menu
17772     * for this view is being built.
17773     */
17774    public interface OnCreateContextMenuListener {
17775        /**
17776         * Called when the context menu for this view is being built. It is not
17777         * safe to hold onto the menu after this method returns.
17778         *
17779         * @param menu The context menu that is being built
17780         * @param v The view for which the context menu is being built
17781         * @param menuInfo Extra information about the item for which the
17782         *            context menu should be shown. This information will vary
17783         *            depending on the class of v.
17784         */
17785        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
17786    }
17787
17788    /**
17789     * Interface definition for a callback to be invoked when the status bar changes
17790     * visibility.  This reports <strong>global</strong> changes to the system UI
17791     * state, not what the application is requesting.
17792     *
17793     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
17794     */
17795    public interface OnSystemUiVisibilityChangeListener {
17796        /**
17797         * Called when the status bar changes visibility because of a call to
17798         * {@link View#setSystemUiVisibility(int)}.
17799         *
17800         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE},
17801         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}.
17802         * This tells you the <strong>global</strong> state of these UI visibility
17803         * flags, not what your app is currently applying.
17804         */
17805        public void onSystemUiVisibilityChange(int visibility);
17806    }
17807
17808    /**
17809     * Interface definition for a callback to be invoked when this view is attached
17810     * or detached from its window.
17811     */
17812    public interface OnAttachStateChangeListener {
17813        /**
17814         * Called when the view is attached to a window.
17815         * @param v The view that was attached
17816         */
17817        public void onViewAttachedToWindow(View v);
17818        /**
17819         * Called when the view is detached from a window.
17820         * @param v The view that was detached
17821         */
17822        public void onViewDetachedFromWindow(View v);
17823    }
17824
17825    private final class UnsetPressedState implements Runnable {
17826        public void run() {
17827            setPressed(false);
17828        }
17829    }
17830
17831    /**
17832     * Base class for derived classes that want to save and restore their own
17833     * state in {@link android.view.View#onSaveInstanceState()}.
17834     */
17835    public static class BaseSavedState extends AbsSavedState {
17836        /**
17837         * Constructor used when reading from a parcel. Reads the state of the superclass.
17838         *
17839         * @param source
17840         */
17841        public BaseSavedState(Parcel source) {
17842            super(source);
17843        }
17844
17845        /**
17846         * Constructor called by derived classes when creating their SavedState objects
17847         *
17848         * @param superState The state of the superclass of this view
17849         */
17850        public BaseSavedState(Parcelable superState) {
17851            super(superState);
17852        }
17853
17854        public static final Parcelable.Creator<BaseSavedState> CREATOR =
17855                new Parcelable.Creator<BaseSavedState>() {
17856            public BaseSavedState createFromParcel(Parcel in) {
17857                return new BaseSavedState(in);
17858            }
17859
17860            public BaseSavedState[] newArray(int size) {
17861                return new BaseSavedState[size];
17862            }
17863        };
17864    }
17865
17866    /**
17867     * A set of information given to a view when it is attached to its parent
17868     * window.
17869     */
17870    static class AttachInfo {
17871        interface Callbacks {
17872            void playSoundEffect(int effectId);
17873            boolean performHapticFeedback(int effectId, boolean always);
17874        }
17875
17876        /**
17877         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
17878         * to a Handler. This class contains the target (View) to invalidate and
17879         * the coordinates of the dirty rectangle.
17880         *
17881         * For performance purposes, this class also implements a pool of up to
17882         * POOL_LIMIT objects that get reused. This reduces memory allocations
17883         * whenever possible.
17884         */
17885        static class InvalidateInfo {
17886            private static final int POOL_LIMIT = 10;
17887
17888            private static final SynchronizedPool<InvalidateInfo> sPool =
17889                    new SynchronizedPool<InvalidateInfo>(POOL_LIMIT);
17890
17891            View target;
17892
17893            int left;
17894            int top;
17895            int right;
17896            int bottom;
17897
17898            public static InvalidateInfo obtain() {
17899                InvalidateInfo instance = sPool.acquire();
17900                return (instance != null) ? instance : new InvalidateInfo();
17901            }
17902
17903            public void recycle() {
17904                target = null;
17905                sPool.release(this);
17906            }
17907        }
17908
17909        final IWindowSession mSession;
17910
17911        final IWindow mWindow;
17912
17913        final IBinder mWindowToken;
17914
17915        final Display mDisplay;
17916
17917        final Callbacks mRootCallbacks;
17918
17919        HardwareCanvas mHardwareCanvas;
17920
17921        IWindowId mIWindowId;
17922        WindowId mWindowId;
17923
17924        /**
17925         * The top view of the hierarchy.
17926         */
17927        View mRootView;
17928
17929        IBinder mPanelParentWindowToken;
17930        Surface mSurface;
17931
17932        boolean mHardwareAccelerated;
17933        boolean mHardwareAccelerationRequested;
17934        HardwareRenderer mHardwareRenderer;
17935
17936        boolean mScreenOn;
17937
17938        /**
17939         * Scale factor used by the compatibility mode
17940         */
17941        float mApplicationScale;
17942
17943        /**
17944         * Indicates whether the application is in compatibility mode
17945         */
17946        boolean mScalingRequired;
17947
17948        /**
17949         * If set, ViewRootImpl doesn't use its lame animation for when the window resizes.
17950         */
17951        boolean mTurnOffWindowResizeAnim;
17952
17953        /**
17954         * Left position of this view's window
17955         */
17956        int mWindowLeft;
17957
17958        /**
17959         * Top position of this view's window
17960         */
17961        int mWindowTop;
17962
17963        /**
17964         * Indicates whether views need to use 32-bit drawing caches
17965         */
17966        boolean mUse32BitDrawingCache;
17967
17968        /**
17969         * For windows that are full-screen but using insets to layout inside
17970         * of the screen areas, these are the current insets to appear inside
17971         * the overscan area of the display.
17972         */
17973        final Rect mOverscanInsets = new Rect();
17974
17975        /**
17976         * For windows that are full-screen but using insets to layout inside
17977         * of the screen decorations, these are the current insets for the
17978         * content of the window.
17979         */
17980        final Rect mContentInsets = new Rect();
17981
17982        /**
17983         * For windows that are full-screen but using insets to layout inside
17984         * of the screen decorations, these are the current insets for the
17985         * actual visible parts of the window.
17986         */
17987        final Rect mVisibleInsets = new Rect();
17988
17989        /**
17990         * The internal insets given by this window.  This value is
17991         * supplied by the client (through
17992         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
17993         * be given to the window manager when changed to be used in laying
17994         * out windows behind it.
17995         */
17996        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
17997                = new ViewTreeObserver.InternalInsetsInfo();
17998
17999        /**
18000         * All views in the window's hierarchy that serve as scroll containers,
18001         * used to determine if the window can be resized or must be panned
18002         * to adjust for a soft input area.
18003         */
18004        final ArrayList<View> mScrollContainers = new ArrayList<View>();
18005
18006        final KeyEvent.DispatcherState mKeyDispatchState
18007                = new KeyEvent.DispatcherState();
18008
18009        /**
18010         * Indicates whether the view's window currently has the focus.
18011         */
18012        boolean mHasWindowFocus;
18013
18014        /**
18015         * The current visibility of the window.
18016         */
18017        int mWindowVisibility;
18018
18019        /**
18020         * Indicates the time at which drawing started to occur.
18021         */
18022        long mDrawingTime;
18023
18024        /**
18025         * Indicates whether or not ignoring the DIRTY_MASK flags.
18026         */
18027        boolean mIgnoreDirtyState;
18028
18029        /**
18030         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
18031         * to avoid clearing that flag prematurely.
18032         */
18033        boolean mSetIgnoreDirtyState = false;
18034
18035        /**
18036         * Indicates whether the view's window is currently in touch mode.
18037         */
18038        boolean mInTouchMode;
18039
18040        /**
18041         * Indicates that ViewAncestor should trigger a global layout change
18042         * the next time it performs a traversal
18043         */
18044        boolean mRecomputeGlobalAttributes;
18045
18046        /**
18047         * Always report new attributes at next traversal.
18048         */
18049        boolean mForceReportNewAttributes;
18050
18051        /**
18052         * Set during a traveral if any views want to keep the screen on.
18053         */
18054        boolean mKeepScreenOn;
18055
18056        /**
18057         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
18058         */
18059        int mSystemUiVisibility;
18060
18061        /**
18062         * Hack to force certain system UI visibility flags to be cleared.
18063         */
18064        int mDisabledSystemUiVisibility;
18065
18066        /**
18067         * Last global system UI visibility reported by the window manager.
18068         */
18069        int mGlobalSystemUiVisibility;
18070
18071        /**
18072         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
18073         * attached.
18074         */
18075        boolean mHasSystemUiListeners;
18076
18077        /**
18078         * Set if the window has requested to extend into the overscan region
18079         * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN.
18080         */
18081        boolean mOverscanRequested;
18082
18083        /**
18084         * Set if the visibility of any views has changed.
18085         */
18086        boolean mViewVisibilityChanged;
18087
18088        /**
18089         * Set to true if a view has been scrolled.
18090         */
18091        boolean mViewScrollChanged;
18092
18093        /**
18094         * Global to the view hierarchy used as a temporary for dealing with
18095         * x/y points in the transparent region computations.
18096         */
18097        final int[] mTransparentLocation = new int[2];
18098
18099        /**
18100         * Global to the view hierarchy used as a temporary for dealing with
18101         * x/y points in the ViewGroup.invalidateChild implementation.
18102         */
18103        final int[] mInvalidateChildLocation = new int[2];
18104
18105
18106        /**
18107         * Global to the view hierarchy used as a temporary for dealing with
18108         * x/y location when view is transformed.
18109         */
18110        final float[] mTmpTransformLocation = new float[2];
18111
18112        /**
18113         * The view tree observer used to dispatch global events like
18114         * layout, pre-draw, touch mode change, etc.
18115         */
18116        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
18117
18118        /**
18119         * A Canvas used by the view hierarchy to perform bitmap caching.
18120         */
18121        Canvas mCanvas;
18122
18123        /**
18124         * The view root impl.
18125         */
18126        final ViewRootImpl mViewRootImpl;
18127
18128        /**
18129         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
18130         * handler can be used to pump events in the UI events queue.
18131         */
18132        final Handler mHandler;
18133
18134        /**
18135         * Temporary for use in computing invalidate rectangles while
18136         * calling up the hierarchy.
18137         */
18138        final Rect mTmpInvalRect = new Rect();
18139
18140        /**
18141         * Temporary for use in computing hit areas with transformed views
18142         */
18143        final RectF mTmpTransformRect = new RectF();
18144
18145        /**
18146         * Temporary for use in transforming invalidation rect
18147         */
18148        final Matrix mTmpMatrix = new Matrix();
18149
18150        /**
18151         * Temporary for use in transforming invalidation rect
18152         */
18153        final Transformation mTmpTransformation = new Transformation();
18154
18155        /**
18156         * Temporary list for use in collecting focusable descendents of a view.
18157         */
18158        final ArrayList<View> mTempArrayList = new ArrayList<View>(24);
18159
18160        /**
18161         * The id of the window for accessibility purposes.
18162         */
18163        int mAccessibilityWindowId = View.NO_ID;
18164
18165        /**
18166         * Flags related to accessibility processing.
18167         *
18168         * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
18169         * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS
18170         */
18171        int mAccessibilityFetchFlags;
18172
18173        /**
18174         * The drawable for highlighting accessibility focus.
18175         */
18176        Drawable mAccessibilityFocusDrawable;
18177
18178        /**
18179         * Show where the margins, bounds and layout bounds are for each view.
18180         */
18181        boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false);
18182
18183        /**
18184         * Point used to compute visible regions.
18185         */
18186        final Point mPoint = new Point();
18187
18188        /**
18189         * Used to track which View originated a requestLayout() call, used when
18190         * requestLayout() is called during layout.
18191         */
18192        View mViewRequestingLayout;
18193
18194        /**
18195         * Creates a new set of attachment information with the specified
18196         * events handler and thread.
18197         *
18198         * @param handler the events handler the view must use
18199         */
18200        AttachInfo(IWindowSession session, IWindow window, Display display,
18201                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
18202            mSession = session;
18203            mWindow = window;
18204            mWindowToken = window.asBinder();
18205            mDisplay = display;
18206            mViewRootImpl = viewRootImpl;
18207            mHandler = handler;
18208            mRootCallbacks = effectPlayer;
18209        }
18210    }
18211
18212    /**
18213     * <p>ScrollabilityCache holds various fields used by a View when scrolling
18214     * is supported. This avoids keeping too many unused fields in most
18215     * instances of View.</p>
18216     */
18217    private static class ScrollabilityCache implements Runnable {
18218
18219        /**
18220         * Scrollbars are not visible
18221         */
18222        public static final int OFF = 0;
18223
18224        /**
18225         * Scrollbars are visible
18226         */
18227        public static final int ON = 1;
18228
18229        /**
18230         * Scrollbars are fading away
18231         */
18232        public static final int FADING = 2;
18233
18234        public boolean fadeScrollBars;
18235
18236        public int fadingEdgeLength;
18237        public int scrollBarDefaultDelayBeforeFade;
18238        public int scrollBarFadeDuration;
18239
18240        public int scrollBarSize;
18241        public ScrollBarDrawable scrollBar;
18242        public float[] interpolatorValues;
18243        public View host;
18244
18245        public final Paint paint;
18246        public final Matrix matrix;
18247        public Shader shader;
18248
18249        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
18250
18251        private static final float[] OPAQUE = { 255 };
18252        private static final float[] TRANSPARENT = { 0.0f };
18253
18254        /**
18255         * When fading should start. This time moves into the future every time
18256         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
18257         */
18258        public long fadeStartTime;
18259
18260
18261        /**
18262         * The current state of the scrollbars: ON, OFF, or FADING
18263         */
18264        public int state = OFF;
18265
18266        private int mLastColor;
18267
18268        public ScrollabilityCache(ViewConfiguration configuration, View host) {
18269            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
18270            scrollBarSize = configuration.getScaledScrollBarSize();
18271            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
18272            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
18273
18274            paint = new Paint();
18275            matrix = new Matrix();
18276            // use use a height of 1, and then wack the matrix each time we
18277            // actually use it.
18278            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18279            paint.setShader(shader);
18280            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18281
18282            this.host = host;
18283        }
18284
18285        public void setFadeColor(int color) {
18286            if (color != mLastColor) {
18287                mLastColor = color;
18288
18289                if (color != 0) {
18290                    shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
18291                            color & 0x00FFFFFF, Shader.TileMode.CLAMP);
18292                    paint.setShader(shader);
18293                    // Restore the default transfer mode (src_over)
18294                    paint.setXfermode(null);
18295                } else {
18296                    shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
18297                    paint.setShader(shader);
18298                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
18299                }
18300            }
18301        }
18302
18303        public void run() {
18304            long now = AnimationUtils.currentAnimationTimeMillis();
18305            if (now >= fadeStartTime) {
18306
18307                // the animation fades the scrollbars out by changing
18308                // the opacity (alpha) from fully opaque to fully
18309                // transparent
18310                int nextFrame = (int) now;
18311                int framesCount = 0;
18312
18313                Interpolator interpolator = scrollBarInterpolator;
18314
18315                // Start opaque
18316                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
18317
18318                // End transparent
18319                nextFrame += scrollBarFadeDuration;
18320                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
18321
18322                state = FADING;
18323
18324                // Kick off the fade animation
18325                host.invalidate(true);
18326            }
18327        }
18328    }
18329
18330    /**
18331     * Resuable callback for sending
18332     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
18333     */
18334    private class SendViewScrolledAccessibilityEvent implements Runnable {
18335        public volatile boolean mIsPending;
18336
18337        public void run() {
18338            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
18339            mIsPending = false;
18340        }
18341    }
18342
18343    /**
18344     * <p>
18345     * This class represents a delegate that can be registered in a {@link View}
18346     * to enhance accessibility support via composition rather via inheritance.
18347     * It is specifically targeted to widget developers that extend basic View
18348     * classes i.e. classes in package android.view, that would like their
18349     * applications to be backwards compatible.
18350     * </p>
18351     * <div class="special reference">
18352     * <h3>Developer Guides</h3>
18353     * <p>For more information about making applications accessible, read the
18354     * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a>
18355     * developer guide.</p>
18356     * </div>
18357     * <p>
18358     * A scenario in which a developer would like to use an accessibility delegate
18359     * is overriding a method introduced in a later API version then the minimal API
18360     * version supported by the application. For example, the method
18361     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
18362     * in API version 4 when the accessibility APIs were first introduced. If a
18363     * developer would like his application to run on API version 4 devices (assuming
18364     * all other APIs used by the application are version 4 or lower) and take advantage
18365     * of this method, instead of overriding the method which would break the application's
18366     * backwards compatibility, he can override the corresponding method in this
18367     * delegate and register the delegate in the target View if the API version of
18368     * the system is high enough i.e. the API version is same or higher to the API
18369     * version that introduced
18370     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
18371     * </p>
18372     * <p>
18373     * Here is an example implementation:
18374     * </p>
18375     * <code><pre><p>
18376     * if (Build.VERSION.SDK_INT >= 14) {
18377     *     // If the API version is equal of higher than the version in
18378     *     // which onInitializeAccessibilityNodeInfo was introduced we
18379     *     // register a delegate with a customized implementation.
18380     *     View view = findViewById(R.id.view_id);
18381     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
18382     *         public void onInitializeAccessibilityNodeInfo(View host,
18383     *                 AccessibilityNodeInfo info) {
18384     *             // Let the default implementation populate the info.
18385     *             super.onInitializeAccessibilityNodeInfo(host, info);
18386     *             // Set some other information.
18387     *             info.setEnabled(host.isEnabled());
18388     *         }
18389     *     });
18390     * }
18391     * </code></pre></p>
18392     * <p>
18393     * This delegate contains methods that correspond to the accessibility methods
18394     * in View. If a delegate has been specified the implementation in View hands
18395     * off handling to the corresponding method in this delegate. The default
18396     * implementation the delegate methods behaves exactly as the corresponding
18397     * method in View for the case of no accessibility delegate been set. Hence,
18398     * to customize the behavior of a View method, clients can override only the
18399     * corresponding delegate method without altering the behavior of the rest
18400     * accessibility related methods of the host view.
18401     * </p>
18402     */
18403    public static class AccessibilityDelegate {
18404
18405        /**
18406         * Sends an accessibility event of the given type. If accessibility is not
18407         * enabled this method has no effect.
18408         * <p>
18409         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
18410         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
18411         * been set.
18412         * </p>
18413         *
18414         * @param host The View hosting the delegate.
18415         * @param eventType The type of the event to send.
18416         *
18417         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
18418         */
18419        public void sendAccessibilityEvent(View host, int eventType) {
18420            host.sendAccessibilityEventInternal(eventType);
18421        }
18422
18423        /**
18424         * Performs the specified accessibility action on the view. For
18425         * possible accessibility actions look at {@link AccessibilityNodeInfo}.
18426         * <p>
18427         * The default implementation behaves as
18428         * {@link View#performAccessibilityAction(int, Bundle)
18429         *  View#performAccessibilityAction(int, Bundle)} for the case of
18430         *  no accessibility delegate been set.
18431         * </p>
18432         *
18433         * @param action The action to perform.
18434         * @return Whether the action was performed.
18435         *
18436         * @see View#performAccessibilityAction(int, Bundle)
18437         *      View#performAccessibilityAction(int, Bundle)
18438         */
18439        public boolean performAccessibilityAction(View host, int action, Bundle args) {
18440            return host.performAccessibilityActionInternal(action, args);
18441        }
18442
18443        /**
18444         * Sends an accessibility event. This method behaves exactly as
18445         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
18446         * empty {@link AccessibilityEvent} and does not perform a check whether
18447         * accessibility is enabled.
18448         * <p>
18449         * The default implementation behaves as
18450         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18451         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
18452         * the case of no accessibility delegate been set.
18453         * </p>
18454         *
18455         * @param host The View hosting the delegate.
18456         * @param event The event to send.
18457         *
18458         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18459         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
18460         */
18461        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
18462            host.sendAccessibilityEventUncheckedInternal(event);
18463        }
18464
18465        /**
18466         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
18467         * to its children for adding their text content to the event.
18468         * <p>
18469         * The default implementation behaves as
18470         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18471         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
18472         * the case of no accessibility delegate been set.
18473         * </p>
18474         *
18475         * @param host The View hosting the delegate.
18476         * @param event The event.
18477         * @return True if the event population was completed.
18478         *
18479         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18480         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
18481         */
18482        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18483            return host.dispatchPopulateAccessibilityEventInternal(event);
18484        }
18485
18486        /**
18487         * Gives a chance to the host View to populate the accessibility event with its
18488         * text content.
18489         * <p>
18490         * The default implementation behaves as
18491         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
18492         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
18493         * the case of no accessibility delegate been set.
18494         * </p>
18495         *
18496         * @param host The View hosting the delegate.
18497         * @param event The accessibility event which to populate.
18498         *
18499         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
18500         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
18501         */
18502        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
18503            host.onPopulateAccessibilityEventInternal(event);
18504        }
18505
18506        /**
18507         * Initializes an {@link AccessibilityEvent} with information about the
18508         * the host View which is the event source.
18509         * <p>
18510         * The default implementation behaves as
18511         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
18512         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
18513         * the case of no accessibility delegate been set.
18514         * </p>
18515         *
18516         * @param host The View hosting the delegate.
18517         * @param event The event to initialize.
18518         *
18519         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
18520         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
18521         */
18522        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
18523            host.onInitializeAccessibilityEventInternal(event);
18524        }
18525
18526        /**
18527         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
18528         * <p>
18529         * The default implementation behaves as
18530         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18531         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
18532         * the case of no accessibility delegate been set.
18533         * </p>
18534         *
18535         * @param host The View hosting the delegate.
18536         * @param info The instance to initialize.
18537         *
18538         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18539         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
18540         */
18541        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
18542            host.onInitializeAccessibilityNodeInfoInternal(info);
18543        }
18544
18545        /**
18546         * Called when a child of the host View has requested sending an
18547         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
18548         * to augment the event.
18549         * <p>
18550         * The default implementation behaves as
18551         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18552         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
18553         * the case of no accessibility delegate been set.
18554         * </p>
18555         *
18556         * @param host The View hosting the delegate.
18557         * @param child The child which requests sending the event.
18558         * @param event The event to be sent.
18559         * @return True if the event should be sent
18560         *
18561         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18562         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
18563         */
18564        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
18565                AccessibilityEvent event) {
18566            return host.onRequestSendAccessibilityEventInternal(child, event);
18567        }
18568
18569        /**
18570         * Gets the provider for managing a virtual view hierarchy rooted at this View
18571         * and reported to {@link android.accessibilityservice.AccessibilityService}s
18572         * that explore the window content.
18573         * <p>
18574         * The default implementation behaves as
18575         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
18576         * the case of no accessibility delegate been set.
18577         * </p>
18578         *
18579         * @return The provider.
18580         *
18581         * @see AccessibilityNodeProvider
18582         */
18583        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
18584            return null;
18585        }
18586    }
18587
18588    private class MatchIdPredicate implements Predicate<View> {
18589        public int mId;
18590
18591        @Override
18592        public boolean apply(View view) {
18593            return (view.mID == mId);
18594        }
18595    }
18596
18597    private class MatchLabelForPredicate implements Predicate<View> {
18598        private int mLabeledId;
18599
18600        @Override
18601        public boolean apply(View view) {
18602            return (view.mLabelForId == mLabeledId);
18603        }
18604    }
18605
18606    /**
18607     * Dump all private flags in readable format, useful for documentation and
18608     * sanity checking.
18609     */
18610    private static void dumpFlags() {
18611        final HashMap<String, String> found = Maps.newHashMap();
18612        try {
18613            for (Field field : View.class.getDeclaredFields()) {
18614                final int modifiers = field.getModifiers();
18615                if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
18616                    if (field.getType().equals(int.class)) {
18617                        final int value = field.getInt(null);
18618                        dumpFlag(found, field.getName(), value);
18619                    } else if (field.getType().equals(int[].class)) {
18620                        final int[] values = (int[]) field.get(null);
18621                        for (int i = 0; i < values.length; i++) {
18622                            dumpFlag(found, field.getName() + "[" + i + "]", values[i]);
18623                        }
18624                    }
18625                }
18626            }
18627        } catch (IllegalAccessException e) {
18628            throw new RuntimeException(e);
18629        }
18630
18631        final ArrayList<String> keys = Lists.newArrayList();
18632        keys.addAll(found.keySet());
18633        Collections.sort(keys);
18634        for (String key : keys) {
18635            Log.d(VIEW_LOG_TAG, found.get(key));
18636        }
18637    }
18638
18639    private static void dumpFlag(HashMap<String, String> found, String name, int value) {
18640        // Sort flags by prefix, then by bits, always keeping unique keys
18641        final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' ');
18642        final int prefix = name.indexOf('_');
18643        final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name;
18644        final String output = bits + " " + name;
18645        found.put(key, output);
18646    }
18647}
18648