View.java revision 2a9fa89643ce796ee6dc7edae2742b291b6c5f40
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.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.text.TextUtils;
49import android.util.AttributeSet;
50import android.util.FloatProperty;
51import android.util.LocaleUtil;
52import android.util.Log;
53import android.util.Pool;
54import android.util.Poolable;
55import android.util.PoolableManager;
56import android.util.Pools;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
64import android.view.accessibility.AccessibilityNodeInfo;
65import android.view.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.inputmethod.EditorInfo;
68import android.view.inputmethod.InputConnection;
69import android.view.inputmethod.InputMethodManager;
70import android.widget.ScrollBarDrawable;
71
72import static android.os.Build.VERSION_CODES.*;
73
74import com.android.internal.R;
75import com.android.internal.util.Predicate;
76import com.android.internal.view.menu.MenuBuilder;
77
78import java.lang.ref.WeakReference;
79import java.lang.reflect.InvocationTargetException;
80import java.lang.reflect.Method;
81import java.util.ArrayList;
82import java.util.Arrays;
83import java.util.Locale;
84import java.util.concurrent.CopyOnWriteArrayList;
85
86/**
87 * <p>
88 * This class represents the basic building block for user interface components. A View
89 * occupies a rectangular area on the screen and is responsible for drawing and
90 * event handling. View is the base class for <em>widgets</em>, which are
91 * used to create interactive UI components (buttons, text fields, etc.). The
92 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
93 * are invisible containers that hold other Views (or other ViewGroups) and define
94 * their layout properties.
95 * </p>
96 *
97 * <div class="special">
98 * <p>For an introduction to using this class to develop your
99 * application's user interface, read the Developer Guide documentation on
100 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
101 * include:
102 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
104 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
105 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
106 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
107 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
108 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
109 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
110 * </p>
111 * </div>
112 *
113 * <a name="Using"></a>
114 * <h3>Using Views</h3>
115 * <p>
116 * All of the views in a window are arranged in a single tree. You can add views
117 * either from code or by specifying a tree of views in one or more XML layout
118 * files. There are many specialized subclasses of views that act as controls or
119 * are capable of displaying text, images, or other content.
120 * </p>
121 * <p>
122 * Once you have created a tree of views, there are typically a few types of
123 * common operations you may wish to perform:
124 * <ul>
125 * <li><strong>Set properties:</strong> for example setting the text of a
126 * {@link android.widget.TextView}. The available properties and the methods
127 * that set them will vary among the different subclasses of views. Note that
128 * properties that are known at build time can be set in the XML layout
129 * files.</li>
130 * <li><strong>Set focus:</strong> The framework will handled moving focus in
131 * response to user input. To force focus to a specific view, call
132 * {@link #requestFocus}.</li>
133 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
134 * that will be notified when something interesting happens to the view. For
135 * example, all views will let you set a listener to be notified when the view
136 * gains or loses focus. You can register such a listener using
137 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
138 * Other view subclasses offer more specialized listeners. For example, a Button
139 * exposes a listener to notify clients when the button is clicked.</li>
140 * <li><strong>Set visibility:</strong> You can hide or show views using
141 * {@link #setVisibility(int)}.</li>
142 * </ul>
143 * </p>
144 * <p><em>
145 * Note: The Android framework is responsible for measuring, laying out and
146 * drawing views. You should not call methods that perform these actions on
147 * views yourself unless you are actually implementing a
148 * {@link android.view.ViewGroup}.
149 * </em></p>
150 *
151 * <a name="Lifecycle"></a>
152 * <h3>Implementing a Custom View</h3>
153 *
154 * <p>
155 * To implement a custom view, you will usually begin by providing overrides for
156 * some of the standard methods that the framework calls on all views. You do
157 * not need to override all of these methods. In fact, you can start by just
158 * overriding {@link #onDraw(android.graphics.Canvas)}.
159 * <table border="2" width="85%" align="center" cellpadding="5">
160 *     <thead>
161 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
162 *     </thead>
163 *
164 *     <tbody>
165 *     <tr>
166 *         <td rowspan="2">Creation</td>
167 *         <td>Constructors</td>
168 *         <td>There is a form of the constructor that are called when the view
169 *         is created from code and a form that is called when the view is
170 *         inflated from a layout file. The second form should parse and apply
171 *         any attributes defined in the layout file.
172 *         </td>
173 *     </tr>
174 *     <tr>
175 *         <td><code>{@link #onFinishInflate()}</code></td>
176 *         <td>Called after a view and all of its children has been inflated
177 *         from XML.</td>
178 *     </tr>
179 *
180 *     <tr>
181 *         <td rowspan="3">Layout</td>
182 *         <td><code>{@link #onMeasure(int, int)}</code></td>
183 *         <td>Called to determine the size requirements for this view and all
184 *         of its children.
185 *         </td>
186 *     </tr>
187 *     <tr>
188 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
189 *         <td>Called when this view should assign a size and position to all
190 *         of its children.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
195 *         <td>Called when the size of this view has changed.
196 *         </td>
197 *     </tr>
198 *
199 *     <tr>
200 *         <td>Drawing</td>
201 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
202 *         <td>Called when the view should render its content.
203 *         </td>
204 *     </tr>
205 *
206 *     <tr>
207 *         <td rowspan="4">Event processing</td>
208 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
209 *         <td>Called when a new key event occurs.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
214 *         <td>Called when a key up event occurs.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
219 *         <td>Called when a trackball motion event occurs.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
224 *         <td>Called when a touch screen motion event occurs.
225 *         </td>
226 *     </tr>
227 *
228 *     <tr>
229 *         <td rowspan="2">Focus</td>
230 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
231 *         <td>Called when the view gains or loses focus.
232 *         </td>
233 *     </tr>
234 *
235 *     <tr>
236 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
237 *         <td>Called when the window containing the view gains or loses focus.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td rowspan="3">Attaching</td>
243 *         <td><code>{@link #onAttachedToWindow()}</code></td>
244 *         <td>Called when the view is attached to a window.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td><code>{@link #onDetachedFromWindow}</code></td>
250 *         <td>Called when the view is detached from its window.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
256 *         <td>Called when the visibility of the window containing the view
257 *         has changed.
258 *         </td>
259 *     </tr>
260 *     </tbody>
261 *
262 * </table>
263 * </p>
264 *
265 * <a name="IDs"></a>
266 * <h3>IDs</h3>
267 * Views may have an integer id associated with them. These ids are typically
268 * assigned in the layout XML files, and are used to find specific views within
269 * the view tree. A common pattern is to:
270 * <ul>
271 * <li>Define a Button in the layout file and assign it a unique ID.
272 * <pre>
273 * &lt;Button
274 *     android:id="@+id/my_button"
275 *     android:layout_width="wrap_content"
276 *     android:layout_height="wrap_content"
277 *     android:text="@string/my_button_text"/&gt;
278 * </pre></li>
279 * <li>From the onCreate method of an Activity, find the Button
280 * <pre class="prettyprint">
281 *      Button myButton = (Button) findViewById(R.id.my_button);
282 * </pre></li>
283 * </ul>
284 * <p>
285 * View IDs need not be unique throughout the tree, but it is good practice to
286 * ensure that they are at least unique within the part of the tree you are
287 * searching.
288 * </p>
289 *
290 * <a name="Position"></a>
291 * <h3>Position</h3>
292 * <p>
293 * The geometry of a view is that of a rectangle. A view has a location,
294 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
295 * two dimensions, expressed as a width and a height. The unit for location
296 * and dimensions is the pixel.
297 * </p>
298 *
299 * <p>
300 * It is possible to retrieve the location of a view by invoking the methods
301 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
302 * coordinate of the rectangle representing the view. The latter returns the
303 * top, or Y, coordinate of the rectangle representing the view. These methods
304 * both return the location of the view relative to its parent. For instance,
305 * when getLeft() returns 20, that means the view is located 20 pixels to the
306 * right of the left edge of its direct parent.
307 * </p>
308 *
309 * <p>
310 * In addition, several convenience methods are offered to avoid unnecessary
311 * computations, namely {@link #getRight()} and {@link #getBottom()}.
312 * These methods return the coordinates of the right and bottom edges of the
313 * rectangle representing the view. For instance, calling {@link #getRight()}
314 * is similar to the following computation: <code>getLeft() + getWidth()</code>
315 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
316 * </p>
317 *
318 * <a name="SizePaddingMargins"></a>
319 * <h3>Size, padding and margins</h3>
320 * <p>
321 * The size of a view is expressed with a width and a height. A view actually
322 * possess two pairs of width and height values.
323 * </p>
324 *
325 * <p>
326 * The first pair is known as <em>measured width</em> and
327 * <em>measured height</em>. These dimensions define how big a view wants to be
328 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
329 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
330 * and {@link #getMeasuredHeight()}.
331 * </p>
332 *
333 * <p>
334 * The second pair is simply known as <em>width</em> and <em>height</em>, or
335 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
336 * dimensions define the actual size of the view on screen, at drawing time and
337 * after layout. These values may, but do not have to, be different from the
338 * measured width and height. The width and height can be obtained by calling
339 * {@link #getWidth()} and {@link #getHeight()}.
340 * </p>
341 *
342 * <p>
343 * To measure its dimensions, a view takes into account its padding. The padding
344 * is expressed in pixels for the left, top, right and bottom parts of the view.
345 * Padding can be used to offset the content of the view by a specific amount of
346 * pixels. For instance, a left padding of 2 will push the view's content by
347 * 2 pixels to the right of the left edge. Padding can be set using the
348 * {@link #setPadding(int, int, int, int)} method and queried by calling
349 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
350 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
351 * </p>
352 *
353 * <p>
354 * Even though a view can define a padding, it does not provide any support for
355 * margins. However, view groups provide such a support. Refer to
356 * {@link android.view.ViewGroup} and
357 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
358 * </p>
359 *
360 * <a name="Layout"></a>
361 * <h3>Layout</h3>
362 * <p>
363 * Layout is a two pass process: a measure pass and a layout pass. The measuring
364 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
365 * of the view tree. Each view pushes dimension specifications down the tree
366 * during the recursion. At the end of the measure pass, every view has stored
367 * its measurements. The second pass happens in
368 * {@link #layout(int,int,int,int)} and is also top-down. During
369 * this pass each parent is responsible for positioning all of its children
370 * using the sizes computed in the measure pass.
371 * </p>
372 *
373 * <p>
374 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
375 * {@link #getMeasuredHeight()} values must be set, along with those for all of
376 * that view's descendants. A view's measured width and measured height values
377 * must respect the constraints imposed by the view's parents. This guarantees
378 * that at the end of the measure pass, all parents accept all of their
379 * children's measurements. A parent view may call measure() more than once on
380 * its children. For example, the parent may measure each child once with
381 * unspecified dimensions to find out how big they want to be, then call
382 * measure() on them again with actual numbers if the sum of all the children's
383 * unconstrained sizes is too big or too small.
384 * </p>
385 *
386 * <p>
387 * The measure pass uses two classes to communicate dimensions. The
388 * {@link MeasureSpec} class is used by views to tell their parents how they
389 * want to be measured and positioned. The base LayoutParams class just
390 * describes how big the view wants to be for both width and height. For each
391 * dimension, it can specify one of:
392 * <ul>
393 * <li> an exact number
394 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
395 * (minus padding)
396 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
397 * enclose its content (plus padding).
398 * </ul>
399 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
400 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
401 * an X and Y value.
402 * </p>
403 *
404 * <p>
405 * MeasureSpecs are used to push requirements down the tree from parent to
406 * child. A MeasureSpec can be in one of three modes:
407 * <ul>
408 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
409 * of a child view. For example, a LinearLayout may call measure() on its child
410 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
411 * tall the child view wants to be given a width of 240 pixels.
412 * <li>EXACTLY: This is used by the parent to impose an exact size on the
413 * child. The child must use this size, and guarantee that all of its
414 * descendants will fit within this size.
415 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
416 * child. The child must gurantee that it and all of its descendants will fit
417 * within this size.
418 * </ul>
419 * </p>
420 *
421 * <p>
422 * To intiate a layout, call {@link #requestLayout}. This method is typically
423 * called by a view on itself when it believes that is can no longer fit within
424 * its current bounds.
425 * </p>
426 *
427 * <a name="Drawing"></a>
428 * <h3>Drawing</h3>
429 * <p>
430 * Drawing is handled by walking the tree and rendering each view that
431 * intersects the the invalid region. Because the tree is traversed in-order,
432 * this means that parents will draw before (i.e., behind) their children, with
433 * siblings drawn in the order they appear in the tree.
434 * If you set a background drawable for a View, then the View will draw it for you
435 * before calling back to its <code>onDraw()</code> method.
436 * </p>
437 *
438 * <p>
439 * Note that the framework will not draw views that are not in the invalid region.
440 * </p>
441 *
442 * <p>
443 * To force a view to draw, call {@link #invalidate()}.
444 * </p>
445 *
446 * <a name="EventHandlingThreading"></a>
447 * <h3>Event Handling and Threading</h3>
448 * <p>
449 * The basic cycle of a view is as follows:
450 * <ol>
451 * <li>An event comes in and is dispatched to the appropriate view. The view
452 * handles the event and notifies any listeners.</li>
453 * <li>If in the course of processing the event, the view's bounds may need
454 * to be changed, the view will call {@link #requestLayout()}.</li>
455 * <li>Similarly, if in the course of processing the event the view's appearance
456 * may need to be changed, the view will call {@link #invalidate()}.</li>
457 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
458 * the framework will take care of measuring, laying out, and drawing the tree
459 * as appropriate.</li>
460 * </ol>
461 * </p>
462 *
463 * <p><em>Note: The entire view tree is single threaded. You must always be on
464 * the UI thread when calling any method on any view.</em>
465 * If you are doing work on other threads and want to update the state of a view
466 * from that thread, you should use a {@link Handler}.
467 * </p>
468 *
469 * <a name="FocusHandling"></a>
470 * <h3>Focus Handling</h3>
471 * <p>
472 * The framework will handle routine focus movement in response to user input.
473 * This includes changing the focus as views are removed or hidden, or as new
474 * views become available. Views indicate their willingness to take focus
475 * through the {@link #isFocusable} method. To change whether a view can take
476 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
477 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
478 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
479 * </p>
480 * <p>
481 * Focus movement is based on an algorithm which finds the nearest neighbor in a
482 * given direction. In rare cases, the default algorithm may not match the
483 * intended behavior of the developer. In these situations, you can provide
484 * explicit overrides by using these XML attributes in the layout file:
485 * <pre>
486 * nextFocusDown
487 * nextFocusLeft
488 * nextFocusRight
489 * nextFocusUp
490 * </pre>
491 * </p>
492 *
493 *
494 * <p>
495 * To get a particular view to take focus, call {@link #requestFocus()}.
496 * </p>
497 *
498 * <a name="TouchMode"></a>
499 * <h3>Touch Mode</h3>
500 * <p>
501 * When a user is navigating a user interface via directional keys such as a D-pad, it is
502 * necessary to give focus to actionable items such as buttons so the user can see
503 * what will take input.  If the device has touch capabilities, however, and the user
504 * begins interacting with the interface by touching it, it is no longer necessary to
505 * always highlight, or give focus to, a particular view.  This motivates a mode
506 * for interaction named 'touch mode'.
507 * </p>
508 * <p>
509 * For a touch capable device, once the user touches the screen, the device
510 * will enter touch mode.  From this point onward, only views for which
511 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
512 * Other views that are touchable, like buttons, will not take focus when touched; they will
513 * only fire the on click listeners.
514 * </p>
515 * <p>
516 * Any time a user hits a directional key, such as a D-pad direction, the view device will
517 * exit touch mode, and find a view to take focus, so that the user may resume interacting
518 * with the user interface without touching the screen again.
519 * </p>
520 * <p>
521 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
522 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
523 * </p>
524 *
525 * <a name="Scrolling"></a>
526 * <h3>Scrolling</h3>
527 * <p>
528 * The framework provides basic support for views that wish to internally
529 * scroll their content. This includes keeping track of the X and Y scroll
530 * offset as well as mechanisms for drawing scrollbars. See
531 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
532 * {@link #awakenScrollBars()} for more details.
533 * </p>
534 *
535 * <a name="Tags"></a>
536 * <h3>Tags</h3>
537 * <p>
538 * Unlike IDs, tags are not used to identify views. Tags are essentially an
539 * extra piece of information that can be associated with a view. They are most
540 * often used as a convenience to store data related to views in the views
541 * themselves rather than by putting them in a separate structure.
542 * </p>
543 *
544 * <a name="Animation"></a>
545 * <h3>Animation</h3>
546 * <p>
547 * You can attach an {@link Animation} object to a view using
548 * {@link #setAnimation(Animation)} or
549 * {@link #startAnimation(Animation)}. The animation can alter the scale,
550 * rotation, translation and alpha of a view over time. If the animation is
551 * attached to a view that has children, the animation will affect the entire
552 * subtree rooted by that node. When an animation is started, the framework will
553 * take care of redrawing the appropriate views until the animation completes.
554 * </p>
555 * <p>
556 * Starting with Android 3.0, the preferred way of animating views is to use the
557 * {@link android.animation} package APIs.
558 * </p>
559 *
560 * <a name="Security"></a>
561 * <h3>Security</h3>
562 * <p>
563 * Sometimes it is essential that an application be able to verify that an action
564 * is being performed with the full knowledge and consent of the user, such as
565 * granting a permission request, making a purchase or clicking on an advertisement.
566 * Unfortunately, a malicious application could try to spoof the user into
567 * performing these actions, unaware, by concealing the intended purpose of the view.
568 * As a remedy, the framework offers a touch filtering mechanism that can be used to
569 * improve the security of views that provide access to sensitive functionality.
570 * </p><p>
571 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
572 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
573 * will discard touches that are received whenever the view's window is obscured by
574 * another visible window.  As a result, the view will not receive touches whenever a
575 * toast, dialog or other window appears above the view's window.
576 * </p><p>
577 * For more fine-grained control over security, consider overriding the
578 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
579 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
580 * </p>
581 *
582 * @attr ref android.R.styleable#View_alpha
583 * @attr ref android.R.styleable#View_background
584 * @attr ref android.R.styleable#View_clickable
585 * @attr ref android.R.styleable#View_contentDescription
586 * @attr ref android.R.styleable#View_drawingCacheQuality
587 * @attr ref android.R.styleable#View_duplicateParentState
588 * @attr ref android.R.styleable#View_id
589 * @attr ref android.R.styleable#View_requiresFadingEdge
590 * @attr ref android.R.styleable#View_fadingEdgeLength
591 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
592 * @attr ref android.R.styleable#View_fitsSystemWindows
593 * @attr ref android.R.styleable#View_isScrollContainer
594 * @attr ref android.R.styleable#View_focusable
595 * @attr ref android.R.styleable#View_focusableInTouchMode
596 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
597 * @attr ref android.R.styleable#View_keepScreenOn
598 * @attr ref android.R.styleable#View_layerType
599 * @attr ref android.R.styleable#View_longClickable
600 * @attr ref android.R.styleable#View_minHeight
601 * @attr ref android.R.styleable#View_minWidth
602 * @attr ref android.R.styleable#View_nextFocusDown
603 * @attr ref android.R.styleable#View_nextFocusLeft
604 * @attr ref android.R.styleable#View_nextFocusRight
605 * @attr ref android.R.styleable#View_nextFocusUp
606 * @attr ref android.R.styleable#View_onClick
607 * @attr ref android.R.styleable#View_padding
608 * @attr ref android.R.styleable#View_paddingBottom
609 * @attr ref android.R.styleable#View_paddingLeft
610 * @attr ref android.R.styleable#View_paddingRight
611 * @attr ref android.R.styleable#View_paddingTop
612 * @attr ref android.R.styleable#View_saveEnabled
613 * @attr ref android.R.styleable#View_rotation
614 * @attr ref android.R.styleable#View_rotationX
615 * @attr ref android.R.styleable#View_rotationY
616 * @attr ref android.R.styleable#View_scaleX
617 * @attr ref android.R.styleable#View_scaleY
618 * @attr ref android.R.styleable#View_scrollX
619 * @attr ref android.R.styleable#View_scrollY
620 * @attr ref android.R.styleable#View_scrollbarSize
621 * @attr ref android.R.styleable#View_scrollbarStyle
622 * @attr ref android.R.styleable#View_scrollbars
623 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
624 * @attr ref android.R.styleable#View_scrollbarFadeDuration
625 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
626 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
627 * @attr ref android.R.styleable#View_scrollbarThumbVertical
628 * @attr ref android.R.styleable#View_scrollbarTrackVertical
629 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
630 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
631 * @attr ref android.R.styleable#View_soundEffectsEnabled
632 * @attr ref android.R.styleable#View_tag
633 * @attr ref android.R.styleable#View_transformPivotX
634 * @attr ref android.R.styleable#View_transformPivotY
635 * @attr ref android.R.styleable#View_translationX
636 * @attr ref android.R.styleable#View_translationY
637 * @attr ref android.R.styleable#View_visibility
638 *
639 * @see android.view.ViewGroup
640 */
641public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
642        AccessibilityEventSource {
643    private static final boolean DBG = false;
644
645    /**
646     * The logging tag used by this class with android.util.Log.
647     */
648    protected static final String VIEW_LOG_TAG = "View";
649
650    /**
651     * Used to mark a View that has no ID.
652     */
653    public static final int NO_ID = -1;
654
655    /**
656     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
657     * calling setFlags.
658     */
659    private static final int NOT_FOCUSABLE = 0x00000000;
660
661    /**
662     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
663     * setFlags.
664     */
665    private static final int FOCUSABLE = 0x00000001;
666
667    /**
668     * Mask for use with setFlags indicating bits used for focus.
669     */
670    private static final int FOCUSABLE_MASK = 0x00000001;
671
672    /**
673     * This view will adjust its padding to fit sytem windows (e.g. status bar)
674     */
675    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
676
677    /**
678     * This view is visible.
679     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
680     * android:visibility}.
681     */
682    public static final int VISIBLE = 0x00000000;
683
684    /**
685     * This view is invisible, but it still takes up space for layout purposes.
686     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
687     * android:visibility}.
688     */
689    public static final int INVISIBLE = 0x00000004;
690
691    /**
692     * This view is invisible, and it doesn't take any space for layout
693     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
694     * android:visibility}.
695     */
696    public static final int GONE = 0x00000008;
697
698    /**
699     * Mask for use with setFlags indicating bits used for visibility.
700     * {@hide}
701     */
702    static final int VISIBILITY_MASK = 0x0000000C;
703
704    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
705
706    /**
707     * This view is enabled. Intrepretation varies by subclass.
708     * Use with ENABLED_MASK when calling setFlags.
709     * {@hide}
710     */
711    static final int ENABLED = 0x00000000;
712
713    /**
714     * This view is disabled. Intrepretation varies by subclass.
715     * Use with ENABLED_MASK when calling setFlags.
716     * {@hide}
717     */
718    static final int DISABLED = 0x00000020;
719
720   /**
721    * Mask for use with setFlags indicating bits used for indicating whether
722    * this view is enabled
723    * {@hide}
724    */
725    static final int ENABLED_MASK = 0x00000020;
726
727    /**
728     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
729     * called and further optimizations will be performed. It is okay to have
730     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
731     * {@hide}
732     */
733    static final int WILL_NOT_DRAW = 0x00000080;
734
735    /**
736     * Mask for use with setFlags indicating bits used for indicating whether
737     * this view is will draw
738     * {@hide}
739     */
740    static final int DRAW_MASK = 0x00000080;
741
742    /**
743     * <p>This view doesn't show scrollbars.</p>
744     * {@hide}
745     */
746    static final int SCROLLBARS_NONE = 0x00000000;
747
748    /**
749     * <p>This view shows horizontal scrollbars.</p>
750     * {@hide}
751     */
752    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
753
754    /**
755     * <p>This view shows vertical scrollbars.</p>
756     * {@hide}
757     */
758    static final int SCROLLBARS_VERTICAL = 0x00000200;
759
760    /**
761     * <p>Mask for use with setFlags indicating bits used for indicating which
762     * scrollbars are enabled.</p>
763     * {@hide}
764     */
765    static final int SCROLLBARS_MASK = 0x00000300;
766
767    /**
768     * Indicates that the view should filter touches when its window is obscured.
769     * Refer to the class comments for more information about this security feature.
770     * {@hide}
771     */
772    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
773
774    // note flag value 0x00000800 is now available for next flags...
775
776    /**
777     * <p>This view doesn't show fading edges.</p>
778     * {@hide}
779     */
780    static final int FADING_EDGE_NONE = 0x00000000;
781
782    /**
783     * <p>This view shows horizontal fading edges.</p>
784     * {@hide}
785     */
786    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
787
788    /**
789     * <p>This view shows vertical fading edges.</p>
790     * {@hide}
791     */
792    static final int FADING_EDGE_VERTICAL = 0x00002000;
793
794    /**
795     * <p>Mask for use with setFlags indicating bits used for indicating which
796     * fading edges are enabled.</p>
797     * {@hide}
798     */
799    static final int FADING_EDGE_MASK = 0x00003000;
800
801    /**
802     * <p>Indicates this view can be clicked. When clickable, a View reacts
803     * to clicks by notifying the OnClickListener.<p>
804     * {@hide}
805     */
806    static final int CLICKABLE = 0x00004000;
807
808    /**
809     * <p>Indicates this view is caching its drawing into a bitmap.</p>
810     * {@hide}
811     */
812    static final int DRAWING_CACHE_ENABLED = 0x00008000;
813
814    /**
815     * <p>Indicates that no icicle should be saved for this view.<p>
816     * {@hide}
817     */
818    static final int SAVE_DISABLED = 0x000010000;
819
820    /**
821     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
822     * property.</p>
823     * {@hide}
824     */
825    static final int SAVE_DISABLED_MASK = 0x000010000;
826
827    /**
828     * <p>Indicates that no drawing cache should ever be created for this view.<p>
829     * {@hide}
830     */
831    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
832
833    /**
834     * <p>Indicates this view can take / keep focus when int touch mode.</p>
835     * {@hide}
836     */
837    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
838
839    /**
840     * <p>Enables low quality mode for the drawing cache.</p>
841     */
842    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
843
844    /**
845     * <p>Enables high quality mode for the drawing cache.</p>
846     */
847    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
848
849    /**
850     * <p>Enables automatic quality mode for the drawing cache.</p>
851     */
852    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
853
854    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
855            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
856    };
857
858    /**
859     * <p>Mask for use with setFlags indicating bits used for the cache
860     * quality property.</p>
861     * {@hide}
862     */
863    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
864
865    /**
866     * <p>
867     * Indicates this view can be long clicked. When long clickable, a View
868     * reacts to long clicks by notifying the OnLongClickListener or showing a
869     * context menu.
870     * </p>
871     * {@hide}
872     */
873    static final int LONG_CLICKABLE = 0x00200000;
874
875    /**
876     * <p>Indicates that this view gets its drawable states from its direct parent
877     * and ignores its original internal states.</p>
878     *
879     * @hide
880     */
881    static final int DUPLICATE_PARENT_STATE = 0x00400000;
882
883    /**
884     * The scrollbar style to display the scrollbars inside the content area,
885     * without increasing the padding. The scrollbars will be overlaid with
886     * translucency on the view's content.
887     */
888    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
889
890    /**
891     * The scrollbar style to display the scrollbars inside the padded area,
892     * increasing the padding of the view. The scrollbars will not overlap the
893     * content area of the view.
894     */
895    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
896
897    /**
898     * The scrollbar style to display the scrollbars at the edge of the view,
899     * without increasing the padding. The scrollbars will be overlaid with
900     * translucency.
901     */
902    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
903
904    /**
905     * The scrollbar style to display the scrollbars at the edge of the view,
906     * increasing the padding of the view. The scrollbars will only overlap the
907     * background, if any.
908     */
909    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
910
911    /**
912     * Mask to check if the scrollbar style is overlay or inset.
913     * {@hide}
914     */
915    static final int SCROLLBARS_INSET_MASK = 0x01000000;
916
917    /**
918     * Mask to check if the scrollbar style is inside or outside.
919     * {@hide}
920     */
921    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
922
923    /**
924     * Mask for scrollbar style.
925     * {@hide}
926     */
927    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
928
929    /**
930     * View flag indicating that the screen should remain on while the
931     * window containing this view is visible to the user.  This effectively
932     * takes care of automatically setting the WindowManager's
933     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
934     */
935    public static final int KEEP_SCREEN_ON = 0x04000000;
936
937    /**
938     * View flag indicating whether this view should have sound effects enabled
939     * for events such as clicking and touching.
940     */
941    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
942
943    /**
944     * View flag indicating whether this view should have haptic feedback
945     * enabled for events such as long presses.
946     */
947    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
948
949    /**
950     * <p>Indicates that the view hierarchy should stop saving state when
951     * it reaches this view.  If state saving is initiated immediately at
952     * the view, it will be allowed.
953     * {@hide}
954     */
955    static final int PARENT_SAVE_DISABLED = 0x20000000;
956
957    /**
958     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
959     * {@hide}
960     */
961    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
962
963    /**
964     * Horizontal direction of this view is from Left to Right.
965     * Use with {@link #setLayoutDirection}.
966     * {@hide}
967     */
968    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
969
970    /**
971     * Horizontal direction of this view is from Right to Left.
972     * Use with {@link #setLayoutDirection}.
973     * {@hide}
974     */
975    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
976
977    /**
978     * Horizontal direction of this view is inherited from its parent.
979     * Use with {@link #setLayoutDirection}.
980     * {@hide}
981     */
982    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
983
984    /**
985     * Horizontal direction of this view is from deduced from the default language
986     * script for the locale. Use with {@link #setLayoutDirection}.
987     * {@hide}
988     */
989    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
990
991    /**
992     * Mask for use with setFlags indicating bits used for horizontalDirection.
993     * {@hide}
994     */
995    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
996
997    /*
998     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
999     * flag value.
1000     * {@hide}
1001     */
1002    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
1003        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
1004
1005    /**
1006     * Default horizontalDirection.
1007     * {@hide}
1008     */
1009    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1010
1011    /**
1012     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1013     * should add all focusable Views regardless if they are focusable in touch mode.
1014     */
1015    public static final int FOCUSABLES_ALL = 0x00000000;
1016
1017    /**
1018     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1019     * should add only Views focusable in touch mode.
1020     */
1021    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1022
1023    /**
1024     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1025     * item.
1026     */
1027    public static final int FOCUS_BACKWARD = 0x00000001;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1031     * item.
1032     */
1033    public static final int FOCUS_FORWARD = 0x00000002;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move focus to the left.
1037     */
1038    public static final int FOCUS_LEFT = 0x00000011;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move focus up.
1042     */
1043    public static final int FOCUS_UP = 0x00000021;
1044
1045    /**
1046     * Use with {@link #focusSearch(int)}. Move focus to the right.
1047     */
1048    public static final int FOCUS_RIGHT = 0x00000042;
1049
1050    /**
1051     * Use with {@link #focusSearch(int)}. Move focus down.
1052     */
1053    public static final int FOCUS_DOWN = 0x00000082;
1054
1055    /**
1056     * Bits of {@link #getMeasuredWidthAndState()} and
1057     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1058     */
1059    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1060
1061    /**
1062     * Bits of {@link #getMeasuredWidthAndState()} and
1063     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1064     */
1065    public static final int MEASURED_STATE_MASK = 0xff000000;
1066
1067    /**
1068     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1069     * for functions that combine both width and height into a single int,
1070     * such as {@link #getMeasuredState()} and the childState argument of
1071     * {@link #resolveSizeAndState(int, int, int)}.
1072     */
1073    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1074
1075    /**
1076     * Bit of {@link #getMeasuredWidthAndState()} and
1077     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1078     * is smaller that the space the view would like to have.
1079     */
1080    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1081
1082    /**
1083     * Base View state sets
1084     */
1085    // Singles
1086    /**
1087     * Indicates the view has no states set. States are used with
1088     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1089     * view depending on its state.
1090     *
1091     * @see android.graphics.drawable.Drawable
1092     * @see #getDrawableState()
1093     */
1094    protected static final int[] EMPTY_STATE_SET;
1095    /**
1096     * Indicates the view is enabled. States are used with
1097     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1098     * view depending on its state.
1099     *
1100     * @see android.graphics.drawable.Drawable
1101     * @see #getDrawableState()
1102     */
1103    protected static final int[] ENABLED_STATE_SET;
1104    /**
1105     * Indicates the view is focused. States are used with
1106     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1107     * view depending on its state.
1108     *
1109     * @see android.graphics.drawable.Drawable
1110     * @see #getDrawableState()
1111     */
1112    protected static final int[] FOCUSED_STATE_SET;
1113    /**
1114     * Indicates the view is selected. States are used with
1115     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1116     * view depending on its state.
1117     *
1118     * @see android.graphics.drawable.Drawable
1119     * @see #getDrawableState()
1120     */
1121    protected static final int[] SELECTED_STATE_SET;
1122    /**
1123     * Indicates the view is pressed. States are used with
1124     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1125     * view depending on its state.
1126     *
1127     * @see android.graphics.drawable.Drawable
1128     * @see #getDrawableState()
1129     * @hide
1130     */
1131    protected static final int[] PRESSED_STATE_SET;
1132    /**
1133     * Indicates the view's window has focus. States are used with
1134     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1135     * view depending on its state.
1136     *
1137     * @see android.graphics.drawable.Drawable
1138     * @see #getDrawableState()
1139     */
1140    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1141    // Doubles
1142    /**
1143     * Indicates the view is enabled and has the focus.
1144     *
1145     * @see #ENABLED_STATE_SET
1146     * @see #FOCUSED_STATE_SET
1147     */
1148    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1149    /**
1150     * Indicates the view is enabled and selected.
1151     *
1152     * @see #ENABLED_STATE_SET
1153     * @see #SELECTED_STATE_SET
1154     */
1155    protected static final int[] ENABLED_SELECTED_STATE_SET;
1156    /**
1157     * Indicates the view is enabled and that its window has focus.
1158     *
1159     * @see #ENABLED_STATE_SET
1160     * @see #WINDOW_FOCUSED_STATE_SET
1161     */
1162    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1163    /**
1164     * Indicates the view is focused and selected.
1165     *
1166     * @see #FOCUSED_STATE_SET
1167     * @see #SELECTED_STATE_SET
1168     */
1169    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1170    /**
1171     * Indicates the view has the focus and that its window has the focus.
1172     *
1173     * @see #FOCUSED_STATE_SET
1174     * @see #WINDOW_FOCUSED_STATE_SET
1175     */
1176    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1177    /**
1178     * Indicates the view is selected and that its window has the focus.
1179     *
1180     * @see #SELECTED_STATE_SET
1181     * @see #WINDOW_FOCUSED_STATE_SET
1182     */
1183    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1184    // Triples
1185    /**
1186     * Indicates the view is enabled, focused and selected.
1187     *
1188     * @see #ENABLED_STATE_SET
1189     * @see #FOCUSED_STATE_SET
1190     * @see #SELECTED_STATE_SET
1191     */
1192    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1193    /**
1194     * Indicates the view is enabled, focused and its window has the focus.
1195     *
1196     * @see #ENABLED_STATE_SET
1197     * @see #FOCUSED_STATE_SET
1198     * @see #WINDOW_FOCUSED_STATE_SET
1199     */
1200    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is enabled, selected and its window has the focus.
1203     *
1204     * @see #ENABLED_STATE_SET
1205     * @see #SELECTED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is focused, selected and its window has the focus.
1211     *
1212     * @see #FOCUSED_STATE_SET
1213     * @see #SELECTED_STATE_SET
1214     * @see #WINDOW_FOCUSED_STATE_SET
1215     */
1216    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1217    /**
1218     * Indicates the view is enabled, focused, selected and its window
1219     * has the focus.
1220     *
1221     * @see #ENABLED_STATE_SET
1222     * @see #FOCUSED_STATE_SET
1223     * @see #SELECTED_STATE_SET
1224     * @see #WINDOW_FOCUSED_STATE_SET
1225     */
1226    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1227    /**
1228     * Indicates the view is pressed and its window has the focus.
1229     *
1230     * @see #PRESSED_STATE_SET
1231     * @see #WINDOW_FOCUSED_STATE_SET
1232     */
1233    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1234    /**
1235     * Indicates the view is pressed and selected.
1236     *
1237     * @see #PRESSED_STATE_SET
1238     * @see #SELECTED_STATE_SET
1239     */
1240    protected static final int[] PRESSED_SELECTED_STATE_SET;
1241    /**
1242     * Indicates the view is pressed, selected and its window has the focus.
1243     *
1244     * @see #PRESSED_STATE_SET
1245     * @see #SELECTED_STATE_SET
1246     * @see #WINDOW_FOCUSED_STATE_SET
1247     */
1248    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1249    /**
1250     * Indicates the view is pressed and focused.
1251     *
1252     * @see #PRESSED_STATE_SET
1253     * @see #FOCUSED_STATE_SET
1254     */
1255    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1256    /**
1257     * Indicates the view is pressed, focused and its window has the focus.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #FOCUSED_STATE_SET
1261     * @see #WINDOW_FOCUSED_STATE_SET
1262     */
1263    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1264    /**
1265     * Indicates the view is pressed, focused and selected.
1266     *
1267     * @see #PRESSED_STATE_SET
1268     * @see #SELECTED_STATE_SET
1269     * @see #FOCUSED_STATE_SET
1270     */
1271    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1272    /**
1273     * Indicates the view is pressed, focused, selected and its window has the focus.
1274     *
1275     * @see #PRESSED_STATE_SET
1276     * @see #FOCUSED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     * @see #WINDOW_FOCUSED_STATE_SET
1279     */
1280    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1281    /**
1282     * Indicates the view is pressed and enabled.
1283     *
1284     * @see #PRESSED_STATE_SET
1285     * @see #ENABLED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_ENABLED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, enabled and its window has the focus.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #ENABLED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, enabled and selected.
1298     *
1299     * @see #PRESSED_STATE_SET
1300     * @see #ENABLED_STATE_SET
1301     * @see #SELECTED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed, enabled, selected and its window has the
1306     * focus.
1307     *
1308     * @see #PRESSED_STATE_SET
1309     * @see #ENABLED_STATE_SET
1310     * @see #SELECTED_STATE_SET
1311     * @see #WINDOW_FOCUSED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, enabled and focused.
1316     *
1317     * @see #PRESSED_STATE_SET
1318     * @see #ENABLED_STATE_SET
1319     * @see #FOCUSED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed, enabled, focused and its window has the
1324     * focus.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #ENABLED_STATE_SET
1328     * @see #FOCUSED_STATE_SET
1329     * @see #WINDOW_FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, enabled, focused and selected.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #ENABLED_STATE_SET
1337     * @see #SELECTED_STATE_SET
1338     * @see #FOCUSED_STATE_SET
1339     */
1340    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1341    /**
1342     * Indicates the view is pressed, enabled, focused, selected and its window
1343     * has the focus.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #ENABLED_STATE_SET
1347     * @see #SELECTED_STATE_SET
1348     * @see #FOCUSED_STATE_SET
1349     * @see #WINDOW_FOCUSED_STATE_SET
1350     */
1351    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1352
1353    /**
1354     * The order here is very important to {@link #getDrawableState()}
1355     */
1356    private static final int[][] VIEW_STATE_SETS;
1357
1358    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1359    static final int VIEW_STATE_SELECTED = 1 << 1;
1360    static final int VIEW_STATE_FOCUSED = 1 << 2;
1361    static final int VIEW_STATE_ENABLED = 1 << 3;
1362    static final int VIEW_STATE_PRESSED = 1 << 4;
1363    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1364    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1365    static final int VIEW_STATE_HOVERED = 1 << 7;
1366    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1367    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1368
1369    static final int[] VIEW_STATE_IDS = new int[] {
1370        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1371        R.attr.state_selected,          VIEW_STATE_SELECTED,
1372        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1373        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1374        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1375        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1376        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1377        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1378        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1379        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1380    };
1381
1382    static {
1383        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1384            throw new IllegalStateException(
1385                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1386        }
1387        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1388        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1389            int viewState = R.styleable.ViewDrawableStates[i];
1390            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1391                if (VIEW_STATE_IDS[j] == viewState) {
1392                    orderedIds[i * 2] = viewState;
1393                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1394                }
1395            }
1396        }
1397        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1398        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1399        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1400            int numBits = Integer.bitCount(i);
1401            int[] set = new int[numBits];
1402            int pos = 0;
1403            for (int j = 0; j < orderedIds.length; j += 2) {
1404                if ((i & orderedIds[j+1]) != 0) {
1405                    set[pos++] = orderedIds[j];
1406                }
1407            }
1408            VIEW_STATE_SETS[i] = set;
1409        }
1410
1411        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1412        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1413        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1414        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1416        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1417        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1419        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1421        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1423                | VIEW_STATE_FOCUSED];
1424        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1425        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1427        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1428                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1429        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1431                | VIEW_STATE_ENABLED];
1432        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1439                | VIEW_STATE_ENABLED];
1440        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1441                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1442                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1443
1444        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1445        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1447        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1449        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1451                | VIEW_STATE_PRESSED];
1452        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1459                | VIEW_STATE_PRESSED];
1460        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1462                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1470                | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1473                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1476                | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1482                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1483        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1484                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1485                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1486                | VIEW_STATE_PRESSED];
1487    }
1488
1489    /**
1490     * Temporary Rect currently for use in setBackground().  This will probably
1491     * be extended in the future to hold our own class with more than just
1492     * a Rect. :)
1493     */
1494    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1495
1496    /**
1497     * Map used to store views' tags.
1498     */
1499    private SparseArray<Object> mKeyedTags;
1500
1501    /**
1502     * The next available accessiiblity id.
1503     */
1504    private static int sNextAccessibilityViewId;
1505
1506    /**
1507     * The animation currently associated with this view.
1508     * @hide
1509     */
1510    protected Animation mCurrentAnimation = null;
1511
1512    /**
1513     * Width as measured during measure pass.
1514     * {@hide}
1515     */
1516    @ViewDebug.ExportedProperty(category = "measurement")
1517    int mMeasuredWidth;
1518
1519    /**
1520     * Height as measured during measure pass.
1521     * {@hide}
1522     */
1523    @ViewDebug.ExportedProperty(category = "measurement")
1524    int mMeasuredHeight;
1525
1526    /**
1527     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1528     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1529     * its display list. This flag, used only when hw accelerated, allows us to clear the
1530     * flag while retaining this information until it's needed (at getDisplayList() time and
1531     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1532     *
1533     * {@hide}
1534     */
1535    boolean mRecreateDisplayList = false;
1536
1537    /**
1538     * The view's identifier.
1539     * {@hide}
1540     *
1541     * @see #setId(int)
1542     * @see #getId()
1543     */
1544    @ViewDebug.ExportedProperty(resolveId = true)
1545    int mID = NO_ID;
1546
1547    /**
1548     * The stable ID of this view for accessibility porposes.
1549     */
1550    int mAccessibilityViewId = NO_ID;
1551
1552    /**
1553     * The view's tag.
1554     * {@hide}
1555     *
1556     * @see #setTag(Object)
1557     * @see #getTag()
1558     */
1559    protected Object mTag;
1560
1561    // for mPrivateFlags:
1562    /** {@hide} */
1563    static final int WANTS_FOCUS                    = 0x00000001;
1564    /** {@hide} */
1565    static final int FOCUSED                        = 0x00000002;
1566    /** {@hide} */
1567    static final int SELECTED                       = 0x00000004;
1568    /** {@hide} */
1569    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1570    /** {@hide} */
1571    static final int HAS_BOUNDS                     = 0x00000010;
1572    /** {@hide} */
1573    static final int DRAWN                          = 0x00000020;
1574    /**
1575     * When this flag is set, this view is running an animation on behalf of its
1576     * children and should therefore not cancel invalidate requests, even if they
1577     * lie outside of this view's bounds.
1578     *
1579     * {@hide}
1580     */
1581    static final int DRAW_ANIMATION                 = 0x00000040;
1582    /** {@hide} */
1583    static final int SKIP_DRAW                      = 0x00000080;
1584    /** {@hide} */
1585    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1586    /** {@hide} */
1587    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1588    /** {@hide} */
1589    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1590    /** {@hide} */
1591    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1592    /** {@hide} */
1593    static final int FORCE_LAYOUT                   = 0x00001000;
1594    /** {@hide} */
1595    static final int LAYOUT_REQUIRED                = 0x00002000;
1596
1597    private static final int PRESSED                = 0x00004000;
1598
1599    /** {@hide} */
1600    static final int DRAWING_CACHE_VALID            = 0x00008000;
1601    /**
1602     * Flag used to indicate that this view should be drawn once more (and only once
1603     * more) after its animation has completed.
1604     * {@hide}
1605     */
1606    static final int ANIMATION_STARTED              = 0x00010000;
1607
1608    private static final int SAVE_STATE_CALLED      = 0x00020000;
1609
1610    /**
1611     * Indicates that the View returned true when onSetAlpha() was called and that
1612     * the alpha must be restored.
1613     * {@hide}
1614     */
1615    static final int ALPHA_SET                      = 0x00040000;
1616
1617    /**
1618     * Set by {@link #setScrollContainer(boolean)}.
1619     */
1620    static final int SCROLL_CONTAINER               = 0x00080000;
1621
1622    /**
1623     * Set by {@link #setScrollContainer(boolean)}.
1624     */
1625    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1626
1627    /**
1628     * View flag indicating whether this view was invalidated (fully or partially.)
1629     *
1630     * @hide
1631     */
1632    static final int DIRTY                          = 0x00200000;
1633
1634    /**
1635     * View flag indicating whether this view was invalidated by an opaque
1636     * invalidate request.
1637     *
1638     * @hide
1639     */
1640    static final int DIRTY_OPAQUE                   = 0x00400000;
1641
1642    /**
1643     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1644     *
1645     * @hide
1646     */
1647    static final int DIRTY_MASK                     = 0x00600000;
1648
1649    /**
1650     * Indicates whether the background is opaque.
1651     *
1652     * @hide
1653     */
1654    static final int OPAQUE_BACKGROUND              = 0x00800000;
1655
1656    /**
1657     * Indicates whether the scrollbars are opaque.
1658     *
1659     * @hide
1660     */
1661    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1662
1663    /**
1664     * Indicates whether the view is opaque.
1665     *
1666     * @hide
1667     */
1668    static final int OPAQUE_MASK                    = 0x01800000;
1669
1670    /**
1671     * Indicates a prepressed state;
1672     * the short time between ACTION_DOWN and recognizing
1673     * a 'real' press. Prepressed is used to recognize quick taps
1674     * even when they are shorter than ViewConfiguration.getTapTimeout().
1675     *
1676     * @hide
1677     */
1678    private static final int PREPRESSED             = 0x02000000;
1679
1680    /**
1681     * Indicates whether the view is temporarily detached.
1682     *
1683     * @hide
1684     */
1685    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1686
1687    /**
1688     * Indicates that we should awaken scroll bars once attached
1689     *
1690     * @hide
1691     */
1692    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1693
1694    /**
1695     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1696     * @hide
1697     */
1698    private static final int HOVERED              = 0x10000000;
1699
1700    /**
1701     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1702     * for transform operations
1703     *
1704     * @hide
1705     */
1706    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1707
1708    /** {@hide} */
1709    static final int ACTIVATED                    = 0x40000000;
1710
1711    /**
1712     * Indicates that this view was specifically invalidated, not just dirtied because some
1713     * child view was invalidated. The flag is used to determine when we need to recreate
1714     * a view's display list (as opposed to just returning a reference to its existing
1715     * display list).
1716     *
1717     * @hide
1718     */
1719    static final int INVALIDATED                  = 0x80000000;
1720
1721    /* Masks for mPrivateFlags2 */
1722
1723    /**
1724     * Indicates that this view has reported that it can accept the current drag's content.
1725     * Cleared when the drag operation concludes.
1726     * @hide
1727     */
1728    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1729
1730    /**
1731     * Indicates that this view is currently directly under the drag location in a
1732     * drag-and-drop operation involving content that it can accept.  Cleared when
1733     * the drag exits the view, or when the drag operation concludes.
1734     * @hide
1735     */
1736    static final int DRAG_HOVERED                 = 0x00000002;
1737
1738    /**
1739     * Indicates whether the view layout direction has been resolved and drawn to the
1740     * right-to-left direction.
1741     *
1742     * @hide
1743     */
1744    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1745
1746    /**
1747     * Indicates whether the view layout direction has been resolved.
1748     *
1749     * @hide
1750     */
1751    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1752
1753
1754    /* End of masks for mPrivateFlags2 */
1755
1756    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1757
1758    /**
1759     * Always allow a user to over-scroll this view, provided it is a
1760     * view that can scroll.
1761     *
1762     * @see #getOverScrollMode()
1763     * @see #setOverScrollMode(int)
1764     */
1765    public static final int OVER_SCROLL_ALWAYS = 0;
1766
1767    /**
1768     * Allow a user to over-scroll this view only if the content is large
1769     * enough to meaningfully scroll, provided it is a view that can scroll.
1770     *
1771     * @see #getOverScrollMode()
1772     * @see #setOverScrollMode(int)
1773     */
1774    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1775
1776    /**
1777     * Never allow a user to over-scroll this view.
1778     *
1779     * @see #getOverScrollMode()
1780     * @see #setOverScrollMode(int)
1781     */
1782    public static final int OVER_SCROLL_NEVER = 2;
1783
1784    /**
1785     * View has requested the system UI (status bar) to be visible (the default).
1786     *
1787     * @see #setSystemUiVisibility(int)
1788     */
1789    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1790
1791    /**
1792     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1793     *
1794     * This is for use in games, book readers, video players, or any other "immersive" application
1795     * where the usual system chrome is deemed too distracting.
1796     *
1797     * In low profile mode, the status bar and/or navigation icons may dim.
1798     *
1799     * @see #setSystemUiVisibility(int)
1800     */
1801    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1802
1803    /**
1804     * View has requested that the system navigation be temporarily hidden.
1805     *
1806     * This is an even less obtrusive state than that called for by
1807     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1808     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1809     * those to disappear. This is useful (in conjunction with the
1810     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1811     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1812     * window flags) for displaying content using every last pixel on the display.
1813     *
1814     * There is a limitation: because navigation controls are so important, the least user
1815     * interaction will cause them to reappear immediately.
1816     *
1817     * @see #setSystemUiVisibility(int)
1818     */
1819    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1820
1821    /**
1822     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1823     */
1824    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1825
1826    /**
1827     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1828     */
1829    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1830
1831    /**
1832     * @hide
1833     *
1834     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1835     * out of the public fields to keep the undefined bits out of the developer's way.
1836     *
1837     * Flag to make the status bar not expandable.  Unless you also
1838     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1839     */
1840    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1841
1842    /**
1843     * @hide
1844     *
1845     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1846     * out of the public fields to keep the undefined bits out of the developer's way.
1847     *
1848     * Flag to hide notification icons and scrolling ticker text.
1849     */
1850    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1851
1852    /**
1853     * @hide
1854     *
1855     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1856     * out of the public fields to keep the undefined bits out of the developer's way.
1857     *
1858     * Flag to disable incoming notification alerts.  This will not block
1859     * icons, but it will block sound, vibrating and other visual or aural notifications.
1860     */
1861    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1862
1863    /**
1864     * @hide
1865     *
1866     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1867     * out of the public fields to keep the undefined bits out of the developer's way.
1868     *
1869     * Flag to hide only the scrolling ticker.  Note that
1870     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1871     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1872     */
1873    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1874
1875    /**
1876     * @hide
1877     *
1878     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1879     * out of the public fields to keep the undefined bits out of the developer's way.
1880     *
1881     * Flag to hide the center system info area.
1882     */
1883    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1884
1885    /**
1886     * @hide
1887     *
1888     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1889     * out of the public fields to keep the undefined bits out of the developer's way.
1890     *
1891     * Flag to hide only the navigation buttons.  Don't use this
1892     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1893     *
1894     * THIS DOES NOT DISABLE THE BACK BUTTON
1895     */
1896    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1897
1898    /**
1899     * @hide
1900     *
1901     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1902     * out of the public fields to keep the undefined bits out of the developer's way.
1903     *
1904     * Flag to hide only the back button.  Don't use this
1905     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1906     */
1907    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1908
1909    /**
1910     * @hide
1911     *
1912     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1913     * out of the public fields to keep the undefined bits out of the developer's way.
1914     *
1915     * Flag to hide only the clock.  You might use this if your activity has
1916     * its own clock making the status bar's clock redundant.
1917     */
1918    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1919
1920    /**
1921     * @hide
1922     */
1923    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1924
1925    /**
1926     * Find views that render the specified text.
1927     *
1928     * @see #findViewsWithText(ArrayList, CharSequence, int)
1929     */
1930    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1931
1932    /**
1933     * Find find views that contain the specified content description.
1934     *
1935     * @see #findViewsWithText(ArrayList, CharSequence, int)
1936     */
1937    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1938
1939    /**
1940     * Controls the over-scroll mode for this view.
1941     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1942     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1943     * and {@link #OVER_SCROLL_NEVER}.
1944     */
1945    private int mOverScrollMode;
1946
1947    /**
1948     * The parent this view is attached to.
1949     * {@hide}
1950     *
1951     * @see #getParent()
1952     */
1953    protected ViewParent mParent;
1954
1955    /**
1956     * {@hide}
1957     */
1958    AttachInfo mAttachInfo;
1959
1960    /**
1961     * {@hide}
1962     */
1963    @ViewDebug.ExportedProperty(flagMapping = {
1964        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1965                name = "FORCE_LAYOUT"),
1966        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1967                name = "LAYOUT_REQUIRED"),
1968        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1969            name = "DRAWING_CACHE_INVALID", outputIf = false),
1970        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1971        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1972        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1973        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1974    })
1975    int mPrivateFlags;
1976    int mPrivateFlags2;
1977
1978    /**
1979     * This view's request for the visibility of the status bar.
1980     * @hide
1981     */
1982    @ViewDebug.ExportedProperty(flagMapping = {
1983        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
1984                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
1985                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
1986        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1987                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1988                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
1989        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
1990                                equals = SYSTEM_UI_FLAG_VISIBLE,
1991                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
1992    })
1993    int mSystemUiVisibility;
1994
1995    /**
1996     * Count of how many windows this view has been attached to.
1997     */
1998    int mWindowAttachCount;
1999
2000    /**
2001     * The layout parameters associated with this view and used by the parent
2002     * {@link android.view.ViewGroup} to determine how this view should be
2003     * laid out.
2004     * {@hide}
2005     */
2006    protected ViewGroup.LayoutParams mLayoutParams;
2007
2008    /**
2009     * The view flags hold various views states.
2010     * {@hide}
2011     */
2012    @ViewDebug.ExportedProperty
2013    int mViewFlags;
2014
2015    static class TransformationInfo {
2016        /**
2017         * The transform matrix for the View. This transform is calculated internally
2018         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2019         * is used by default. Do *not* use this variable directly; instead call
2020         * getMatrix(), which will automatically recalculate the matrix if necessary
2021         * to get the correct matrix based on the latest rotation and scale properties.
2022         */
2023        private final Matrix mMatrix = new Matrix();
2024
2025        /**
2026         * The transform matrix for the View. This transform is calculated internally
2027         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2028         * is used by default. Do *not* use this variable directly; instead call
2029         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2030         * to get the correct matrix based on the latest rotation and scale properties.
2031         */
2032        private Matrix mInverseMatrix;
2033
2034        /**
2035         * An internal variable that tracks whether we need to recalculate the
2036         * transform matrix, based on whether the rotation or scaleX/Y properties
2037         * have changed since the matrix was last calculated.
2038         */
2039        boolean mMatrixDirty = false;
2040
2041        /**
2042         * An internal variable that tracks whether we need to recalculate the
2043         * transform matrix, based on whether the rotation or scaleX/Y properties
2044         * have changed since the matrix was last calculated.
2045         */
2046        private boolean mInverseMatrixDirty = true;
2047
2048        /**
2049         * A variable that tracks whether we need to recalculate the
2050         * transform matrix, based on whether the rotation or scaleX/Y properties
2051         * have changed since the matrix was last calculated. This variable
2052         * is only valid after a call to updateMatrix() or to a function that
2053         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2054         */
2055        private boolean mMatrixIsIdentity = true;
2056
2057        /**
2058         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2059         */
2060        private Camera mCamera = null;
2061
2062        /**
2063         * This matrix is used when computing the matrix for 3D rotations.
2064         */
2065        private Matrix matrix3D = null;
2066
2067        /**
2068         * These prev values are used to recalculate a centered pivot point when necessary. The
2069         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2070         * set), so thes values are only used then as well.
2071         */
2072        private int mPrevWidth = -1;
2073        private int mPrevHeight = -1;
2074
2075        /**
2076         * The degrees rotation around the vertical axis through the pivot point.
2077         */
2078        @ViewDebug.ExportedProperty
2079        float mRotationY = 0f;
2080
2081        /**
2082         * The degrees rotation around the horizontal axis through the pivot point.
2083         */
2084        @ViewDebug.ExportedProperty
2085        float mRotationX = 0f;
2086
2087        /**
2088         * The degrees rotation around the pivot point.
2089         */
2090        @ViewDebug.ExportedProperty
2091        float mRotation = 0f;
2092
2093        /**
2094         * The amount of translation of the object away from its left property (post-layout).
2095         */
2096        @ViewDebug.ExportedProperty
2097        float mTranslationX = 0f;
2098
2099        /**
2100         * The amount of translation of the object away from its top property (post-layout).
2101         */
2102        @ViewDebug.ExportedProperty
2103        float mTranslationY = 0f;
2104
2105        /**
2106         * The amount of scale in the x direction around the pivot point. A
2107         * value of 1 means no scaling is applied.
2108         */
2109        @ViewDebug.ExportedProperty
2110        float mScaleX = 1f;
2111
2112        /**
2113         * The amount of scale in the y direction around the pivot point. A
2114         * value of 1 means no scaling is applied.
2115         */
2116        @ViewDebug.ExportedProperty
2117        float mScaleY = 1f;
2118
2119        /**
2120         * The amount of scale in the x direction around the pivot point. A
2121         * value of 1 means no scaling is applied.
2122         */
2123        @ViewDebug.ExportedProperty
2124        float mPivotX = 0f;
2125
2126        /**
2127         * The amount of scale in the y direction around the pivot point. A
2128         * value of 1 means no scaling is applied.
2129         */
2130        @ViewDebug.ExportedProperty
2131        float mPivotY = 0f;
2132
2133        /**
2134         * The opacity of the View. This is a value from 0 to 1, where 0 means
2135         * completely transparent and 1 means completely opaque.
2136         */
2137        @ViewDebug.ExportedProperty
2138        float mAlpha = 1f;
2139    }
2140
2141    TransformationInfo mTransformationInfo;
2142
2143    private boolean mLastIsOpaque;
2144
2145    /**
2146     * Convenience value to check for float values that are close enough to zero to be considered
2147     * zero.
2148     */
2149    private static final float NONZERO_EPSILON = .001f;
2150
2151    /**
2152     * The distance in pixels from the left edge of this view's parent
2153     * to the left edge of this view.
2154     * {@hide}
2155     */
2156    @ViewDebug.ExportedProperty(category = "layout")
2157    protected int mLeft;
2158    /**
2159     * The distance in pixels from the left edge of this view's parent
2160     * to the right edge of this view.
2161     * {@hide}
2162     */
2163    @ViewDebug.ExportedProperty(category = "layout")
2164    protected int mRight;
2165    /**
2166     * The distance in pixels from the top edge of this view's parent
2167     * to the top edge of this view.
2168     * {@hide}
2169     */
2170    @ViewDebug.ExportedProperty(category = "layout")
2171    protected int mTop;
2172    /**
2173     * The distance in pixels from the top edge of this view's parent
2174     * to the bottom edge of this view.
2175     * {@hide}
2176     */
2177    @ViewDebug.ExportedProperty(category = "layout")
2178    protected int mBottom;
2179
2180    /**
2181     * The offset, in pixels, by which the content of this view is scrolled
2182     * horizontally.
2183     * {@hide}
2184     */
2185    @ViewDebug.ExportedProperty(category = "scrolling")
2186    protected int mScrollX;
2187    /**
2188     * The offset, in pixels, by which the content of this view is scrolled
2189     * vertically.
2190     * {@hide}
2191     */
2192    @ViewDebug.ExportedProperty(category = "scrolling")
2193    protected int mScrollY;
2194
2195    /**
2196     * The left padding in pixels, that is the distance in pixels between the
2197     * left edge of this view and the left edge of its content.
2198     * {@hide}
2199     */
2200    @ViewDebug.ExportedProperty(category = "padding")
2201    protected int mPaddingLeft;
2202    /**
2203     * The right padding in pixels, that is the distance in pixels between the
2204     * right edge of this view and the right edge of its content.
2205     * {@hide}
2206     */
2207    @ViewDebug.ExportedProperty(category = "padding")
2208    protected int mPaddingRight;
2209    /**
2210     * The top padding in pixels, that is the distance in pixels between the
2211     * top edge of this view and the top edge of its content.
2212     * {@hide}
2213     */
2214    @ViewDebug.ExportedProperty(category = "padding")
2215    protected int mPaddingTop;
2216    /**
2217     * The bottom padding in pixels, that is the distance in pixels between the
2218     * bottom edge of this view and the bottom edge of its content.
2219     * {@hide}
2220     */
2221    @ViewDebug.ExportedProperty(category = "padding")
2222    protected int mPaddingBottom;
2223
2224    /**
2225     * Briefly describes the view and is primarily used for accessibility support.
2226     */
2227    private CharSequence mContentDescription;
2228
2229    /**
2230     * Cache the paddingRight set by the user to append to the scrollbar's size.
2231     *
2232     * @hide
2233     */
2234    @ViewDebug.ExportedProperty(category = "padding")
2235    protected int mUserPaddingRight;
2236
2237    /**
2238     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2239     *
2240     * @hide
2241     */
2242    @ViewDebug.ExportedProperty(category = "padding")
2243    protected int mUserPaddingBottom;
2244
2245    /**
2246     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2247     *
2248     * @hide
2249     */
2250    @ViewDebug.ExportedProperty(category = "padding")
2251    protected int mUserPaddingLeft;
2252
2253    /**
2254     * Cache if the user padding is relative.
2255     *
2256     */
2257    @ViewDebug.ExportedProperty(category = "padding")
2258    boolean mUserPaddingRelative;
2259
2260    /**
2261     * Cache the paddingStart set by the user to append to the scrollbar's size.
2262     *
2263     */
2264    @ViewDebug.ExportedProperty(category = "padding")
2265    int mUserPaddingStart;
2266
2267    /**
2268     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2269     *
2270     */
2271    @ViewDebug.ExportedProperty(category = "padding")
2272    int mUserPaddingEnd;
2273
2274    /**
2275     * @hide
2276     */
2277    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2278    /**
2279     * @hide
2280     */
2281    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2282
2283    private Drawable mBGDrawable;
2284
2285    private int mBackgroundResource;
2286    private boolean mBackgroundSizeChanged;
2287
2288    /**
2289     * Listener used to dispatch focus change events.
2290     * This field should be made private, so it is hidden from the SDK.
2291     * {@hide}
2292     */
2293    protected OnFocusChangeListener mOnFocusChangeListener;
2294
2295    /**
2296     * Listeners for layout change events.
2297     */
2298    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2299
2300    /**
2301     * Listeners for attach events.
2302     */
2303    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2304
2305    /**
2306     * Listener used to dispatch click events.
2307     * This field should be made private, so it is hidden from the SDK.
2308     * {@hide}
2309     */
2310    protected OnClickListener mOnClickListener;
2311
2312    /**
2313     * Listener used to dispatch long click events.
2314     * This field should be made private, so it is hidden from the SDK.
2315     * {@hide}
2316     */
2317    protected OnLongClickListener mOnLongClickListener;
2318
2319    /**
2320     * Listener used to build the context menu.
2321     * This field should be made private, so it is hidden from the SDK.
2322     * {@hide}
2323     */
2324    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2325
2326    private OnKeyListener mOnKeyListener;
2327
2328    private OnTouchListener mOnTouchListener;
2329
2330    private OnHoverListener mOnHoverListener;
2331
2332    private OnGenericMotionListener mOnGenericMotionListener;
2333
2334    private OnDragListener mOnDragListener;
2335
2336    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2337
2338    /**
2339     * The application environment this view lives in.
2340     * This field should be made private, so it is hidden from the SDK.
2341     * {@hide}
2342     */
2343    protected Context mContext;
2344
2345    private final Resources mResources;
2346
2347    private ScrollabilityCache mScrollCache;
2348
2349    private int[] mDrawableState = null;
2350
2351    /**
2352     * Set to true when drawing cache is enabled and cannot be created.
2353     *
2354     * @hide
2355     */
2356    public boolean mCachingFailed;
2357
2358    private Bitmap mDrawingCache;
2359    private Bitmap mUnscaledDrawingCache;
2360    private HardwareLayer mHardwareLayer;
2361    DisplayList mDisplayList;
2362
2363    /**
2364     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2365     * the user may specify which view to go to next.
2366     */
2367    private int mNextFocusLeftId = View.NO_ID;
2368
2369    /**
2370     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2371     * the user may specify which view to go to next.
2372     */
2373    private int mNextFocusRightId = View.NO_ID;
2374
2375    /**
2376     * When this view has focus and the next focus is {@link #FOCUS_UP},
2377     * the user may specify which view to go to next.
2378     */
2379    private int mNextFocusUpId = View.NO_ID;
2380
2381    /**
2382     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2383     * the user may specify which view to go to next.
2384     */
2385    private int mNextFocusDownId = View.NO_ID;
2386
2387    /**
2388     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2389     * the user may specify which view to go to next.
2390     */
2391    int mNextFocusForwardId = View.NO_ID;
2392
2393    private CheckForLongPress mPendingCheckForLongPress;
2394    private CheckForTap mPendingCheckForTap = null;
2395    private PerformClick mPerformClick;
2396    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2397
2398    private UnsetPressedState mUnsetPressedState;
2399
2400    /**
2401     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2402     * up event while a long press is invoked as soon as the long press duration is reached, so
2403     * a long press could be performed before the tap is checked, in which case the tap's action
2404     * should not be invoked.
2405     */
2406    private boolean mHasPerformedLongPress;
2407
2408    /**
2409     * The minimum height of the view. We'll try our best to have the height
2410     * of this view to at least this amount.
2411     */
2412    @ViewDebug.ExportedProperty(category = "measurement")
2413    private int mMinHeight;
2414
2415    /**
2416     * The minimum width of the view. We'll try our best to have the width
2417     * of this view to at least this amount.
2418     */
2419    @ViewDebug.ExportedProperty(category = "measurement")
2420    private int mMinWidth;
2421
2422    /**
2423     * The delegate to handle touch events that are physically in this view
2424     * but should be handled by another view.
2425     */
2426    private TouchDelegate mTouchDelegate = null;
2427
2428    /**
2429     * Solid color to use as a background when creating the drawing cache. Enables
2430     * the cache to use 16 bit bitmaps instead of 32 bit.
2431     */
2432    private int mDrawingCacheBackgroundColor = 0;
2433
2434    /**
2435     * Special tree observer used when mAttachInfo is null.
2436     */
2437    private ViewTreeObserver mFloatingTreeObserver;
2438
2439    /**
2440     * Cache the touch slop from the context that created the view.
2441     */
2442    private int mTouchSlop;
2443
2444    /**
2445     * Object that handles automatic animation of view properties.
2446     */
2447    private ViewPropertyAnimator mAnimator = null;
2448
2449    /**
2450     * Flag indicating that a drag can cross window boundaries.  When
2451     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2452     * with this flag set, all visible applications will be able to participate
2453     * in the drag operation and receive the dragged content.
2454     *
2455     * @hide
2456     */
2457    public static final int DRAG_FLAG_GLOBAL = 1;
2458
2459    /**
2460     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2461     */
2462    private float mVerticalScrollFactor;
2463
2464    /**
2465     * Position of the vertical scroll bar.
2466     */
2467    private int mVerticalScrollbarPosition;
2468
2469    /**
2470     * Position the scroll bar at the default position as determined by the system.
2471     */
2472    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2473
2474    /**
2475     * Position the scroll bar along the left edge.
2476     */
2477    public static final int SCROLLBAR_POSITION_LEFT = 1;
2478
2479    /**
2480     * Position the scroll bar along the right edge.
2481     */
2482    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2483
2484    /**
2485     * Indicates that the view does not have a layer.
2486     *
2487     * @see #getLayerType()
2488     * @see #setLayerType(int, android.graphics.Paint)
2489     * @see #LAYER_TYPE_SOFTWARE
2490     * @see #LAYER_TYPE_HARDWARE
2491     */
2492    public static final int LAYER_TYPE_NONE = 0;
2493
2494    /**
2495     * <p>Indicates that the view has a software layer. A software layer is backed
2496     * by a bitmap and causes the view to be rendered using Android's software
2497     * rendering pipeline, even if hardware acceleration is enabled.</p>
2498     *
2499     * <p>Software layers have various usages:</p>
2500     * <p>When the application is not using hardware acceleration, a software layer
2501     * is useful to apply a specific color filter and/or blending mode and/or
2502     * translucency to a view and all its children.</p>
2503     * <p>When the application is using hardware acceleration, a software layer
2504     * is useful to render drawing primitives not supported by the hardware
2505     * accelerated pipeline. It can also be used to cache a complex view tree
2506     * into a texture and reduce the complexity of drawing operations. For instance,
2507     * when animating a complex view tree with a translation, a software layer can
2508     * be used to render the view tree only once.</p>
2509     * <p>Software layers should be avoided when the affected view tree updates
2510     * often. Every update will require to re-render the software layer, which can
2511     * potentially be slow (particularly when hardware acceleration is turned on
2512     * since the layer will have to be uploaded into a hardware texture after every
2513     * update.)</p>
2514     *
2515     * @see #getLayerType()
2516     * @see #setLayerType(int, android.graphics.Paint)
2517     * @see #LAYER_TYPE_NONE
2518     * @see #LAYER_TYPE_HARDWARE
2519     */
2520    public static final int LAYER_TYPE_SOFTWARE = 1;
2521
2522    /**
2523     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2524     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2525     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2526     * rendering pipeline, but only if hardware acceleration is turned on for the
2527     * view hierarchy. When hardware acceleration is turned off, hardware layers
2528     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2529     *
2530     * <p>A hardware layer is useful to apply a specific color filter and/or
2531     * blending mode and/or translucency to a view and all its children.</p>
2532     * <p>A hardware layer can be used to cache a complex view tree into a
2533     * texture and reduce the complexity of drawing operations. For instance,
2534     * when animating a complex view tree with a translation, a hardware layer can
2535     * be used to render the view tree only once.</p>
2536     * <p>A hardware layer can also be used to increase the rendering quality when
2537     * rotation transformations are applied on a view. It can also be used to
2538     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2539     *
2540     * @see #getLayerType()
2541     * @see #setLayerType(int, android.graphics.Paint)
2542     * @see #LAYER_TYPE_NONE
2543     * @see #LAYER_TYPE_SOFTWARE
2544     */
2545    public static final int LAYER_TYPE_HARDWARE = 2;
2546
2547    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2548            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2549            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2550            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2551    })
2552    int mLayerType = LAYER_TYPE_NONE;
2553    Paint mLayerPaint;
2554    Rect mLocalDirtyRect;
2555
2556    /**
2557     * Set to true when the view is sending hover accessibility events because it
2558     * is the innermost hovered view.
2559     */
2560    private boolean mSendingHoverAccessibilityEvents;
2561
2562    /**
2563     * Delegate for injecting accessiblity functionality.
2564     */
2565    AccessibilityDelegate mAccessibilityDelegate;
2566
2567    /**
2568     * Text direction is inherited thru {@link ViewGroup}
2569     * @hide
2570     */
2571    public static final int TEXT_DIRECTION_INHERIT = 0;
2572
2573    /**
2574     * Text direction is using "first strong algorithm". The first strong directional character
2575     * determines the paragraph direction. If there is no strong directional character, the
2576     * paragraph direction is the view's resolved ayout direction.
2577     *
2578     * @hide
2579     */
2580    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2581
2582    /**
2583     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2584     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2585     * If there are neither, the paragraph direction is the view's resolved layout direction.
2586     *
2587     * @hide
2588     */
2589    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2590
2591    /**
2592     * Text direction is forced to LTR.
2593     *
2594     * @hide
2595     */
2596    public static final int TEXT_DIRECTION_LTR = 3;
2597
2598    /**
2599     * Text direction is forced to RTL.
2600     *
2601     * @hide
2602     */
2603    public static final int TEXT_DIRECTION_RTL = 4;
2604
2605    /**
2606     * Default text direction is inherited
2607     *
2608     * @hide
2609     */
2610    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2611
2612    /**
2613     * The text direction that has been defined by {@link #setTextDirection(int)}.
2614     *
2615     * {@hide}
2616     */
2617    @ViewDebug.ExportedProperty(category = "text", mapping = {
2618            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2619            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2620            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2621            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2622            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2623    })
2624    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2625
2626    /**
2627     * The resolved text direction.  This needs resolution if the value is
2628     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if that is
2629     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2630     * chain of the view.
2631     *
2632     * {@hide}
2633     */
2634    @ViewDebug.ExportedProperty(category = "text", mapping = {
2635            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2636            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2637            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2638            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2639            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2640    })
2641    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2642
2643    /**
2644     * Consistency verifier for debugging purposes.
2645     * @hide
2646     */
2647    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2648            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2649                    new InputEventConsistencyVerifier(this, 0) : null;
2650
2651    /**
2652     * Simple constructor to use when creating a view from code.
2653     *
2654     * @param context The Context the view is running in, through which it can
2655     *        access the current theme, resources, etc.
2656     */
2657    public View(Context context) {
2658        mContext = context;
2659        mResources = context != null ? context.getResources() : null;
2660        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2661        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2662        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2663        mUserPaddingStart = -1;
2664        mUserPaddingEnd = -1;
2665        mUserPaddingRelative = false;
2666    }
2667
2668    /**
2669     * Constructor that is called when inflating a view from XML. This is called
2670     * when a view is being constructed from an XML file, supplying attributes
2671     * that were specified in the XML file. This version uses a default style of
2672     * 0, so the only attribute values applied are those in the Context's Theme
2673     * and the given AttributeSet.
2674     *
2675     * <p>
2676     * The method onFinishInflate() will be called after all children have been
2677     * added.
2678     *
2679     * @param context The Context the view is running in, through which it can
2680     *        access the current theme, resources, etc.
2681     * @param attrs The attributes of the XML tag that is inflating the view.
2682     * @see #View(Context, AttributeSet, int)
2683     */
2684    public View(Context context, AttributeSet attrs) {
2685        this(context, attrs, 0);
2686    }
2687
2688    /**
2689     * Perform inflation from XML and apply a class-specific base style. This
2690     * constructor of View allows subclasses to use their own base style when
2691     * they are inflating. For example, a Button class's constructor would call
2692     * this version of the super class constructor and supply
2693     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2694     * the theme's button style to modify all of the base view attributes (in
2695     * particular its background) as well as the Button class's attributes.
2696     *
2697     * @param context The Context the view is running in, through which it can
2698     *        access the current theme, resources, etc.
2699     * @param attrs The attributes of the XML tag that is inflating the view.
2700     * @param defStyle The default style to apply to this view. If 0, no style
2701     *        will be applied (beyond what is included in the theme). This may
2702     *        either be an attribute resource, whose value will be retrieved
2703     *        from the current theme, or an explicit style resource.
2704     * @see #View(Context, AttributeSet)
2705     */
2706    public View(Context context, AttributeSet attrs, int defStyle) {
2707        this(context);
2708
2709        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2710                defStyle, 0);
2711
2712        Drawable background = null;
2713
2714        int leftPadding = -1;
2715        int topPadding = -1;
2716        int rightPadding = -1;
2717        int bottomPadding = -1;
2718        int startPadding = -1;
2719        int endPadding = -1;
2720
2721        int padding = -1;
2722
2723        int viewFlagValues = 0;
2724        int viewFlagMasks = 0;
2725
2726        boolean setScrollContainer = false;
2727
2728        int x = 0;
2729        int y = 0;
2730
2731        float tx = 0;
2732        float ty = 0;
2733        float rotation = 0;
2734        float rotationX = 0;
2735        float rotationY = 0;
2736        float sx = 1f;
2737        float sy = 1f;
2738        boolean transformSet = false;
2739
2740        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2741
2742        int overScrollMode = mOverScrollMode;
2743        final int N = a.getIndexCount();
2744        for (int i = 0; i < N; i++) {
2745            int attr = a.getIndex(i);
2746            switch (attr) {
2747                case com.android.internal.R.styleable.View_background:
2748                    background = a.getDrawable(attr);
2749                    break;
2750                case com.android.internal.R.styleable.View_padding:
2751                    padding = a.getDimensionPixelSize(attr, -1);
2752                    break;
2753                 case com.android.internal.R.styleable.View_paddingLeft:
2754                    leftPadding = a.getDimensionPixelSize(attr, -1);
2755                    break;
2756                case com.android.internal.R.styleable.View_paddingTop:
2757                    topPadding = a.getDimensionPixelSize(attr, -1);
2758                    break;
2759                case com.android.internal.R.styleable.View_paddingRight:
2760                    rightPadding = a.getDimensionPixelSize(attr, -1);
2761                    break;
2762                case com.android.internal.R.styleable.View_paddingBottom:
2763                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2764                    break;
2765                case com.android.internal.R.styleable.View_paddingStart:
2766                    startPadding = a.getDimensionPixelSize(attr, -1);
2767                    break;
2768                case com.android.internal.R.styleable.View_paddingEnd:
2769                    endPadding = a.getDimensionPixelSize(attr, -1);
2770                    break;
2771                case com.android.internal.R.styleable.View_scrollX:
2772                    x = a.getDimensionPixelOffset(attr, 0);
2773                    break;
2774                case com.android.internal.R.styleable.View_scrollY:
2775                    y = a.getDimensionPixelOffset(attr, 0);
2776                    break;
2777                case com.android.internal.R.styleable.View_alpha:
2778                    setAlpha(a.getFloat(attr, 1f));
2779                    break;
2780                case com.android.internal.R.styleable.View_transformPivotX:
2781                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2782                    break;
2783                case com.android.internal.R.styleable.View_transformPivotY:
2784                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2785                    break;
2786                case com.android.internal.R.styleable.View_translationX:
2787                    tx = a.getDimensionPixelOffset(attr, 0);
2788                    transformSet = true;
2789                    break;
2790                case com.android.internal.R.styleable.View_translationY:
2791                    ty = a.getDimensionPixelOffset(attr, 0);
2792                    transformSet = true;
2793                    break;
2794                case com.android.internal.R.styleable.View_rotation:
2795                    rotation = a.getFloat(attr, 0);
2796                    transformSet = true;
2797                    break;
2798                case com.android.internal.R.styleable.View_rotationX:
2799                    rotationX = a.getFloat(attr, 0);
2800                    transformSet = true;
2801                    break;
2802                case com.android.internal.R.styleable.View_rotationY:
2803                    rotationY = a.getFloat(attr, 0);
2804                    transformSet = true;
2805                    break;
2806                case com.android.internal.R.styleable.View_scaleX:
2807                    sx = a.getFloat(attr, 1f);
2808                    transformSet = true;
2809                    break;
2810                case com.android.internal.R.styleable.View_scaleY:
2811                    sy = a.getFloat(attr, 1f);
2812                    transformSet = true;
2813                    break;
2814                case com.android.internal.R.styleable.View_id:
2815                    mID = a.getResourceId(attr, NO_ID);
2816                    break;
2817                case com.android.internal.R.styleable.View_tag:
2818                    mTag = a.getText(attr);
2819                    break;
2820                case com.android.internal.R.styleable.View_fitsSystemWindows:
2821                    if (a.getBoolean(attr, false)) {
2822                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2823                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2824                    }
2825                    break;
2826                case com.android.internal.R.styleable.View_focusable:
2827                    if (a.getBoolean(attr, false)) {
2828                        viewFlagValues |= FOCUSABLE;
2829                        viewFlagMasks |= FOCUSABLE_MASK;
2830                    }
2831                    break;
2832                case com.android.internal.R.styleable.View_focusableInTouchMode:
2833                    if (a.getBoolean(attr, false)) {
2834                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2835                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2836                    }
2837                    break;
2838                case com.android.internal.R.styleable.View_clickable:
2839                    if (a.getBoolean(attr, false)) {
2840                        viewFlagValues |= CLICKABLE;
2841                        viewFlagMasks |= CLICKABLE;
2842                    }
2843                    break;
2844                case com.android.internal.R.styleable.View_longClickable:
2845                    if (a.getBoolean(attr, false)) {
2846                        viewFlagValues |= LONG_CLICKABLE;
2847                        viewFlagMasks |= LONG_CLICKABLE;
2848                    }
2849                    break;
2850                case com.android.internal.R.styleable.View_saveEnabled:
2851                    if (!a.getBoolean(attr, true)) {
2852                        viewFlagValues |= SAVE_DISABLED;
2853                        viewFlagMasks |= SAVE_DISABLED_MASK;
2854                    }
2855                    break;
2856                case com.android.internal.R.styleable.View_duplicateParentState:
2857                    if (a.getBoolean(attr, false)) {
2858                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2859                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2860                    }
2861                    break;
2862                case com.android.internal.R.styleable.View_visibility:
2863                    final int visibility = a.getInt(attr, 0);
2864                    if (visibility != 0) {
2865                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2866                        viewFlagMasks |= VISIBILITY_MASK;
2867                    }
2868                    break;
2869                case com.android.internal.R.styleable.View_layoutDirection:
2870                    // Clear any HORIZONTAL_DIRECTION flag already set
2871                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2872                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2873                    final int layoutDirection = a.getInt(attr, -1);
2874                    if (layoutDirection != -1) {
2875                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2876                    } else {
2877                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2878                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2879                    }
2880                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2881                    break;
2882                case com.android.internal.R.styleable.View_drawingCacheQuality:
2883                    final int cacheQuality = a.getInt(attr, 0);
2884                    if (cacheQuality != 0) {
2885                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2886                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2887                    }
2888                    break;
2889                case com.android.internal.R.styleable.View_contentDescription:
2890                    mContentDescription = a.getString(attr);
2891                    break;
2892                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2893                    if (!a.getBoolean(attr, true)) {
2894                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2895                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2896                    }
2897                    break;
2898                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2899                    if (!a.getBoolean(attr, true)) {
2900                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2901                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2902                    }
2903                    break;
2904                case R.styleable.View_scrollbars:
2905                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2906                    if (scrollbars != SCROLLBARS_NONE) {
2907                        viewFlagValues |= scrollbars;
2908                        viewFlagMasks |= SCROLLBARS_MASK;
2909                        initializeScrollbars(a);
2910                    }
2911                    break;
2912                //noinspection deprecation
2913                case R.styleable.View_fadingEdge:
2914                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2915                        // Ignore the attribute starting with ICS
2916                        break;
2917                    }
2918                    // With builds < ICS, fall through and apply fading edges
2919                case R.styleable.View_requiresFadingEdge:
2920                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2921                    if (fadingEdge != FADING_EDGE_NONE) {
2922                        viewFlagValues |= fadingEdge;
2923                        viewFlagMasks |= FADING_EDGE_MASK;
2924                        initializeFadingEdge(a);
2925                    }
2926                    break;
2927                case R.styleable.View_scrollbarStyle:
2928                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2929                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2930                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2931                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2932                    }
2933                    break;
2934                case R.styleable.View_isScrollContainer:
2935                    setScrollContainer = true;
2936                    if (a.getBoolean(attr, false)) {
2937                        setScrollContainer(true);
2938                    }
2939                    break;
2940                case com.android.internal.R.styleable.View_keepScreenOn:
2941                    if (a.getBoolean(attr, false)) {
2942                        viewFlagValues |= KEEP_SCREEN_ON;
2943                        viewFlagMasks |= KEEP_SCREEN_ON;
2944                    }
2945                    break;
2946                case R.styleable.View_filterTouchesWhenObscured:
2947                    if (a.getBoolean(attr, false)) {
2948                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2949                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2950                    }
2951                    break;
2952                case R.styleable.View_nextFocusLeft:
2953                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2954                    break;
2955                case R.styleable.View_nextFocusRight:
2956                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2957                    break;
2958                case R.styleable.View_nextFocusUp:
2959                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2960                    break;
2961                case R.styleable.View_nextFocusDown:
2962                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2963                    break;
2964                case R.styleable.View_nextFocusForward:
2965                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2966                    break;
2967                case R.styleable.View_minWidth:
2968                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2969                    break;
2970                case R.styleable.View_minHeight:
2971                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2972                    break;
2973                case R.styleable.View_onClick:
2974                    if (context.isRestricted()) {
2975                        throw new IllegalStateException("The android:onClick attribute cannot "
2976                                + "be used within a restricted context");
2977                    }
2978
2979                    final String handlerName = a.getString(attr);
2980                    if (handlerName != null) {
2981                        setOnClickListener(new OnClickListener() {
2982                            private Method mHandler;
2983
2984                            public void onClick(View v) {
2985                                if (mHandler == null) {
2986                                    try {
2987                                        mHandler = getContext().getClass().getMethod(handlerName,
2988                                                View.class);
2989                                    } catch (NoSuchMethodException e) {
2990                                        int id = getId();
2991                                        String idText = id == NO_ID ? "" : " with id '"
2992                                                + getContext().getResources().getResourceEntryName(
2993                                                    id) + "'";
2994                                        throw new IllegalStateException("Could not find a method " +
2995                                                handlerName + "(View) in the activity "
2996                                                + getContext().getClass() + " for onClick handler"
2997                                                + " on view " + View.this.getClass() + idText, e);
2998                                    }
2999                                }
3000
3001                                try {
3002                                    mHandler.invoke(getContext(), View.this);
3003                                } catch (IllegalAccessException e) {
3004                                    throw new IllegalStateException("Could not execute non "
3005                                            + "public method of the activity", e);
3006                                } catch (InvocationTargetException e) {
3007                                    throw new IllegalStateException("Could not execute "
3008                                            + "method of the activity", e);
3009                                }
3010                            }
3011                        });
3012                    }
3013                    break;
3014                case R.styleable.View_overScrollMode:
3015                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3016                    break;
3017                case R.styleable.View_verticalScrollbarPosition:
3018                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3019                    break;
3020                case R.styleable.View_layerType:
3021                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3022                    break;
3023                case R.styleable.View_textDirection:
3024                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3025                    break;
3026            }
3027        }
3028
3029        a.recycle();
3030
3031        setOverScrollMode(overScrollMode);
3032
3033        if (background != null) {
3034            setBackgroundDrawable(background);
3035        }
3036
3037        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3038
3039        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3040        // layout direction). Those cached values will be used later during padding resolution.
3041        mUserPaddingStart = startPadding;
3042        mUserPaddingEnd = endPadding;
3043
3044        if (padding >= 0) {
3045            leftPadding = padding;
3046            topPadding = padding;
3047            rightPadding = padding;
3048            bottomPadding = padding;
3049        }
3050
3051        // If the user specified the padding (either with android:padding or
3052        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3053        // use the default padding or the padding from the background drawable
3054        // (stored at this point in mPadding*)
3055        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3056                topPadding >= 0 ? topPadding : mPaddingTop,
3057                rightPadding >= 0 ? rightPadding : mPaddingRight,
3058                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3059
3060        if (viewFlagMasks != 0) {
3061            setFlags(viewFlagValues, viewFlagMasks);
3062        }
3063
3064        // Needs to be called after mViewFlags is set
3065        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3066            recomputePadding();
3067        }
3068
3069        if (x != 0 || y != 0) {
3070            scrollTo(x, y);
3071        }
3072
3073        if (transformSet) {
3074            setTranslationX(tx);
3075            setTranslationY(ty);
3076            setRotation(rotation);
3077            setRotationX(rotationX);
3078            setRotationY(rotationY);
3079            setScaleX(sx);
3080            setScaleY(sy);
3081        }
3082
3083        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3084            setScrollContainer(true);
3085        }
3086
3087        computeOpaqueFlags();
3088    }
3089
3090    /**
3091     * Non-public constructor for use in testing
3092     */
3093    View() {
3094        mResources = null;
3095    }
3096
3097    /**
3098     * <p>
3099     * Initializes the fading edges from a given set of styled attributes. This
3100     * method should be called by subclasses that need fading edges and when an
3101     * instance of these subclasses is created programmatically rather than
3102     * being inflated from XML. This method is automatically called when the XML
3103     * is inflated.
3104     * </p>
3105     *
3106     * @param a the styled attributes set to initialize the fading edges from
3107     */
3108    protected void initializeFadingEdge(TypedArray a) {
3109        initScrollCache();
3110
3111        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3112                R.styleable.View_fadingEdgeLength,
3113                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3114    }
3115
3116    /**
3117     * Returns the size of the vertical faded edges used to indicate that more
3118     * content in this view is visible.
3119     *
3120     * @return The size in pixels of the vertical faded edge or 0 if vertical
3121     *         faded edges are not enabled for this view.
3122     * @attr ref android.R.styleable#View_fadingEdgeLength
3123     */
3124    public int getVerticalFadingEdgeLength() {
3125        if (isVerticalFadingEdgeEnabled()) {
3126            ScrollabilityCache cache = mScrollCache;
3127            if (cache != null) {
3128                return cache.fadingEdgeLength;
3129            }
3130        }
3131        return 0;
3132    }
3133
3134    /**
3135     * Set the size of the faded edge used to indicate that more content in this
3136     * view is available.  Will not change whether the fading edge is enabled; use
3137     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3138     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3139     * for the vertical or horizontal fading edges.
3140     *
3141     * @param length The size in pixels of the faded edge used to indicate that more
3142     *        content in this view is visible.
3143     */
3144    public void setFadingEdgeLength(int length) {
3145        initScrollCache();
3146        mScrollCache.fadingEdgeLength = length;
3147    }
3148
3149    /**
3150     * Returns the size of the horizontal faded edges used to indicate that more
3151     * content in this view is visible.
3152     *
3153     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3154     *         faded edges are not enabled for this view.
3155     * @attr ref android.R.styleable#View_fadingEdgeLength
3156     */
3157    public int getHorizontalFadingEdgeLength() {
3158        if (isHorizontalFadingEdgeEnabled()) {
3159            ScrollabilityCache cache = mScrollCache;
3160            if (cache != null) {
3161                return cache.fadingEdgeLength;
3162            }
3163        }
3164        return 0;
3165    }
3166
3167    /**
3168     * Returns the width of the vertical scrollbar.
3169     *
3170     * @return The width in pixels of the vertical scrollbar or 0 if there
3171     *         is no vertical scrollbar.
3172     */
3173    public int getVerticalScrollbarWidth() {
3174        ScrollabilityCache cache = mScrollCache;
3175        if (cache != null) {
3176            ScrollBarDrawable scrollBar = cache.scrollBar;
3177            if (scrollBar != null) {
3178                int size = scrollBar.getSize(true);
3179                if (size <= 0) {
3180                    size = cache.scrollBarSize;
3181                }
3182                return size;
3183            }
3184            return 0;
3185        }
3186        return 0;
3187    }
3188
3189    /**
3190     * Returns the height of the horizontal scrollbar.
3191     *
3192     * @return The height in pixels of the horizontal scrollbar or 0 if
3193     *         there is no horizontal scrollbar.
3194     */
3195    protected int getHorizontalScrollbarHeight() {
3196        ScrollabilityCache cache = mScrollCache;
3197        if (cache != null) {
3198            ScrollBarDrawable scrollBar = cache.scrollBar;
3199            if (scrollBar != null) {
3200                int size = scrollBar.getSize(false);
3201                if (size <= 0) {
3202                    size = cache.scrollBarSize;
3203                }
3204                return size;
3205            }
3206            return 0;
3207        }
3208        return 0;
3209    }
3210
3211    /**
3212     * <p>
3213     * Initializes the scrollbars from a given set of styled attributes. This
3214     * method should be called by subclasses that need scrollbars and when an
3215     * instance of these subclasses is created programmatically rather than
3216     * being inflated from XML. This method is automatically called when the XML
3217     * is inflated.
3218     * </p>
3219     *
3220     * @param a the styled attributes set to initialize the scrollbars from
3221     */
3222    protected void initializeScrollbars(TypedArray a) {
3223        initScrollCache();
3224
3225        final ScrollabilityCache scrollabilityCache = mScrollCache;
3226
3227        if (scrollabilityCache.scrollBar == null) {
3228            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3229        }
3230
3231        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3232
3233        if (!fadeScrollbars) {
3234            scrollabilityCache.state = ScrollabilityCache.ON;
3235        }
3236        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3237
3238
3239        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3240                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3241                        .getScrollBarFadeDuration());
3242        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3243                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3244                ViewConfiguration.getScrollDefaultDelay());
3245
3246
3247        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3248                com.android.internal.R.styleable.View_scrollbarSize,
3249                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3250
3251        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3252        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3253
3254        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3255        if (thumb != null) {
3256            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3257        }
3258
3259        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3260                false);
3261        if (alwaysDraw) {
3262            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3263        }
3264
3265        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3266        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3267
3268        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3269        if (thumb != null) {
3270            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3271        }
3272
3273        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3274                false);
3275        if (alwaysDraw) {
3276            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3277        }
3278
3279        // Re-apply user/background padding so that scrollbar(s) get added
3280        resolvePadding();
3281    }
3282
3283    /**
3284     * <p>
3285     * Initalizes the scrollability cache if necessary.
3286     * </p>
3287     */
3288    private void initScrollCache() {
3289        if (mScrollCache == null) {
3290            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3291        }
3292    }
3293
3294    /**
3295     * Set the position of the vertical scroll bar. Should be one of
3296     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3297     * {@link #SCROLLBAR_POSITION_RIGHT}.
3298     *
3299     * @param position Where the vertical scroll bar should be positioned.
3300     */
3301    public void setVerticalScrollbarPosition(int position) {
3302        if (mVerticalScrollbarPosition != position) {
3303            mVerticalScrollbarPosition = position;
3304            computeOpaqueFlags();
3305            resolvePadding();
3306        }
3307    }
3308
3309    /**
3310     * @return The position where the vertical scroll bar will show, if applicable.
3311     * @see #setVerticalScrollbarPosition(int)
3312     */
3313    public int getVerticalScrollbarPosition() {
3314        return mVerticalScrollbarPosition;
3315    }
3316
3317    /**
3318     * Register a callback to be invoked when focus of this view changed.
3319     *
3320     * @param l The callback that will run.
3321     */
3322    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3323        mOnFocusChangeListener = l;
3324    }
3325
3326    /**
3327     * Add a listener that will be called when the bounds of the view change due to
3328     * layout processing.
3329     *
3330     * @param listener The listener that will be called when layout bounds change.
3331     */
3332    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3333        if (mOnLayoutChangeListeners == null) {
3334            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3335        }
3336        mOnLayoutChangeListeners.add(listener);
3337    }
3338
3339    /**
3340     * Remove a listener for layout changes.
3341     *
3342     * @param listener The listener for layout bounds change.
3343     */
3344    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3345        if (mOnLayoutChangeListeners == null) {
3346            return;
3347        }
3348        mOnLayoutChangeListeners.remove(listener);
3349    }
3350
3351    /**
3352     * Add a listener for attach state changes.
3353     *
3354     * This listener will be called whenever this view is attached or detached
3355     * from a window. Remove the listener using
3356     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3357     *
3358     * @param listener Listener to attach
3359     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3360     */
3361    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3362        if (mOnAttachStateChangeListeners == null) {
3363            mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3364        }
3365        mOnAttachStateChangeListeners.add(listener);
3366    }
3367
3368    /**
3369     * Remove a listener for attach state changes. The listener will receive no further
3370     * notification of window attach/detach events.
3371     *
3372     * @param listener Listener to remove
3373     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3374     */
3375    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3376        if (mOnAttachStateChangeListeners == null) {
3377            return;
3378        }
3379        mOnAttachStateChangeListeners.remove(listener);
3380    }
3381
3382    /**
3383     * Returns the focus-change callback registered for this view.
3384     *
3385     * @return The callback, or null if one is not registered.
3386     */
3387    public OnFocusChangeListener getOnFocusChangeListener() {
3388        return mOnFocusChangeListener;
3389    }
3390
3391    /**
3392     * Register a callback to be invoked when this view is clicked. If this view is not
3393     * clickable, it becomes clickable.
3394     *
3395     * @param l The callback that will run
3396     *
3397     * @see #setClickable(boolean)
3398     */
3399    public void setOnClickListener(OnClickListener l) {
3400        if (!isClickable()) {
3401            setClickable(true);
3402        }
3403        mOnClickListener = l;
3404    }
3405
3406    /**
3407     * Register a callback to be invoked when this view is clicked and held. If this view is not
3408     * long clickable, it becomes long clickable.
3409     *
3410     * @param l The callback that will run
3411     *
3412     * @see #setLongClickable(boolean)
3413     */
3414    public void setOnLongClickListener(OnLongClickListener l) {
3415        if (!isLongClickable()) {
3416            setLongClickable(true);
3417        }
3418        mOnLongClickListener = l;
3419    }
3420
3421    /**
3422     * Register a callback to be invoked when the context menu for this view is
3423     * being built. If this view is not long clickable, it becomes long clickable.
3424     *
3425     * @param l The callback that will run
3426     *
3427     */
3428    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3429        if (!isLongClickable()) {
3430            setLongClickable(true);
3431        }
3432        mOnCreateContextMenuListener = l;
3433    }
3434
3435    /**
3436     * Call this view's OnClickListener, if it is defined.
3437     *
3438     * @return True there was an assigned OnClickListener that was called, false
3439     *         otherwise is returned.
3440     */
3441    public boolean performClick() {
3442        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3443
3444        if (mOnClickListener != null) {
3445            playSoundEffect(SoundEffectConstants.CLICK);
3446            mOnClickListener.onClick(this);
3447            return true;
3448        }
3449
3450        return false;
3451    }
3452
3453    /**
3454     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3455     * OnLongClickListener did not consume the event.
3456     *
3457     * @return True if one of the above receivers consumed the event, false otherwise.
3458     */
3459    public boolean performLongClick() {
3460        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3461
3462        boolean handled = false;
3463        if (mOnLongClickListener != null) {
3464            handled = mOnLongClickListener.onLongClick(View.this);
3465        }
3466        if (!handled) {
3467            handled = showContextMenu();
3468        }
3469        if (handled) {
3470            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3471        }
3472        return handled;
3473    }
3474
3475    /**
3476     * Performs button-related actions during a touch down event.
3477     *
3478     * @param event The event.
3479     * @return True if the down was consumed.
3480     *
3481     * @hide
3482     */
3483    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3484        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3485            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3486                return true;
3487            }
3488        }
3489        return false;
3490    }
3491
3492    /**
3493     * Bring up the context menu for this view.
3494     *
3495     * @return Whether a context menu was displayed.
3496     */
3497    public boolean showContextMenu() {
3498        return getParent().showContextMenuForChild(this);
3499    }
3500
3501    /**
3502     * Bring up the context menu for this view, referring to the item under the specified point.
3503     *
3504     * @param x The referenced x coordinate.
3505     * @param y The referenced y coordinate.
3506     * @param metaState The keyboard modifiers that were pressed.
3507     * @return Whether a context menu was displayed.
3508     *
3509     * @hide
3510     */
3511    public boolean showContextMenu(float x, float y, int metaState) {
3512        return showContextMenu();
3513    }
3514
3515    /**
3516     * Start an action mode.
3517     *
3518     * @param callback Callback that will control the lifecycle of the action mode
3519     * @return The new action mode if it is started, null otherwise
3520     *
3521     * @see ActionMode
3522     */
3523    public ActionMode startActionMode(ActionMode.Callback callback) {
3524        return getParent().startActionModeForChild(this, callback);
3525    }
3526
3527    /**
3528     * Register a callback to be invoked when a key is pressed in this view.
3529     * @param l the key listener to attach to this view
3530     */
3531    public void setOnKeyListener(OnKeyListener l) {
3532        mOnKeyListener = l;
3533    }
3534
3535    /**
3536     * Register a callback to be invoked when a touch event is sent to this view.
3537     * @param l the touch listener to attach to this view
3538     */
3539    public void setOnTouchListener(OnTouchListener l) {
3540        mOnTouchListener = l;
3541    }
3542
3543    /**
3544     * Register a callback to be invoked when a generic motion event is sent to this view.
3545     * @param l the generic motion listener to attach to this view
3546     */
3547    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3548        mOnGenericMotionListener = l;
3549    }
3550
3551    /**
3552     * Register a callback to be invoked when a hover event is sent to this view.
3553     * @param l the hover listener to attach to this view
3554     */
3555    public void setOnHoverListener(OnHoverListener l) {
3556        mOnHoverListener = l;
3557    }
3558
3559    /**
3560     * Register a drag event listener callback object for this View. The parameter is
3561     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3562     * View, the system calls the
3563     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3564     * @param l An implementation of {@link android.view.View.OnDragListener}.
3565     */
3566    public void setOnDragListener(OnDragListener l) {
3567        mOnDragListener = l;
3568    }
3569
3570    /**
3571     * Give this view focus. This will cause
3572     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3573     *
3574     * Note: this does not check whether this {@link View} should get focus, it just
3575     * gives it focus no matter what.  It should only be called internally by framework
3576     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3577     *
3578     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3579     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3580     *        focus moved when requestFocus() is called. It may not always
3581     *        apply, in which case use the default View.FOCUS_DOWN.
3582     * @param previouslyFocusedRect The rectangle of the view that had focus
3583     *        prior in this View's coordinate system.
3584     */
3585    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3586        if (DBG) {
3587            System.out.println(this + " requestFocus()");
3588        }
3589
3590        if ((mPrivateFlags & FOCUSED) == 0) {
3591            mPrivateFlags |= FOCUSED;
3592
3593            if (mParent != null) {
3594                mParent.requestChildFocus(this, this);
3595            }
3596
3597            onFocusChanged(true, direction, previouslyFocusedRect);
3598            refreshDrawableState();
3599        }
3600    }
3601
3602    /**
3603     * Request that a rectangle of this view be visible on the screen,
3604     * scrolling if necessary just enough.
3605     *
3606     * <p>A View should call this if it maintains some notion of which part
3607     * of its content is interesting.  For example, a text editing view
3608     * should call this when its cursor moves.
3609     *
3610     * @param rectangle The rectangle.
3611     * @return Whether any parent scrolled.
3612     */
3613    public boolean requestRectangleOnScreen(Rect rectangle) {
3614        return requestRectangleOnScreen(rectangle, false);
3615    }
3616
3617    /**
3618     * Request that a rectangle of this view be visible on the screen,
3619     * scrolling if necessary just enough.
3620     *
3621     * <p>A View should call this if it maintains some notion of which part
3622     * of its content is interesting.  For example, a text editing view
3623     * should call this when its cursor moves.
3624     *
3625     * <p>When <code>immediate</code> is set to true, scrolling will not be
3626     * animated.
3627     *
3628     * @param rectangle The rectangle.
3629     * @param immediate True to forbid animated scrolling, false otherwise
3630     * @return Whether any parent scrolled.
3631     */
3632    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3633        View child = this;
3634        ViewParent parent = mParent;
3635        boolean scrolled = false;
3636        while (parent != null) {
3637            scrolled |= parent.requestChildRectangleOnScreen(child,
3638                    rectangle, immediate);
3639
3640            // offset rect so next call has the rectangle in the
3641            // coordinate system of its direct child.
3642            rectangle.offset(child.getLeft(), child.getTop());
3643            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3644
3645            if (!(parent instanceof View)) {
3646                break;
3647            }
3648
3649            child = (View) parent;
3650            parent = child.getParent();
3651        }
3652        return scrolled;
3653    }
3654
3655    /**
3656     * Called when this view wants to give up focus. This will cause
3657     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3658     */
3659    public void clearFocus() {
3660        if (DBG) {
3661            System.out.println(this + " clearFocus()");
3662        }
3663
3664        if ((mPrivateFlags & FOCUSED) != 0) {
3665            mPrivateFlags &= ~FOCUSED;
3666
3667            if (mParent != null) {
3668                mParent.clearChildFocus(this);
3669            }
3670
3671            onFocusChanged(false, 0, null);
3672            refreshDrawableState();
3673        }
3674    }
3675
3676    /**
3677     * Called to clear the focus of a view that is about to be removed.
3678     * Doesn't call clearChildFocus, which prevents this view from taking
3679     * focus again before it has been removed from the parent
3680     */
3681    void clearFocusForRemoval() {
3682        if ((mPrivateFlags & FOCUSED) != 0) {
3683            mPrivateFlags &= ~FOCUSED;
3684
3685            onFocusChanged(false, 0, null);
3686            refreshDrawableState();
3687        }
3688    }
3689
3690    /**
3691     * Called internally by the view system when a new view is getting focus.
3692     * This is what clears the old focus.
3693     */
3694    void unFocus() {
3695        if (DBG) {
3696            System.out.println(this + " unFocus()");
3697        }
3698
3699        if ((mPrivateFlags & FOCUSED) != 0) {
3700            mPrivateFlags &= ~FOCUSED;
3701
3702            onFocusChanged(false, 0, null);
3703            refreshDrawableState();
3704        }
3705    }
3706
3707    /**
3708     * Returns true if this view has focus iteself, or is the ancestor of the
3709     * view that has focus.
3710     *
3711     * @return True if this view has or contains focus, false otherwise.
3712     */
3713    @ViewDebug.ExportedProperty(category = "focus")
3714    public boolean hasFocus() {
3715        return (mPrivateFlags & FOCUSED) != 0;
3716    }
3717
3718    /**
3719     * Returns true if this view is focusable or if it contains a reachable View
3720     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3721     * is a View whose parents do not block descendants focus.
3722     *
3723     * Only {@link #VISIBLE} views are considered focusable.
3724     *
3725     * @return True if the view is focusable or if the view contains a focusable
3726     *         View, false otherwise.
3727     *
3728     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3729     */
3730    public boolean hasFocusable() {
3731        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3732    }
3733
3734    /**
3735     * Called by the view system when the focus state of this view changes.
3736     * When the focus change event is caused by directional navigation, direction
3737     * and previouslyFocusedRect provide insight into where the focus is coming from.
3738     * When overriding, be sure to call up through to the super class so that
3739     * the standard focus handling will occur.
3740     *
3741     * @param gainFocus True if the View has focus; false otherwise.
3742     * @param direction The direction focus has moved when requestFocus()
3743     *                  is called to give this view focus. Values are
3744     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3745     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3746     *                  It may not always apply, in which case use the default.
3747     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3748     *        system, of the previously focused view.  If applicable, this will be
3749     *        passed in as finer grained information about where the focus is coming
3750     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3751     */
3752    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3753        if (gainFocus) {
3754            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3755        }
3756
3757        InputMethodManager imm = InputMethodManager.peekInstance();
3758        if (!gainFocus) {
3759            if (isPressed()) {
3760                setPressed(false);
3761            }
3762            if (imm != null && mAttachInfo != null
3763                    && mAttachInfo.mHasWindowFocus) {
3764                imm.focusOut(this);
3765            }
3766            onFocusLost();
3767        } else if (imm != null && mAttachInfo != null
3768                && mAttachInfo.mHasWindowFocus) {
3769            imm.focusIn(this);
3770        }
3771
3772        invalidate(true);
3773        if (mOnFocusChangeListener != null) {
3774            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3775        }
3776
3777        if (mAttachInfo != null) {
3778            mAttachInfo.mKeyDispatchState.reset(this);
3779        }
3780    }
3781
3782    /**
3783     * Sends an accessibility event of the given type. If accessiiblity is
3784     * not enabled this method has no effect. The default implementation calls
3785     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3786     * to populate information about the event source (this View), then calls
3787     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3788     * populate the text content of the event source including its descendants,
3789     * and last calls
3790     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3791     * on its parent to resuest sending of the event to interested parties.
3792     * <p>
3793     * If an {@link AccessibilityDelegate} has been specified via calling
3794     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3795     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3796     * responsible for handling this call.
3797     * </p>
3798     *
3799     * @param eventType The type of the event to send.
3800     *
3801     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3802     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3803     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3804     * @see AccessibilityDelegate
3805     */
3806    public void sendAccessibilityEvent(int eventType) {
3807        if (mAccessibilityDelegate != null) {
3808            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3809        } else {
3810            sendAccessibilityEventInternal(eventType);
3811        }
3812    }
3813
3814    /**
3815     * @see #sendAccessibilityEvent(int)
3816     *
3817     * Note: Called from the default {@link AccessibilityDelegate}.
3818     */
3819    void sendAccessibilityEventInternal(int eventType) {
3820        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3821            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3822        }
3823    }
3824
3825    /**
3826     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3827     * takes as an argument an empty {@link AccessibilityEvent} and does not
3828     * perform a check whether accessibility is enabled.
3829     * <p>
3830     * If an {@link AccessibilityDelegate} has been specified via calling
3831     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3832     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
3833     * is responsible for handling this call.
3834     * </p>
3835     *
3836     * @param event The event to send.
3837     *
3838     * @see #sendAccessibilityEvent(int)
3839     */
3840    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3841        if (mAccessibilityDelegate != null) {
3842           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
3843        } else {
3844            sendAccessibilityEventUncheckedInternal(event);
3845        }
3846    }
3847
3848    /**
3849     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
3850     *
3851     * Note: Called from the default {@link AccessibilityDelegate}.
3852     */
3853    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
3854        if (!isShown()) {
3855            return;
3856        }
3857        onInitializeAccessibilityEvent(event);
3858        dispatchPopulateAccessibilityEvent(event);
3859        // In the beginning we called #isShown(), so we know that getParent() is not null.
3860        getParent().requestSendAccessibilityEvent(this, event);
3861    }
3862
3863    /**
3864     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3865     * to its children for adding their text content to the event. Note that the
3866     * event text is populated in a separate dispatch path since we add to the
3867     * event not only the text of the source but also the text of all its descendants.
3868     * A typical implementation will call
3869     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3870     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3871     * on each child. Override this method if custom population of the event text
3872     * content is required.
3873     * <p>
3874     * If an {@link AccessibilityDelegate} has been specified via calling
3875     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3876     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
3877     * is responsible for handling this call.
3878     * </p>
3879     *
3880     * @param event The event.
3881     *
3882     * @return True if the event population was completed.
3883     */
3884    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3885        if (mAccessibilityDelegate != null) {
3886            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
3887        } else {
3888            return dispatchPopulateAccessibilityEventInternal(event);
3889        }
3890    }
3891
3892    /**
3893     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3894     *
3895     * Note: Called from the default {@link AccessibilityDelegate}.
3896     */
3897    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
3898        // Do not populate text to scroll events. They describe position change
3899        // and usually come from container with a lot of text which is not very
3900        // informative for accessibility purposes. Also they are fired frequently.
3901        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
3902            return true;
3903        }
3904        onPopulateAccessibilityEvent(event);
3905        return false;
3906    }
3907
3908    /**
3909     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3910     * giving a chance to this View to populate the accessibility event with its
3911     * text content. While the implementation is free to modify other event
3912     * attributes this should be performed in
3913     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
3914     * <p>
3915     * Example: Adding formatted date string to an accessibility event in addition
3916     *          to the text added by the super implementation.
3917     * </p><p><pre><code>
3918     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3919     *     super.onPopulateAccessibilityEvent(event);
3920     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
3921     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
3922     *         mCurrentDate.getTimeInMillis(), flags);
3923     *     event.getText().add(selectedDateUtterance);
3924     * }
3925     * </code></pre></p>
3926     * <p>
3927     * If an {@link AccessibilityDelegate} has been specified via calling
3928     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3929     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
3930     * is responsible for handling this call.
3931     * </p>
3932     *
3933     * @param event The accessibility event which to populate.
3934     *
3935     * @see #sendAccessibilityEvent(int)
3936     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3937     */
3938    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3939        if (mAccessibilityDelegate != null) {
3940            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
3941        } else {
3942            onPopulateAccessibilityEventInternal(event);
3943        }
3944    }
3945
3946    /**
3947     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
3948     *
3949     * Note: Called from the default {@link AccessibilityDelegate}.
3950     */
3951    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
3952
3953    }
3954
3955    /**
3956     * Initializes an {@link AccessibilityEvent} with information about
3957     * this View which is the event source. In other words, the source of
3958     * an accessibility event is the view whose state change triggered firing
3959     * the event.
3960     * <p>
3961     * Example: Setting the password property of an event in addition
3962     *          to properties set by the super implementation.
3963     * </p><p><pre><code>
3964     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3965     *    super.onInitializeAccessibilityEvent(event);
3966     *    event.setPassword(true);
3967     * }
3968     * </code></pre></p>
3969     * <p>
3970     * If an {@link AccessibilityDelegate} has been specified via calling
3971     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3972     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
3973     * is responsible for handling this call.
3974     * </p>
3975     *
3976     * @param event The event to initialize.
3977     *
3978     * @see #sendAccessibilityEvent(int)
3979     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3980     */
3981    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3982        if (mAccessibilityDelegate != null) {
3983            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
3984        } else {
3985            onInitializeAccessibilityEventInternal(event);
3986        }
3987    }
3988
3989    /**
3990     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3991     *
3992     * Note: Called from the default {@link AccessibilityDelegate}.
3993     */
3994    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
3995        event.setSource(this);
3996        event.setClassName(getClass().getName());
3997        event.setPackageName(getContext().getPackageName());
3998        event.setEnabled(isEnabled());
3999        event.setContentDescription(mContentDescription);
4000
4001        final int eventType = event.getEventType();
4002        switch (eventType) {
4003            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4004                if (mAttachInfo != null) {
4005                    ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4006                    getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4007                            FOCUSABLES_ALL);
4008                    event.setItemCount(focusablesTempList.size());
4009                    event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4010                    focusablesTempList.clear();
4011                }
4012            } break;
4013            case AccessibilityEvent.TYPE_VIEW_SCROLLED: {
4014                event.setScrollX(mScrollX);
4015                event.setScrollY(mScrollY);
4016                event.setItemCount(getHeight());
4017            } break;
4018        }
4019    }
4020
4021    /**
4022     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4023     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4024     * This method is responsible for obtaining an accessibility node info from a
4025     * pool of reusable instances and calling
4026     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4027     * initialize the former.
4028     * <p>
4029     * Note: The client is responsible for recycling the obtained instance by calling
4030     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4031     * </p>
4032     * @return A populated {@link AccessibilityNodeInfo}.
4033     *
4034     * @see AccessibilityNodeInfo
4035     */
4036    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4037        AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4038        onInitializeAccessibilityNodeInfo(info);
4039        return info;
4040    }
4041
4042    /**
4043     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4044     * The base implementation sets:
4045     * <ul>
4046     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4047     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4048     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4049     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4050     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4051     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4052     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4053     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4054     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4055     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4056     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4057     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4058     * </ul>
4059     * <p>
4060     * Subclasses should override this method, call the super implementation,
4061     * and set additional attributes.
4062     * </p>
4063     * <p>
4064     * If an {@link AccessibilityDelegate} has been specified via calling
4065     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4066     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4067     * is responsible for handling this call.
4068     * </p>
4069     *
4070     * @param info The instance to initialize.
4071     */
4072    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4073        if (mAccessibilityDelegate != null) {
4074            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4075        } else {
4076            onInitializeAccessibilityNodeInfoInternal(info);
4077        }
4078    }
4079
4080    /**
4081     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4082     *
4083     * Note: Called from the default {@link AccessibilityDelegate}.
4084     */
4085    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4086        Rect bounds = mAttachInfo.mTmpInvalRect;
4087        getDrawingRect(bounds);
4088        info.setBoundsInParent(bounds);
4089
4090        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4091        getLocationOnScreen(locationOnScreen);
4092        bounds.offsetTo(0, 0);
4093        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4094        info.setBoundsInScreen(bounds);
4095
4096        ViewParent parent = getParent();
4097        if (parent instanceof View) {
4098            View parentView = (View) parent;
4099            info.setParent(parentView);
4100        }
4101
4102        info.setPackageName(mContext.getPackageName());
4103        info.setClassName(getClass().getName());
4104        info.setContentDescription(getContentDescription());
4105
4106        info.setEnabled(isEnabled());
4107        info.setClickable(isClickable());
4108        info.setFocusable(isFocusable());
4109        info.setFocused(isFocused());
4110        info.setSelected(isSelected());
4111        info.setLongClickable(isLongClickable());
4112
4113        // TODO: These make sense only if we are in an AdapterView but all
4114        // views can be selected. Maybe from accessiiblity perspective
4115        // we should report as selectable view in an AdapterView.
4116        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4117        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4118
4119        if (isFocusable()) {
4120            if (isFocused()) {
4121                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4122            } else {
4123                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4124            }
4125        }
4126    }
4127
4128    /**
4129     * Sets a delegate for implementing accessibility support via compositon as
4130     * opposed to inheritance. The delegate's primary use is for implementing
4131     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4132     *
4133     * @param delegate The delegate instance.
4134     *
4135     * @see AccessibilityDelegate
4136     */
4137    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4138        mAccessibilityDelegate = delegate;
4139    }
4140
4141    /**
4142     * Gets the unique identifier of this view on the screen for accessibility purposes.
4143     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4144     *
4145     * @return The view accessibility id.
4146     *
4147     * @hide
4148     */
4149    public int getAccessibilityViewId() {
4150        if (mAccessibilityViewId == NO_ID) {
4151            mAccessibilityViewId = sNextAccessibilityViewId++;
4152        }
4153        return mAccessibilityViewId;
4154    }
4155
4156    /**
4157     * Gets the unique identifier of the window in which this View reseides.
4158     *
4159     * @return The window accessibility id.
4160     *
4161     * @hide
4162     */
4163    public int getAccessibilityWindowId() {
4164        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4165    }
4166
4167    /**
4168     * Gets the {@link View} description. It briefly describes the view and is
4169     * primarily used for accessibility support. Set this property to enable
4170     * better accessibility support for your application. This is especially
4171     * true for views that do not have textual representation (For example,
4172     * ImageButton).
4173     *
4174     * @return The content descriptiopn.
4175     *
4176     * @attr ref android.R.styleable#View_contentDescription
4177     */
4178    public CharSequence getContentDescription() {
4179        return mContentDescription;
4180    }
4181
4182    /**
4183     * Sets the {@link View} description. It briefly describes the view and is
4184     * primarily used for accessibility support. Set this property to enable
4185     * better accessibility support for your application. This is especially
4186     * true for views that do not have textual representation (For example,
4187     * ImageButton).
4188     *
4189     * @param contentDescription The content description.
4190     *
4191     * @attr ref android.R.styleable#View_contentDescription
4192     */
4193    public void setContentDescription(CharSequence contentDescription) {
4194        mContentDescription = contentDescription;
4195    }
4196
4197    /**
4198     * Invoked whenever this view loses focus, either by losing window focus or by losing
4199     * focus within its window. This method can be used to clear any state tied to the
4200     * focus. For instance, if a button is held pressed with the trackball and the window
4201     * loses focus, this method can be used to cancel the press.
4202     *
4203     * Subclasses of View overriding this method should always call super.onFocusLost().
4204     *
4205     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4206     * @see #onWindowFocusChanged(boolean)
4207     *
4208     * @hide pending API council approval
4209     */
4210    protected void onFocusLost() {
4211        resetPressedState();
4212    }
4213
4214    private void resetPressedState() {
4215        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4216            return;
4217        }
4218
4219        if (isPressed()) {
4220            setPressed(false);
4221
4222            if (!mHasPerformedLongPress) {
4223                removeLongPressCallback();
4224            }
4225        }
4226    }
4227
4228    /**
4229     * Returns true if this view has focus
4230     *
4231     * @return True if this view has focus, false otherwise.
4232     */
4233    @ViewDebug.ExportedProperty(category = "focus")
4234    public boolean isFocused() {
4235        return (mPrivateFlags & FOCUSED) != 0;
4236    }
4237
4238    /**
4239     * Find the view in the hierarchy rooted at this view that currently has
4240     * focus.
4241     *
4242     * @return The view that currently has focus, or null if no focused view can
4243     *         be found.
4244     */
4245    public View findFocus() {
4246        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4247    }
4248
4249    /**
4250     * Change whether this view is one of the set of scrollable containers in
4251     * its window.  This will be used to determine whether the window can
4252     * resize or must pan when a soft input area is open -- scrollable
4253     * containers allow the window to use resize mode since the container
4254     * will appropriately shrink.
4255     */
4256    public void setScrollContainer(boolean isScrollContainer) {
4257        if (isScrollContainer) {
4258            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4259                mAttachInfo.mScrollContainers.add(this);
4260                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4261            }
4262            mPrivateFlags |= SCROLL_CONTAINER;
4263        } else {
4264            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4265                mAttachInfo.mScrollContainers.remove(this);
4266            }
4267            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4268        }
4269    }
4270
4271    /**
4272     * Returns the quality of the drawing cache.
4273     *
4274     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4275     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4276     *
4277     * @see #setDrawingCacheQuality(int)
4278     * @see #setDrawingCacheEnabled(boolean)
4279     * @see #isDrawingCacheEnabled()
4280     *
4281     * @attr ref android.R.styleable#View_drawingCacheQuality
4282     */
4283    public int getDrawingCacheQuality() {
4284        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4285    }
4286
4287    /**
4288     * Set the drawing cache quality of this view. This value is used only when the
4289     * drawing cache is enabled
4290     *
4291     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4292     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4293     *
4294     * @see #getDrawingCacheQuality()
4295     * @see #setDrawingCacheEnabled(boolean)
4296     * @see #isDrawingCacheEnabled()
4297     *
4298     * @attr ref android.R.styleable#View_drawingCacheQuality
4299     */
4300    public void setDrawingCacheQuality(int quality) {
4301        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4302    }
4303
4304    /**
4305     * Returns whether the screen should remain on, corresponding to the current
4306     * value of {@link #KEEP_SCREEN_ON}.
4307     *
4308     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4309     *
4310     * @see #setKeepScreenOn(boolean)
4311     *
4312     * @attr ref android.R.styleable#View_keepScreenOn
4313     */
4314    public boolean getKeepScreenOn() {
4315        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4316    }
4317
4318    /**
4319     * Controls whether the screen should remain on, modifying the
4320     * value of {@link #KEEP_SCREEN_ON}.
4321     *
4322     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4323     *
4324     * @see #getKeepScreenOn()
4325     *
4326     * @attr ref android.R.styleable#View_keepScreenOn
4327     */
4328    public void setKeepScreenOn(boolean keepScreenOn) {
4329        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4330    }
4331
4332    /**
4333     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4334     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4335     *
4336     * @attr ref android.R.styleable#View_nextFocusLeft
4337     */
4338    public int getNextFocusLeftId() {
4339        return mNextFocusLeftId;
4340    }
4341
4342    /**
4343     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4344     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4345     * decide automatically.
4346     *
4347     * @attr ref android.R.styleable#View_nextFocusLeft
4348     */
4349    public void setNextFocusLeftId(int nextFocusLeftId) {
4350        mNextFocusLeftId = nextFocusLeftId;
4351    }
4352
4353    /**
4354     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4355     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4356     *
4357     * @attr ref android.R.styleable#View_nextFocusRight
4358     */
4359    public int getNextFocusRightId() {
4360        return mNextFocusRightId;
4361    }
4362
4363    /**
4364     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4365     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4366     * decide automatically.
4367     *
4368     * @attr ref android.R.styleable#View_nextFocusRight
4369     */
4370    public void setNextFocusRightId(int nextFocusRightId) {
4371        mNextFocusRightId = nextFocusRightId;
4372    }
4373
4374    /**
4375     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4376     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4377     *
4378     * @attr ref android.R.styleable#View_nextFocusUp
4379     */
4380    public int getNextFocusUpId() {
4381        return mNextFocusUpId;
4382    }
4383
4384    /**
4385     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4386     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4387     * decide automatically.
4388     *
4389     * @attr ref android.R.styleable#View_nextFocusUp
4390     */
4391    public void setNextFocusUpId(int nextFocusUpId) {
4392        mNextFocusUpId = nextFocusUpId;
4393    }
4394
4395    /**
4396     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4397     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4398     *
4399     * @attr ref android.R.styleable#View_nextFocusDown
4400     */
4401    public int getNextFocusDownId() {
4402        return mNextFocusDownId;
4403    }
4404
4405    /**
4406     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4407     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4408     * decide automatically.
4409     *
4410     * @attr ref android.R.styleable#View_nextFocusDown
4411     */
4412    public void setNextFocusDownId(int nextFocusDownId) {
4413        mNextFocusDownId = nextFocusDownId;
4414    }
4415
4416    /**
4417     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4418     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4419     *
4420     * @attr ref android.R.styleable#View_nextFocusForward
4421     */
4422    public int getNextFocusForwardId() {
4423        return mNextFocusForwardId;
4424    }
4425
4426    /**
4427     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4428     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4429     * decide automatically.
4430     *
4431     * @attr ref android.R.styleable#View_nextFocusForward
4432     */
4433    public void setNextFocusForwardId(int nextFocusForwardId) {
4434        mNextFocusForwardId = nextFocusForwardId;
4435    }
4436
4437    /**
4438     * Returns the visibility of this view and all of its ancestors
4439     *
4440     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4441     */
4442    public boolean isShown() {
4443        View current = this;
4444        //noinspection ConstantConditions
4445        do {
4446            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4447                return false;
4448            }
4449            ViewParent parent = current.mParent;
4450            if (parent == null) {
4451                return false; // We are not attached to the view root
4452            }
4453            if (!(parent instanceof View)) {
4454                return true;
4455            }
4456            current = (View) parent;
4457        } while (current != null);
4458
4459        return false;
4460    }
4461
4462    /**
4463     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4464     * is set
4465     *
4466     * @param insets Insets for system windows
4467     *
4468     * @return True if this view applied the insets, false otherwise
4469     */
4470    protected boolean fitSystemWindows(Rect insets) {
4471        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4472            mPaddingLeft = insets.left;
4473            mPaddingTop = insets.top;
4474            mPaddingRight = insets.right;
4475            mPaddingBottom = insets.bottom;
4476            requestLayout();
4477            return true;
4478        }
4479        return false;
4480    }
4481
4482    /**
4483     * Set whether or not this view should account for system screen decorations
4484     * such as the status bar and inset its content. This allows this view to be
4485     * positioned in absolute screen coordinates and remain visible to the user.
4486     *
4487     * <p>This should only be used by top-level window decor views.
4488     *
4489     * @param fitSystemWindows true to inset content for system screen decorations, false for
4490     *                         default behavior.
4491     *
4492     * @attr ref android.R.styleable#View_fitsSystemWindows
4493     */
4494    public void setFitsSystemWindows(boolean fitSystemWindows) {
4495        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4496    }
4497
4498    /**
4499     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4500     * will account for system screen decorations such as the status bar and inset its
4501     * content. This allows the view to be positioned in absolute screen coordinates
4502     * and remain visible to the user.
4503     *
4504     * @return true if this view will adjust its content bounds for system screen decorations.
4505     *
4506     * @attr ref android.R.styleable#View_fitsSystemWindows
4507     */
4508    public boolean fitsSystemWindows() {
4509        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4510    }
4511
4512    /**
4513     * Returns the visibility status for this view.
4514     *
4515     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4516     * @attr ref android.R.styleable#View_visibility
4517     */
4518    @ViewDebug.ExportedProperty(mapping = {
4519        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4520        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4521        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4522    })
4523    public int getVisibility() {
4524        return mViewFlags & VISIBILITY_MASK;
4525    }
4526
4527    /**
4528     * Set the enabled state of this view.
4529     *
4530     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4531     * @attr ref android.R.styleable#View_visibility
4532     */
4533    @RemotableViewMethod
4534    public void setVisibility(int visibility) {
4535        setFlags(visibility, VISIBILITY_MASK);
4536        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4537    }
4538
4539    /**
4540     * Returns the enabled status for this view. The interpretation of the
4541     * enabled state varies by subclass.
4542     *
4543     * @return True if this view is enabled, false otherwise.
4544     */
4545    @ViewDebug.ExportedProperty
4546    public boolean isEnabled() {
4547        return (mViewFlags & ENABLED_MASK) == ENABLED;
4548    }
4549
4550    /**
4551     * Set the enabled state of this view. The interpretation of the enabled
4552     * state varies by subclass.
4553     *
4554     * @param enabled True if this view is enabled, false otherwise.
4555     */
4556    @RemotableViewMethod
4557    public void setEnabled(boolean enabled) {
4558        if (enabled == isEnabled()) return;
4559
4560        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4561
4562        /*
4563         * The View most likely has to change its appearance, so refresh
4564         * the drawable state.
4565         */
4566        refreshDrawableState();
4567
4568        // Invalidate too, since the default behavior for views is to be
4569        // be drawn at 50% alpha rather than to change the drawable.
4570        invalidate(true);
4571    }
4572
4573    /**
4574     * Set whether this view can receive the focus.
4575     *
4576     * Setting this to false will also ensure that this view is not focusable
4577     * in touch mode.
4578     *
4579     * @param focusable If true, this view can receive the focus.
4580     *
4581     * @see #setFocusableInTouchMode(boolean)
4582     * @attr ref android.R.styleable#View_focusable
4583     */
4584    public void setFocusable(boolean focusable) {
4585        if (!focusable) {
4586            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4587        }
4588        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4589    }
4590
4591    /**
4592     * Set whether this view can receive focus while in touch mode.
4593     *
4594     * Setting this to true will also ensure that this view is focusable.
4595     *
4596     * @param focusableInTouchMode If true, this view can receive the focus while
4597     *   in touch mode.
4598     *
4599     * @see #setFocusable(boolean)
4600     * @attr ref android.R.styleable#View_focusableInTouchMode
4601     */
4602    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4603        // Focusable in touch mode should always be set before the focusable flag
4604        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4605        // which, in touch mode, will not successfully request focus on this view
4606        // because the focusable in touch mode flag is not set
4607        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4608        if (focusableInTouchMode) {
4609            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4610        }
4611    }
4612
4613    /**
4614     * Set whether this view should have sound effects enabled for events such as
4615     * clicking and touching.
4616     *
4617     * <p>You may wish to disable sound effects for a view if you already play sounds,
4618     * for instance, a dial key that plays dtmf tones.
4619     *
4620     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4621     * @see #isSoundEffectsEnabled()
4622     * @see #playSoundEffect(int)
4623     * @attr ref android.R.styleable#View_soundEffectsEnabled
4624     */
4625    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4626        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4627    }
4628
4629    /**
4630     * @return whether this view should have sound effects enabled for events such as
4631     *     clicking and touching.
4632     *
4633     * @see #setSoundEffectsEnabled(boolean)
4634     * @see #playSoundEffect(int)
4635     * @attr ref android.R.styleable#View_soundEffectsEnabled
4636     */
4637    @ViewDebug.ExportedProperty
4638    public boolean isSoundEffectsEnabled() {
4639        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4640    }
4641
4642    /**
4643     * Set whether this view should have haptic feedback for events such as
4644     * long presses.
4645     *
4646     * <p>You may wish to disable haptic feedback if your view already controls
4647     * its own haptic feedback.
4648     *
4649     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4650     * @see #isHapticFeedbackEnabled()
4651     * @see #performHapticFeedback(int)
4652     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4653     */
4654    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4655        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4656    }
4657
4658    /**
4659     * @return whether this view should have haptic feedback enabled for events
4660     * long presses.
4661     *
4662     * @see #setHapticFeedbackEnabled(boolean)
4663     * @see #performHapticFeedback(int)
4664     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4665     */
4666    @ViewDebug.ExportedProperty
4667    public boolean isHapticFeedbackEnabled() {
4668        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4669    }
4670
4671    /**
4672     * Returns the layout direction for this view.
4673     *
4674     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4675     *   {@link #LAYOUT_DIRECTION_RTL},
4676     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4677     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4678     * @attr ref android.R.styleable#View_layoutDirection
4679     *
4680     * @hide
4681     */
4682    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4683        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4684        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4685        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4686        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4687    })
4688    public int getLayoutDirection() {
4689        return mViewFlags & LAYOUT_DIRECTION_MASK;
4690    }
4691
4692    /**
4693     * Set the layout direction for this view. This will propagate a reset of layout direction
4694     * resolution to the view's children and resolve layout direction for this view.
4695     *
4696     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4697     *   {@link #LAYOUT_DIRECTION_RTL},
4698     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4699     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4700     *
4701     * @attr ref android.R.styleable#View_layoutDirection
4702     *
4703     * @hide
4704     */
4705    @RemotableViewMethod
4706    public void setLayoutDirection(int layoutDirection) {
4707        if (getLayoutDirection() != layoutDirection) {
4708            resetResolvedLayoutDirection();
4709            // Setting the flag will also request a layout.
4710            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4711        }
4712    }
4713
4714    /**
4715     * Returns the resolved layout direction for this view.
4716     *
4717     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4718     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4719     *
4720     * @hide
4721     */
4722    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4723        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4724        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4725    })
4726    public int getResolvedLayoutDirection() {
4727        resolveLayoutDirectionIfNeeded();
4728        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4729                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4730    }
4731
4732    /**
4733     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4734     * layout attribute and/or the inherited value from the parent.</p>
4735     *
4736     * @return true if the layout is right-to-left.
4737     *
4738     * @hide
4739     */
4740    @ViewDebug.ExportedProperty(category = "layout")
4741    public boolean isLayoutRtl() {
4742        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4743    }
4744
4745    /**
4746     * If this view doesn't do any drawing on its own, set this flag to
4747     * allow further optimizations. By default, this flag is not set on
4748     * View, but could be set on some View subclasses such as ViewGroup.
4749     *
4750     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4751     * you should clear this flag.
4752     *
4753     * @param willNotDraw whether or not this View draw on its own
4754     */
4755    public void setWillNotDraw(boolean willNotDraw) {
4756        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4757    }
4758
4759    /**
4760     * Returns whether or not this View draws on its own.
4761     *
4762     * @return true if this view has nothing to draw, false otherwise
4763     */
4764    @ViewDebug.ExportedProperty(category = "drawing")
4765    public boolean willNotDraw() {
4766        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4767    }
4768
4769    /**
4770     * When a View's drawing cache is enabled, drawing is redirected to an
4771     * offscreen bitmap. Some views, like an ImageView, must be able to
4772     * bypass this mechanism if they already draw a single bitmap, to avoid
4773     * unnecessary usage of the memory.
4774     *
4775     * @param willNotCacheDrawing true if this view does not cache its
4776     *        drawing, false otherwise
4777     */
4778    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4779        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4780    }
4781
4782    /**
4783     * Returns whether or not this View can cache its drawing or not.
4784     *
4785     * @return true if this view does not cache its drawing, false otherwise
4786     */
4787    @ViewDebug.ExportedProperty(category = "drawing")
4788    public boolean willNotCacheDrawing() {
4789        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4790    }
4791
4792    /**
4793     * Indicates whether this view reacts to click events or not.
4794     *
4795     * @return true if the view is clickable, false otherwise
4796     *
4797     * @see #setClickable(boolean)
4798     * @attr ref android.R.styleable#View_clickable
4799     */
4800    @ViewDebug.ExportedProperty
4801    public boolean isClickable() {
4802        return (mViewFlags & CLICKABLE) == CLICKABLE;
4803    }
4804
4805    /**
4806     * Enables or disables click events for this view. When a view
4807     * is clickable it will change its state to "pressed" on every click.
4808     * Subclasses should set the view clickable to visually react to
4809     * user's clicks.
4810     *
4811     * @param clickable true to make the view clickable, false otherwise
4812     *
4813     * @see #isClickable()
4814     * @attr ref android.R.styleable#View_clickable
4815     */
4816    public void setClickable(boolean clickable) {
4817        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4818    }
4819
4820    /**
4821     * Indicates whether this view reacts to long click events or not.
4822     *
4823     * @return true if the view is long clickable, false otherwise
4824     *
4825     * @see #setLongClickable(boolean)
4826     * @attr ref android.R.styleable#View_longClickable
4827     */
4828    public boolean isLongClickable() {
4829        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4830    }
4831
4832    /**
4833     * Enables or disables long click events for this view. When a view is long
4834     * clickable it reacts to the user holding down the button for a longer
4835     * duration than a tap. This event can either launch the listener or a
4836     * context menu.
4837     *
4838     * @param longClickable true to make the view long clickable, false otherwise
4839     * @see #isLongClickable()
4840     * @attr ref android.R.styleable#View_longClickable
4841     */
4842    public void setLongClickable(boolean longClickable) {
4843        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4844    }
4845
4846    /**
4847     * Sets the pressed state for this view.
4848     *
4849     * @see #isClickable()
4850     * @see #setClickable(boolean)
4851     *
4852     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4853     *        the View's internal state from a previously set "pressed" state.
4854     */
4855    public void setPressed(boolean pressed) {
4856        if (pressed) {
4857            mPrivateFlags |= PRESSED;
4858        } else {
4859            mPrivateFlags &= ~PRESSED;
4860        }
4861        refreshDrawableState();
4862        dispatchSetPressed(pressed);
4863    }
4864
4865    /**
4866     * Dispatch setPressed to all of this View's children.
4867     *
4868     * @see #setPressed(boolean)
4869     *
4870     * @param pressed The new pressed state
4871     */
4872    protected void dispatchSetPressed(boolean pressed) {
4873    }
4874
4875    /**
4876     * Indicates whether the view is currently in pressed state. Unless
4877     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4878     * the pressed state.
4879     *
4880     * @see #setPressed(boolean)
4881     * @see #isClickable()
4882     * @see #setClickable(boolean)
4883     *
4884     * @return true if the view is currently pressed, false otherwise
4885     */
4886    public boolean isPressed() {
4887        return (mPrivateFlags & PRESSED) == PRESSED;
4888    }
4889
4890    /**
4891     * Indicates whether this view will save its state (that is,
4892     * whether its {@link #onSaveInstanceState} method will be called).
4893     *
4894     * @return Returns true if the view state saving is enabled, else false.
4895     *
4896     * @see #setSaveEnabled(boolean)
4897     * @attr ref android.R.styleable#View_saveEnabled
4898     */
4899    public boolean isSaveEnabled() {
4900        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4901    }
4902
4903    /**
4904     * Controls whether the saving of this view's state is
4905     * enabled (that is, whether its {@link #onSaveInstanceState} method
4906     * will be called).  Note that even if freezing is enabled, the
4907     * view still must have an id assigned to it (via {@link #setId(int)})
4908     * for its state to be saved.  This flag can only disable the
4909     * saving of this view; any child views may still have their state saved.
4910     *
4911     * @param enabled Set to false to <em>disable</em> state saving, or true
4912     * (the default) to allow it.
4913     *
4914     * @see #isSaveEnabled()
4915     * @see #setId(int)
4916     * @see #onSaveInstanceState()
4917     * @attr ref android.R.styleable#View_saveEnabled
4918     */
4919    public void setSaveEnabled(boolean enabled) {
4920        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4921    }
4922
4923    /**
4924     * Gets whether the framework should discard touches when the view's
4925     * window is obscured by another visible window.
4926     * Refer to the {@link View} security documentation for more details.
4927     *
4928     * @return True if touch filtering is enabled.
4929     *
4930     * @see #setFilterTouchesWhenObscured(boolean)
4931     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4932     */
4933    @ViewDebug.ExportedProperty
4934    public boolean getFilterTouchesWhenObscured() {
4935        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4936    }
4937
4938    /**
4939     * Sets whether the framework should discard touches when the view's
4940     * window is obscured by another visible window.
4941     * Refer to the {@link View} security documentation for more details.
4942     *
4943     * @param enabled True if touch filtering should be enabled.
4944     *
4945     * @see #getFilterTouchesWhenObscured
4946     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4947     */
4948    public void setFilterTouchesWhenObscured(boolean enabled) {
4949        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4950                FILTER_TOUCHES_WHEN_OBSCURED);
4951    }
4952
4953    /**
4954     * Indicates whether the entire hierarchy under this view will save its
4955     * state when a state saving traversal occurs from its parent.  The default
4956     * is true; if false, these views will not be saved unless
4957     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4958     *
4959     * @return Returns true if the view state saving from parent is enabled, else false.
4960     *
4961     * @see #setSaveFromParentEnabled(boolean)
4962     */
4963    public boolean isSaveFromParentEnabled() {
4964        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4965    }
4966
4967    /**
4968     * Controls whether the entire hierarchy under this view will save its
4969     * state when a state saving traversal occurs from its parent.  The default
4970     * is true; if false, these views will not be saved unless
4971     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4972     *
4973     * @param enabled Set to false to <em>disable</em> state saving, or true
4974     * (the default) to allow it.
4975     *
4976     * @see #isSaveFromParentEnabled()
4977     * @see #setId(int)
4978     * @see #onSaveInstanceState()
4979     */
4980    public void setSaveFromParentEnabled(boolean enabled) {
4981        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4982    }
4983
4984
4985    /**
4986     * Returns whether this View is able to take focus.
4987     *
4988     * @return True if this view can take focus, or false otherwise.
4989     * @attr ref android.R.styleable#View_focusable
4990     */
4991    @ViewDebug.ExportedProperty(category = "focus")
4992    public final boolean isFocusable() {
4993        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4994    }
4995
4996    /**
4997     * When a view is focusable, it may not want to take focus when in touch mode.
4998     * For example, a button would like focus when the user is navigating via a D-pad
4999     * so that the user can click on it, but once the user starts touching the screen,
5000     * the button shouldn't take focus
5001     * @return Whether the view is focusable in touch mode.
5002     * @attr ref android.R.styleable#View_focusableInTouchMode
5003     */
5004    @ViewDebug.ExportedProperty
5005    public final boolean isFocusableInTouchMode() {
5006        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5007    }
5008
5009    /**
5010     * Find the nearest view in the specified direction that can take focus.
5011     * This does not actually give focus to that view.
5012     *
5013     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5014     *
5015     * @return The nearest focusable in the specified direction, or null if none
5016     *         can be found.
5017     */
5018    public View focusSearch(int direction) {
5019        if (mParent != null) {
5020            return mParent.focusSearch(this, direction);
5021        } else {
5022            return null;
5023        }
5024    }
5025
5026    /**
5027     * This method is the last chance for the focused view and its ancestors to
5028     * respond to an arrow key. This is called when the focused view did not
5029     * consume the key internally, nor could the view system find a new view in
5030     * the requested direction to give focus to.
5031     *
5032     * @param focused The currently focused view.
5033     * @param direction The direction focus wants to move. One of FOCUS_UP,
5034     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5035     * @return True if the this view consumed this unhandled move.
5036     */
5037    public boolean dispatchUnhandledMove(View focused, int direction) {
5038        return false;
5039    }
5040
5041    /**
5042     * If a user manually specified the next view id for a particular direction,
5043     * use the root to look up the view.
5044     * @param root The root view of the hierarchy containing this view.
5045     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5046     * or FOCUS_BACKWARD.
5047     * @return The user specified next view, or null if there is none.
5048     */
5049    View findUserSetNextFocus(View root, int direction) {
5050        switch (direction) {
5051            case FOCUS_LEFT:
5052                if (mNextFocusLeftId == View.NO_ID) return null;
5053                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5054            case FOCUS_RIGHT:
5055                if (mNextFocusRightId == View.NO_ID) return null;
5056                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5057            case FOCUS_UP:
5058                if (mNextFocusUpId == View.NO_ID) return null;
5059                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5060            case FOCUS_DOWN:
5061                if (mNextFocusDownId == View.NO_ID) return null;
5062                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5063            case FOCUS_FORWARD:
5064                if (mNextFocusForwardId == View.NO_ID) return null;
5065                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5066            case FOCUS_BACKWARD: {
5067                final int id = mID;
5068                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5069                    @Override
5070                    public boolean apply(View t) {
5071                        return t.mNextFocusForwardId == id;
5072                    }
5073                });
5074            }
5075        }
5076        return null;
5077    }
5078
5079    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5080        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5081            @Override
5082            public boolean apply(View t) {
5083                return t.mID == childViewId;
5084            }
5085        });
5086
5087        if (result == null) {
5088            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5089                    + "by user for id " + childViewId);
5090        }
5091        return result;
5092    }
5093
5094    /**
5095     * Find and return all focusable views that are descendants of this view,
5096     * possibly including this view if it is focusable itself.
5097     *
5098     * @param direction The direction of the focus
5099     * @return A list of focusable views
5100     */
5101    public ArrayList<View> getFocusables(int direction) {
5102        ArrayList<View> result = new ArrayList<View>(24);
5103        addFocusables(result, direction);
5104        return result;
5105    }
5106
5107    /**
5108     * Add any focusable views that are descendants of this view (possibly
5109     * including this view if it is focusable itself) to views.  If we are in touch mode,
5110     * only add views that are also focusable in touch mode.
5111     *
5112     * @param views Focusable views found so far
5113     * @param direction The direction of the focus
5114     */
5115    public void addFocusables(ArrayList<View> views, int direction) {
5116        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5117    }
5118
5119    /**
5120     * Adds any focusable views that are descendants of this view (possibly
5121     * including this view if it is focusable itself) to views. This method
5122     * adds all focusable views regardless if we are in touch mode or
5123     * only views focusable in touch mode if we are in touch mode depending on
5124     * the focusable mode paramater.
5125     *
5126     * @param views Focusable views found so far or null if all we are interested is
5127     *        the number of focusables.
5128     * @param direction The direction of the focus.
5129     * @param focusableMode The type of focusables to be added.
5130     *
5131     * @see #FOCUSABLES_ALL
5132     * @see #FOCUSABLES_TOUCH_MODE
5133     */
5134    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5135        if (!isFocusable()) {
5136            return;
5137        }
5138
5139        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5140                isInTouchMode() && !isFocusableInTouchMode()) {
5141            return;
5142        }
5143
5144        if (views != null) {
5145            views.add(this);
5146        }
5147    }
5148
5149    /**
5150     * Finds the Views that contain given text. The containment is case insensitive.
5151     * The search is performed by either the text that the View renders or the content
5152     * description that describes the view for accessibility purposes and the view does
5153     * not render or both. Clients can specify how the search is to be performed via
5154     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5155     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5156     *
5157     * @param outViews The output list of matching Views.
5158     * @param searched The text to match against.
5159     *
5160     * @see #FIND_VIEWS_WITH_TEXT
5161     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5162     * @see #setContentDescription(CharSequence)
5163     */
5164    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5165        if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 && !TextUtils.isEmpty(searched)
5166                && !TextUtils.isEmpty(mContentDescription)) {
5167            String searchedLowerCase = searched.toString().toLowerCase();
5168            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5169            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5170                outViews.add(this);
5171            }
5172        }
5173    }
5174
5175    /**
5176     * Find and return all touchable views that are descendants of this view,
5177     * possibly including this view if it is touchable itself.
5178     *
5179     * @return A list of touchable views
5180     */
5181    public ArrayList<View> getTouchables() {
5182        ArrayList<View> result = new ArrayList<View>();
5183        addTouchables(result);
5184        return result;
5185    }
5186
5187    /**
5188     * Add any touchable views that are descendants of this view (possibly
5189     * including this view if it is touchable itself) to views.
5190     *
5191     * @param views Touchable views found so far
5192     */
5193    public void addTouchables(ArrayList<View> views) {
5194        final int viewFlags = mViewFlags;
5195
5196        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5197                && (viewFlags & ENABLED_MASK) == ENABLED) {
5198            views.add(this);
5199        }
5200    }
5201
5202    /**
5203     * Call this to try to give focus to a specific view or to one of its
5204     * descendants.
5205     *
5206     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5207     * false), or if it is focusable and it is not focusable in touch mode
5208     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5209     *
5210     * See also {@link #focusSearch(int)}, which is what you call to say that you
5211     * have focus, and you want your parent to look for the next one.
5212     *
5213     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5214     * {@link #FOCUS_DOWN} and <code>null</code>.
5215     *
5216     * @return Whether this view or one of its descendants actually took focus.
5217     */
5218    public final boolean requestFocus() {
5219        return requestFocus(View.FOCUS_DOWN);
5220    }
5221
5222
5223    /**
5224     * Call this to try to give focus to a specific view or to one of its
5225     * descendants and give it a hint about what direction focus is heading.
5226     *
5227     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5228     * false), or if it is focusable and it is not focusable in touch mode
5229     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5230     *
5231     * See also {@link #focusSearch(int)}, which is what you call to say that you
5232     * have focus, and you want your parent to look for the next one.
5233     *
5234     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5235     * <code>null</code> set for the previously focused rectangle.
5236     *
5237     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5238     * @return Whether this view or one of its descendants actually took focus.
5239     */
5240    public final boolean requestFocus(int direction) {
5241        return requestFocus(direction, null);
5242    }
5243
5244    /**
5245     * Call this to try to give focus to a specific view or to one of its descendants
5246     * and give it hints about the direction and a specific rectangle that the focus
5247     * is coming from.  The rectangle can help give larger views a finer grained hint
5248     * about where focus is coming from, and therefore, where to show selection, or
5249     * forward focus change internally.
5250     *
5251     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5252     * false), or if it is focusable and it is not focusable in touch mode
5253     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5254     *
5255     * A View will not take focus if it is not visible.
5256     *
5257     * A View will not take focus if one of its parents has
5258     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5259     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5260     *
5261     * See also {@link #focusSearch(int)}, which is what you call to say that you
5262     * have focus, and you want your parent to look for the next one.
5263     *
5264     * You may wish to override this method if your custom {@link View} has an internal
5265     * {@link View} that it wishes to forward the request to.
5266     *
5267     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5268     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5269     *        to give a finer grained hint about where focus is coming from.  May be null
5270     *        if there is no hint.
5271     * @return Whether this view or one of its descendants actually took focus.
5272     */
5273    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5274        // need to be focusable
5275        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5276                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5277            return false;
5278        }
5279
5280        // need to be focusable in touch mode if in touch mode
5281        if (isInTouchMode() &&
5282            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5283               return false;
5284        }
5285
5286        // need to not have any parents blocking us
5287        if (hasAncestorThatBlocksDescendantFocus()) {
5288            return false;
5289        }
5290
5291        handleFocusGainInternal(direction, previouslyFocusedRect);
5292        return true;
5293    }
5294
5295    /** Gets the ViewAncestor, or null if not attached. */
5296    /*package*/ ViewRootImpl getViewRootImpl() {
5297        View root = getRootView();
5298        return root != null ? (ViewRootImpl)root.getParent() : null;
5299    }
5300
5301    /**
5302     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5303     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5304     * touch mode to request focus when they are touched.
5305     *
5306     * @return Whether this view or one of its descendants actually took focus.
5307     *
5308     * @see #isInTouchMode()
5309     *
5310     */
5311    public final boolean requestFocusFromTouch() {
5312        // Leave touch mode if we need to
5313        if (isInTouchMode()) {
5314            ViewRootImpl viewRoot = getViewRootImpl();
5315            if (viewRoot != null) {
5316                viewRoot.ensureTouchMode(false);
5317            }
5318        }
5319        return requestFocus(View.FOCUS_DOWN);
5320    }
5321
5322    /**
5323     * @return Whether any ancestor of this view blocks descendant focus.
5324     */
5325    private boolean hasAncestorThatBlocksDescendantFocus() {
5326        ViewParent ancestor = mParent;
5327        while (ancestor instanceof ViewGroup) {
5328            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5329            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5330                return true;
5331            } else {
5332                ancestor = vgAncestor.getParent();
5333            }
5334        }
5335        return false;
5336    }
5337
5338    /**
5339     * @hide
5340     */
5341    public void dispatchStartTemporaryDetach() {
5342        onStartTemporaryDetach();
5343    }
5344
5345    /**
5346     * This is called when a container is going to temporarily detach a child, with
5347     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5348     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5349     * {@link #onDetachedFromWindow()} when the container is done.
5350     */
5351    public void onStartTemporaryDetach() {
5352        removeUnsetPressCallback();
5353        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5354    }
5355
5356    /**
5357     * @hide
5358     */
5359    public void dispatchFinishTemporaryDetach() {
5360        onFinishTemporaryDetach();
5361    }
5362
5363    /**
5364     * Called after {@link #onStartTemporaryDetach} when the container is done
5365     * changing the view.
5366     */
5367    public void onFinishTemporaryDetach() {
5368    }
5369
5370    /**
5371     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5372     * for this view's window.  Returns null if the view is not currently attached
5373     * to the window.  Normally you will not need to use this directly, but
5374     * just use the standard high-level event callbacks like
5375     * {@link #onKeyDown(int, KeyEvent)}.
5376     */
5377    public KeyEvent.DispatcherState getKeyDispatcherState() {
5378        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5379    }
5380
5381    /**
5382     * Dispatch a key event before it is processed by any input method
5383     * associated with the view hierarchy.  This can be used to intercept
5384     * key events in special situations before the IME consumes them; a
5385     * typical example would be handling the BACK key to update the application's
5386     * UI instead of allowing the IME to see it and close itself.
5387     *
5388     * @param event The key event to be dispatched.
5389     * @return True if the event was handled, false otherwise.
5390     */
5391    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5392        return onKeyPreIme(event.getKeyCode(), event);
5393    }
5394
5395    /**
5396     * Dispatch a key event to the next view on the focus path. This path runs
5397     * from the top of the view tree down to the currently focused view. If this
5398     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5399     * the next node down the focus path. This method also fires any key
5400     * listeners.
5401     *
5402     * @param event The key event to be dispatched.
5403     * @return True if the event was handled, false otherwise.
5404     */
5405    public boolean dispatchKeyEvent(KeyEvent event) {
5406        if (mInputEventConsistencyVerifier != null) {
5407            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5408        }
5409
5410        // Give any attached key listener a first crack at the event.
5411        //noinspection SimplifiableIfStatement
5412        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5413                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5414            return true;
5415        }
5416
5417        if (event.dispatch(this, mAttachInfo != null
5418                ? mAttachInfo.mKeyDispatchState : null, this)) {
5419            return true;
5420        }
5421
5422        if (mInputEventConsistencyVerifier != null) {
5423            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5424        }
5425        return false;
5426    }
5427
5428    /**
5429     * Dispatches a key shortcut event.
5430     *
5431     * @param event The key event to be dispatched.
5432     * @return True if the event was handled by the view, false otherwise.
5433     */
5434    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5435        return onKeyShortcut(event.getKeyCode(), event);
5436    }
5437
5438    /**
5439     * Pass the touch screen motion event down to the target view, or this
5440     * view if it is the target.
5441     *
5442     * @param event The motion event to be dispatched.
5443     * @return True if the event was handled by the view, false otherwise.
5444     */
5445    public boolean dispatchTouchEvent(MotionEvent event) {
5446        if (mInputEventConsistencyVerifier != null) {
5447            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5448        }
5449
5450        if (onFilterTouchEventForSecurity(event)) {
5451            //noinspection SimplifiableIfStatement
5452            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
5453                    mOnTouchListener.onTouch(this, event)) {
5454                return true;
5455            }
5456
5457            if (onTouchEvent(event)) {
5458                return true;
5459            }
5460        }
5461
5462        if (mInputEventConsistencyVerifier != null) {
5463            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5464        }
5465        return false;
5466    }
5467
5468    /**
5469     * Filter the touch event to apply security policies.
5470     *
5471     * @param event The motion event to be filtered.
5472     * @return True if the event should be dispatched, false if the event should be dropped.
5473     *
5474     * @see #getFilterTouchesWhenObscured
5475     */
5476    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5477        //noinspection RedundantIfStatement
5478        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5479                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5480            // Window is obscured, drop this touch.
5481            return false;
5482        }
5483        return true;
5484    }
5485
5486    /**
5487     * Pass a trackball motion event down to the focused view.
5488     *
5489     * @param event The motion event to be dispatched.
5490     * @return True if the event was handled by the view, false otherwise.
5491     */
5492    public boolean dispatchTrackballEvent(MotionEvent event) {
5493        if (mInputEventConsistencyVerifier != null) {
5494            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5495        }
5496
5497        return onTrackballEvent(event);
5498    }
5499
5500    /**
5501     * Dispatch a generic motion event.
5502     * <p>
5503     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5504     * are delivered to the view under the pointer.  All other generic motion events are
5505     * delivered to the focused view.  Hover events are handled specially and are delivered
5506     * to {@link #onHoverEvent(MotionEvent)}.
5507     * </p>
5508     *
5509     * @param event The motion event to be dispatched.
5510     * @return True if the event was handled by the view, false otherwise.
5511     */
5512    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5513        if (mInputEventConsistencyVerifier != null) {
5514            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5515        }
5516
5517        final int source = event.getSource();
5518        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5519            final int action = event.getAction();
5520            if (action == MotionEvent.ACTION_HOVER_ENTER
5521                    || action == MotionEvent.ACTION_HOVER_MOVE
5522                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5523                if (dispatchHoverEvent(event)) {
5524                    return true;
5525                }
5526            } else if (dispatchGenericPointerEvent(event)) {
5527                return true;
5528            }
5529        } else if (dispatchGenericFocusedEvent(event)) {
5530            return true;
5531        }
5532
5533        if (dispatchGenericMotionEventInternal(event)) {
5534            return true;
5535        }
5536
5537        if (mInputEventConsistencyVerifier != null) {
5538            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5539        }
5540        return false;
5541    }
5542
5543    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5544        //noinspection SimplifiableIfStatement
5545        if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5546                && mOnGenericMotionListener.onGenericMotion(this, event)) {
5547            return true;
5548        }
5549
5550        if (onGenericMotionEvent(event)) {
5551            return true;
5552        }
5553
5554        if (mInputEventConsistencyVerifier != null) {
5555            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5556        }
5557        return false;
5558    }
5559
5560    /**
5561     * Dispatch a hover event.
5562     * <p>
5563     * Do not call this method directly.
5564     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5565     * </p>
5566     *
5567     * @param event The motion event to be dispatched.
5568     * @return True if the event was handled by the view, false otherwise.
5569     */
5570    protected boolean dispatchHoverEvent(MotionEvent event) {
5571        //noinspection SimplifiableIfStatement
5572        if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5573                && mOnHoverListener.onHover(this, event)) {
5574            return true;
5575        }
5576
5577        return onHoverEvent(event);
5578    }
5579
5580    /**
5581     * Returns true if the view has a child to which it has recently sent
5582     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5583     * it does not have a hovered child, then it must be the innermost hovered view.
5584     * @hide
5585     */
5586    protected boolean hasHoveredChild() {
5587        return false;
5588    }
5589
5590    /**
5591     * Dispatch a generic motion event to the view under the first pointer.
5592     * <p>
5593     * Do not call this method directly.
5594     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5595     * </p>
5596     *
5597     * @param event The motion event to be dispatched.
5598     * @return True if the event was handled by the view, false otherwise.
5599     */
5600    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5601        return false;
5602    }
5603
5604    /**
5605     * Dispatch a generic motion event to the currently focused view.
5606     * <p>
5607     * Do not call this method directly.
5608     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5609     * </p>
5610     *
5611     * @param event The motion event to be dispatched.
5612     * @return True if the event was handled by the view, false otherwise.
5613     */
5614    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5615        return false;
5616    }
5617
5618    /**
5619     * Dispatch a pointer event.
5620     * <p>
5621     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5622     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5623     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5624     * and should not be expected to handle other pointing device features.
5625     * </p>
5626     *
5627     * @param event The motion event to be dispatched.
5628     * @return True if the event was handled by the view, false otherwise.
5629     * @hide
5630     */
5631    public final boolean dispatchPointerEvent(MotionEvent event) {
5632        if (event.isTouchEvent()) {
5633            return dispatchTouchEvent(event);
5634        } else {
5635            return dispatchGenericMotionEvent(event);
5636        }
5637    }
5638
5639    /**
5640     * Called when the window containing this view gains or loses window focus.
5641     * ViewGroups should override to route to their children.
5642     *
5643     * @param hasFocus True if the window containing this view now has focus,
5644     *        false otherwise.
5645     */
5646    public void dispatchWindowFocusChanged(boolean hasFocus) {
5647        onWindowFocusChanged(hasFocus);
5648    }
5649
5650    /**
5651     * Called when the window containing this view gains or loses focus.  Note
5652     * that this is separate from view focus: to receive key events, both
5653     * your view and its window must have focus.  If a window is displayed
5654     * on top of yours that takes input focus, then your own window will lose
5655     * focus but the view focus will remain unchanged.
5656     *
5657     * @param hasWindowFocus True if the window containing this view now has
5658     *        focus, false otherwise.
5659     */
5660    public void onWindowFocusChanged(boolean hasWindowFocus) {
5661        InputMethodManager imm = InputMethodManager.peekInstance();
5662        if (!hasWindowFocus) {
5663            if (isPressed()) {
5664                setPressed(false);
5665            }
5666            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5667                imm.focusOut(this);
5668            }
5669            removeLongPressCallback();
5670            removeTapCallback();
5671            onFocusLost();
5672        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5673            imm.focusIn(this);
5674        }
5675        refreshDrawableState();
5676    }
5677
5678    /**
5679     * Returns true if this view is in a window that currently has window focus.
5680     * Note that this is not the same as the view itself having focus.
5681     *
5682     * @return True if this view is in a window that currently has window focus.
5683     */
5684    public boolean hasWindowFocus() {
5685        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5686    }
5687
5688    /**
5689     * Dispatch a view visibility change down the view hierarchy.
5690     * ViewGroups should override to route to their children.
5691     * @param changedView The view whose visibility changed. Could be 'this' or
5692     * an ancestor view.
5693     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5694     * {@link #INVISIBLE} or {@link #GONE}.
5695     */
5696    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5697        onVisibilityChanged(changedView, visibility);
5698    }
5699
5700    /**
5701     * Called when the visibility of the view or an ancestor of the view is changed.
5702     * @param changedView The view whose visibility changed. Could be 'this' or
5703     * an ancestor view.
5704     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5705     * {@link #INVISIBLE} or {@link #GONE}.
5706     */
5707    protected void onVisibilityChanged(View changedView, int visibility) {
5708        if (visibility == VISIBLE) {
5709            if (mAttachInfo != null) {
5710                initialAwakenScrollBars();
5711            } else {
5712                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5713            }
5714        }
5715    }
5716
5717    /**
5718     * Dispatch a hint about whether this view is displayed. For instance, when
5719     * a View moves out of the screen, it might receives a display hint indicating
5720     * the view is not displayed. Applications should not <em>rely</em> on this hint
5721     * as there is no guarantee that they will receive one.
5722     *
5723     * @param hint A hint about whether or not this view is displayed:
5724     * {@link #VISIBLE} or {@link #INVISIBLE}.
5725     */
5726    public void dispatchDisplayHint(int hint) {
5727        onDisplayHint(hint);
5728    }
5729
5730    /**
5731     * Gives this view a hint about whether is displayed or not. For instance, when
5732     * a View moves out of the screen, it might receives a display hint indicating
5733     * the view is not displayed. Applications should not <em>rely</em> on this hint
5734     * as there is no guarantee that they will receive one.
5735     *
5736     * @param hint A hint about whether or not this view is displayed:
5737     * {@link #VISIBLE} or {@link #INVISIBLE}.
5738     */
5739    protected void onDisplayHint(int hint) {
5740    }
5741
5742    /**
5743     * Dispatch a window visibility change down the view hierarchy.
5744     * ViewGroups should override to route to their children.
5745     *
5746     * @param visibility The new visibility of the window.
5747     *
5748     * @see #onWindowVisibilityChanged(int)
5749     */
5750    public void dispatchWindowVisibilityChanged(int visibility) {
5751        onWindowVisibilityChanged(visibility);
5752    }
5753
5754    /**
5755     * Called when the window containing has change its visibility
5756     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5757     * that this tells you whether or not your window is being made visible
5758     * to the window manager; this does <em>not</em> tell you whether or not
5759     * your window is obscured by other windows on the screen, even if it
5760     * is itself visible.
5761     *
5762     * @param visibility The new visibility of the window.
5763     */
5764    protected void onWindowVisibilityChanged(int visibility) {
5765        if (visibility == VISIBLE) {
5766            initialAwakenScrollBars();
5767        }
5768    }
5769
5770    /**
5771     * Returns the current visibility of the window this view is attached to
5772     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5773     *
5774     * @return Returns the current visibility of the view's window.
5775     */
5776    public int getWindowVisibility() {
5777        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5778    }
5779
5780    /**
5781     * Retrieve the overall visible display size in which the window this view is
5782     * attached to has been positioned in.  This takes into account screen
5783     * decorations above the window, for both cases where the window itself
5784     * is being position inside of them or the window is being placed under
5785     * then and covered insets are used for the window to position its content
5786     * inside.  In effect, this tells you the available area where content can
5787     * be placed and remain visible to users.
5788     *
5789     * <p>This function requires an IPC back to the window manager to retrieve
5790     * the requested information, so should not be used in performance critical
5791     * code like drawing.
5792     *
5793     * @param outRect Filled in with the visible display frame.  If the view
5794     * is not attached to a window, this is simply the raw display size.
5795     */
5796    public void getWindowVisibleDisplayFrame(Rect outRect) {
5797        if (mAttachInfo != null) {
5798            try {
5799                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5800            } catch (RemoteException e) {
5801                return;
5802            }
5803            // XXX This is really broken, and probably all needs to be done
5804            // in the window manager, and we need to know more about whether
5805            // we want the area behind or in front of the IME.
5806            final Rect insets = mAttachInfo.mVisibleInsets;
5807            outRect.left += insets.left;
5808            outRect.top += insets.top;
5809            outRect.right -= insets.right;
5810            outRect.bottom -= insets.bottom;
5811            return;
5812        }
5813        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5814        d.getRectSize(outRect);
5815    }
5816
5817    /**
5818     * Dispatch a notification about a resource configuration change down
5819     * the view hierarchy.
5820     * ViewGroups should override to route to their children.
5821     *
5822     * @param newConfig The new resource configuration.
5823     *
5824     * @see #onConfigurationChanged(android.content.res.Configuration)
5825     */
5826    public void dispatchConfigurationChanged(Configuration newConfig) {
5827        onConfigurationChanged(newConfig);
5828    }
5829
5830    /**
5831     * Called when the current configuration of the resources being used
5832     * by the application have changed.  You can use this to decide when
5833     * to reload resources that can changed based on orientation and other
5834     * configuration characterstics.  You only need to use this if you are
5835     * not relying on the normal {@link android.app.Activity} mechanism of
5836     * recreating the activity instance upon a configuration change.
5837     *
5838     * @param newConfig The new resource configuration.
5839     */
5840    protected void onConfigurationChanged(Configuration newConfig) {
5841    }
5842
5843    /**
5844     * Private function to aggregate all per-view attributes in to the view
5845     * root.
5846     */
5847    void dispatchCollectViewAttributes(int visibility) {
5848        performCollectViewAttributes(visibility);
5849    }
5850
5851    void performCollectViewAttributes(int visibility) {
5852        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
5853            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
5854                mAttachInfo.mKeepScreenOn = true;
5855            }
5856            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
5857            if (mOnSystemUiVisibilityChangeListener != null) {
5858                mAttachInfo.mHasSystemUiListeners = true;
5859            }
5860        }
5861    }
5862
5863    void needGlobalAttributesUpdate(boolean force) {
5864        final AttachInfo ai = mAttachInfo;
5865        if (ai != null) {
5866            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
5867                    || ai.mHasSystemUiListeners) {
5868                ai.mRecomputeGlobalAttributes = true;
5869            }
5870        }
5871    }
5872
5873    /**
5874     * Returns whether the device is currently in touch mode.  Touch mode is entered
5875     * once the user begins interacting with the device by touch, and affects various
5876     * things like whether focus is always visible to the user.
5877     *
5878     * @return Whether the device is in touch mode.
5879     */
5880    @ViewDebug.ExportedProperty
5881    public boolean isInTouchMode() {
5882        if (mAttachInfo != null) {
5883            return mAttachInfo.mInTouchMode;
5884        } else {
5885            return ViewRootImpl.isInTouchMode();
5886        }
5887    }
5888
5889    /**
5890     * Returns the context the view is running in, through which it can
5891     * access the current theme, resources, etc.
5892     *
5893     * @return The view's Context.
5894     */
5895    @ViewDebug.CapturedViewProperty
5896    public final Context getContext() {
5897        return mContext;
5898    }
5899
5900    /**
5901     * Handle a key event before it is processed by any input method
5902     * associated with the view hierarchy.  This can be used to intercept
5903     * key events in special situations before the IME consumes them; a
5904     * typical example would be handling the BACK key to update the application's
5905     * UI instead of allowing the IME to see it and close itself.
5906     *
5907     * @param keyCode The value in event.getKeyCode().
5908     * @param event Description of the key event.
5909     * @return If you handled the event, return true. If you want to allow the
5910     *         event to be handled by the next receiver, return false.
5911     */
5912    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5913        return false;
5914    }
5915
5916    /**
5917     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
5918     * KeyEvent.Callback.onKeyDown()}: perform press of the view
5919     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
5920     * is released, if the view is enabled and clickable.
5921     *
5922     * @param keyCode A key code that represents the button pressed, from
5923     *                {@link android.view.KeyEvent}.
5924     * @param event   The KeyEvent object that defines the button action.
5925     */
5926    public boolean onKeyDown(int keyCode, KeyEvent event) {
5927        boolean result = false;
5928
5929        switch (keyCode) {
5930            case KeyEvent.KEYCODE_DPAD_CENTER:
5931            case KeyEvent.KEYCODE_ENTER: {
5932                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5933                    return true;
5934                }
5935                // Long clickable items don't necessarily have to be clickable
5936                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
5937                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
5938                        (event.getRepeatCount() == 0)) {
5939                    setPressed(true);
5940                    checkForLongClick(0);
5941                    return true;
5942                }
5943                break;
5944            }
5945        }
5946        return result;
5947    }
5948
5949    /**
5950     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
5951     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
5952     * the event).
5953     */
5954    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
5955        return false;
5956    }
5957
5958    /**
5959     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
5960     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
5961     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
5962     * {@link KeyEvent#KEYCODE_ENTER} is released.
5963     *
5964     * @param keyCode A key code that represents the button pressed, from
5965     *                {@link android.view.KeyEvent}.
5966     * @param event   The KeyEvent object that defines the button action.
5967     */
5968    public boolean onKeyUp(int keyCode, KeyEvent event) {
5969        boolean result = false;
5970
5971        switch (keyCode) {
5972            case KeyEvent.KEYCODE_DPAD_CENTER:
5973            case KeyEvent.KEYCODE_ENTER: {
5974                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5975                    return true;
5976                }
5977                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
5978                    setPressed(false);
5979
5980                    if (!mHasPerformedLongPress) {
5981                        // This is a tap, so remove the longpress check
5982                        removeLongPressCallback();
5983
5984                        result = performClick();
5985                    }
5986                }
5987                break;
5988            }
5989        }
5990        return result;
5991    }
5992
5993    /**
5994     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
5995     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
5996     * the event).
5997     *
5998     * @param keyCode     A key code that represents the button pressed, from
5999     *                    {@link android.view.KeyEvent}.
6000     * @param repeatCount The number of times the action was made.
6001     * @param event       The KeyEvent object that defines the button action.
6002     */
6003    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6004        return false;
6005    }
6006
6007    /**
6008     * Called on the focused view when a key shortcut event is not handled.
6009     * Override this method to implement local key shortcuts for the View.
6010     * Key shortcuts can also be implemented by setting the
6011     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6012     *
6013     * @param keyCode The value in event.getKeyCode().
6014     * @param event Description of the key event.
6015     * @return If you handled the event, return true. If you want to allow the
6016     *         event to be handled by the next receiver, return false.
6017     */
6018    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6019        return false;
6020    }
6021
6022    /**
6023     * Check whether the called view is a text editor, in which case it
6024     * would make sense to automatically display a soft input window for
6025     * it.  Subclasses should override this if they implement
6026     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6027     * a call on that method would return a non-null InputConnection, and
6028     * they are really a first-class editor that the user would normally
6029     * start typing on when the go into a window containing your view.
6030     *
6031     * <p>The default implementation always returns false.  This does
6032     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6033     * will not be called or the user can not otherwise perform edits on your
6034     * view; it is just a hint to the system that this is not the primary
6035     * purpose of this view.
6036     *
6037     * @return Returns true if this view is a text editor, else false.
6038     */
6039    public boolean onCheckIsTextEditor() {
6040        return false;
6041    }
6042
6043    /**
6044     * Create a new InputConnection for an InputMethod to interact
6045     * with the view.  The default implementation returns null, since it doesn't
6046     * support input methods.  You can override this to implement such support.
6047     * This is only needed for views that take focus and text input.
6048     *
6049     * <p>When implementing this, you probably also want to implement
6050     * {@link #onCheckIsTextEditor()} to indicate you will return a
6051     * non-null InputConnection.
6052     *
6053     * @param outAttrs Fill in with attribute information about the connection.
6054     */
6055    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6056        return null;
6057    }
6058
6059    /**
6060     * Called by the {@link android.view.inputmethod.InputMethodManager}
6061     * when a view who is not the current
6062     * input connection target is trying to make a call on the manager.  The
6063     * default implementation returns false; you can override this to return
6064     * true for certain views if you are performing InputConnection proxying
6065     * to them.
6066     * @param view The View that is making the InputMethodManager call.
6067     * @return Return true to allow the call, false to reject.
6068     */
6069    public boolean checkInputConnectionProxy(View view) {
6070        return false;
6071    }
6072
6073    /**
6074     * Show the context menu for this view. It is not safe to hold on to the
6075     * menu after returning from this method.
6076     *
6077     * You should normally not overload this method. Overload
6078     * {@link #onCreateContextMenu(ContextMenu)} or define an
6079     * {@link OnCreateContextMenuListener} to add items to the context menu.
6080     *
6081     * @param menu The context menu to populate
6082     */
6083    public void createContextMenu(ContextMenu menu) {
6084        ContextMenuInfo menuInfo = getContextMenuInfo();
6085
6086        // Sets the current menu info so all items added to menu will have
6087        // my extra info set.
6088        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6089
6090        onCreateContextMenu(menu);
6091        if (mOnCreateContextMenuListener != null) {
6092            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6093        }
6094
6095        // Clear the extra information so subsequent items that aren't mine don't
6096        // have my extra info.
6097        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6098
6099        if (mParent != null) {
6100            mParent.createContextMenu(menu);
6101        }
6102    }
6103
6104    /**
6105     * Views should implement this if they have extra information to associate
6106     * with the context menu. The return result is supplied as a parameter to
6107     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6108     * callback.
6109     *
6110     * @return Extra information about the item for which the context menu
6111     *         should be shown. This information will vary across different
6112     *         subclasses of View.
6113     */
6114    protected ContextMenuInfo getContextMenuInfo() {
6115        return null;
6116    }
6117
6118    /**
6119     * Views should implement this if the view itself is going to add items to
6120     * the context menu.
6121     *
6122     * @param menu the context menu to populate
6123     */
6124    protected void onCreateContextMenu(ContextMenu menu) {
6125    }
6126
6127    /**
6128     * Implement this method to handle trackball motion events.  The
6129     * <em>relative</em> movement of the trackball since the last event
6130     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6131     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6132     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6133     * they will often be fractional values, representing the more fine-grained
6134     * movement information available from a trackball).
6135     *
6136     * @param event The motion event.
6137     * @return True if the event was handled, false otherwise.
6138     */
6139    public boolean onTrackballEvent(MotionEvent event) {
6140        return false;
6141    }
6142
6143    /**
6144     * Implement this method to handle generic motion events.
6145     * <p>
6146     * Generic motion events describe joystick movements, mouse hovers, track pad
6147     * touches, scroll wheel movements and other input events.  The
6148     * {@link MotionEvent#getSource() source} of the motion event specifies
6149     * the class of input that was received.  Implementations of this method
6150     * must examine the bits in the source before processing the event.
6151     * The following code example shows how this is done.
6152     * </p><p>
6153     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6154     * are delivered to the view under the pointer.  All other generic motion events are
6155     * delivered to the focused view.
6156     * </p>
6157     * <code>
6158     * public boolean onGenericMotionEvent(MotionEvent event) {
6159     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6160     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6161     *             // process the joystick movement...
6162     *             return true;
6163     *         }
6164     *     }
6165     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6166     *         switch (event.getAction()) {
6167     *             case MotionEvent.ACTION_HOVER_MOVE:
6168     *                 // process the mouse hover movement...
6169     *                 return true;
6170     *             case MotionEvent.ACTION_SCROLL:
6171     *                 // process the scroll wheel movement...
6172     *                 return true;
6173     *         }
6174     *     }
6175     *     return super.onGenericMotionEvent(event);
6176     * }
6177     * </code>
6178     *
6179     * @param event The generic motion event being processed.
6180     * @return True if the event was handled, false otherwise.
6181     */
6182    public boolean onGenericMotionEvent(MotionEvent event) {
6183        return false;
6184    }
6185
6186    /**
6187     * Implement this method to handle hover events.
6188     * <p>
6189     * This method is called whenever a pointer is hovering into, over, or out of the
6190     * bounds of a view and the view is not currently being touched.
6191     * Hover events are represented as pointer events with action
6192     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6193     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6194     * </p>
6195     * <ul>
6196     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6197     * when the pointer enters the bounds of the view.</li>
6198     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6199     * when the pointer has already entered the bounds of the view and has moved.</li>
6200     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6201     * when the pointer has exited the bounds of the view or when the pointer is
6202     * about to go down due to a button click, tap, or similar user action that
6203     * causes the view to be touched.</li>
6204     * </ul>
6205     * <p>
6206     * The view should implement this method to return true to indicate that it is
6207     * handling the hover event, such as by changing its drawable state.
6208     * </p><p>
6209     * The default implementation calls {@link #setHovered} to update the hovered state
6210     * of the view when a hover enter or hover exit event is received, if the view
6211     * is enabled and is clickable.  The default implementation also sends hover
6212     * accessibility events.
6213     * </p>
6214     *
6215     * @param event The motion event that describes the hover.
6216     * @return True if the view handled the hover event.
6217     *
6218     * @see #isHovered
6219     * @see #setHovered
6220     * @see #onHoverChanged
6221     */
6222    public boolean onHoverEvent(MotionEvent event) {
6223        // The root view may receive hover (or touch) events that are outside the bounds of
6224        // the window.  This code ensures that we only send accessibility events for
6225        // hovers that are actually within the bounds of the root view.
6226        final int action = event.getAction();
6227        if (!mSendingHoverAccessibilityEvents) {
6228            if ((action == MotionEvent.ACTION_HOVER_ENTER
6229                    || action == MotionEvent.ACTION_HOVER_MOVE)
6230                    && !hasHoveredChild()
6231                    && pointInView(event.getX(), event.getY())) {
6232                mSendingHoverAccessibilityEvents = true;
6233                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6234            }
6235        } else {
6236            if (action == MotionEvent.ACTION_HOVER_EXIT
6237                    || (action == MotionEvent.ACTION_HOVER_MOVE
6238                            && !pointInView(event.getX(), event.getY()))) {
6239                mSendingHoverAccessibilityEvents = false;
6240                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6241            }
6242        }
6243
6244        if (isHoverable()) {
6245            switch (action) {
6246                case MotionEvent.ACTION_HOVER_ENTER:
6247                    setHovered(true);
6248                    break;
6249                case MotionEvent.ACTION_HOVER_EXIT:
6250                    setHovered(false);
6251                    break;
6252            }
6253
6254            // Dispatch the event to onGenericMotionEvent before returning true.
6255            // This is to provide compatibility with existing applications that
6256            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6257            // break because of the new default handling for hoverable views
6258            // in onHoverEvent.
6259            // Note that onGenericMotionEvent will be called by default when
6260            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6261            dispatchGenericMotionEventInternal(event);
6262            return true;
6263        }
6264        return false;
6265    }
6266
6267    /**
6268     * Returns true if the view should handle {@link #onHoverEvent}
6269     * by calling {@link #setHovered} to change its hovered state.
6270     *
6271     * @return True if the view is hoverable.
6272     */
6273    private boolean isHoverable() {
6274        final int viewFlags = mViewFlags;
6275        //noinspection SimplifiableIfStatement
6276        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6277            return false;
6278        }
6279
6280        return (viewFlags & CLICKABLE) == CLICKABLE
6281                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6282    }
6283
6284    /**
6285     * Returns true if the view is currently hovered.
6286     *
6287     * @return True if the view is currently hovered.
6288     *
6289     * @see #setHovered
6290     * @see #onHoverChanged
6291     */
6292    @ViewDebug.ExportedProperty
6293    public boolean isHovered() {
6294        return (mPrivateFlags & HOVERED) != 0;
6295    }
6296
6297    /**
6298     * Sets whether the view is currently hovered.
6299     * <p>
6300     * Calling this method also changes the drawable state of the view.  This
6301     * enables the view to react to hover by using different drawable resources
6302     * to change its appearance.
6303     * </p><p>
6304     * The {@link #onHoverChanged} method is called when the hovered state changes.
6305     * </p>
6306     *
6307     * @param hovered True if the view is hovered.
6308     *
6309     * @see #isHovered
6310     * @see #onHoverChanged
6311     */
6312    public void setHovered(boolean hovered) {
6313        if (hovered) {
6314            if ((mPrivateFlags & HOVERED) == 0) {
6315                mPrivateFlags |= HOVERED;
6316                refreshDrawableState();
6317                onHoverChanged(true);
6318            }
6319        } else {
6320            if ((mPrivateFlags & HOVERED) != 0) {
6321                mPrivateFlags &= ~HOVERED;
6322                refreshDrawableState();
6323                onHoverChanged(false);
6324            }
6325        }
6326    }
6327
6328    /**
6329     * Implement this method to handle hover state changes.
6330     * <p>
6331     * This method is called whenever the hover state changes as a result of a
6332     * call to {@link #setHovered}.
6333     * </p>
6334     *
6335     * @param hovered The current hover state, as returned by {@link #isHovered}.
6336     *
6337     * @see #isHovered
6338     * @see #setHovered
6339     */
6340    public void onHoverChanged(boolean hovered) {
6341    }
6342
6343    /**
6344     * Implement this method to handle touch screen motion events.
6345     *
6346     * @param event The motion event.
6347     * @return True if the event was handled, false otherwise.
6348     */
6349    public boolean onTouchEvent(MotionEvent event) {
6350        final int viewFlags = mViewFlags;
6351
6352        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6353            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6354                mPrivateFlags &= ~PRESSED;
6355                refreshDrawableState();
6356            }
6357            // A disabled view that is clickable still consumes the touch
6358            // events, it just doesn't respond to them.
6359            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6360                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6361        }
6362
6363        if (mTouchDelegate != null) {
6364            if (mTouchDelegate.onTouchEvent(event)) {
6365                return true;
6366            }
6367        }
6368
6369        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6370                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6371            switch (event.getAction()) {
6372                case MotionEvent.ACTION_UP:
6373                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6374                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6375                        // take focus if we don't have it already and we should in
6376                        // touch mode.
6377                        boolean focusTaken = false;
6378                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6379                            focusTaken = requestFocus();
6380                        }
6381
6382                        if (prepressed) {
6383                            // The button is being released before we actually
6384                            // showed it as pressed.  Make it show the pressed
6385                            // state now (before scheduling the click) to ensure
6386                            // the user sees it.
6387                            mPrivateFlags |= PRESSED;
6388                            refreshDrawableState();
6389                       }
6390
6391                        if (!mHasPerformedLongPress) {
6392                            // This is a tap, so remove the longpress check
6393                            removeLongPressCallback();
6394
6395                            // Only perform take click actions if we were in the pressed state
6396                            if (!focusTaken) {
6397                                // Use a Runnable and post this rather than calling
6398                                // performClick directly. This lets other visual state
6399                                // of the view update before click actions start.
6400                                if (mPerformClick == null) {
6401                                    mPerformClick = new PerformClick();
6402                                }
6403                                if (!post(mPerformClick)) {
6404                                    performClick();
6405                                }
6406                            }
6407                        }
6408
6409                        if (mUnsetPressedState == null) {
6410                            mUnsetPressedState = new UnsetPressedState();
6411                        }
6412
6413                        if (prepressed) {
6414                            postDelayed(mUnsetPressedState,
6415                                    ViewConfiguration.getPressedStateDuration());
6416                        } else if (!post(mUnsetPressedState)) {
6417                            // If the post failed, unpress right now
6418                            mUnsetPressedState.run();
6419                        }
6420                        removeTapCallback();
6421                    }
6422                    break;
6423
6424                case MotionEvent.ACTION_DOWN:
6425                    mHasPerformedLongPress = false;
6426
6427                    if (performButtonActionOnTouchDown(event)) {
6428                        break;
6429                    }
6430
6431                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6432                    boolean isInScrollingContainer = isInScrollingContainer();
6433
6434                    // For views inside a scrolling container, delay the pressed feedback for
6435                    // a short period in case this is a scroll.
6436                    if (isInScrollingContainer) {
6437                        mPrivateFlags |= PREPRESSED;
6438                        if (mPendingCheckForTap == null) {
6439                            mPendingCheckForTap = new CheckForTap();
6440                        }
6441                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6442                    } else {
6443                        // Not inside a scrolling container, so show the feedback right away
6444                        mPrivateFlags |= PRESSED;
6445                        refreshDrawableState();
6446                        checkForLongClick(0);
6447                    }
6448                    break;
6449
6450                case MotionEvent.ACTION_CANCEL:
6451                    mPrivateFlags &= ~PRESSED;
6452                    refreshDrawableState();
6453                    removeTapCallback();
6454                    break;
6455
6456                case MotionEvent.ACTION_MOVE:
6457                    final int x = (int) event.getX();
6458                    final int y = (int) event.getY();
6459
6460                    // Be lenient about moving outside of buttons
6461                    if (!pointInView(x, y, mTouchSlop)) {
6462                        // Outside button
6463                        removeTapCallback();
6464                        if ((mPrivateFlags & PRESSED) != 0) {
6465                            // Remove any future long press/tap checks
6466                            removeLongPressCallback();
6467
6468                            // Need to switch from pressed to not pressed
6469                            mPrivateFlags &= ~PRESSED;
6470                            refreshDrawableState();
6471                        }
6472                    }
6473                    break;
6474            }
6475            return true;
6476        }
6477
6478        return false;
6479    }
6480
6481    /**
6482     * @hide
6483     */
6484    public boolean isInScrollingContainer() {
6485        ViewParent p = getParent();
6486        while (p != null && p instanceof ViewGroup) {
6487            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6488                return true;
6489            }
6490            p = p.getParent();
6491        }
6492        return false;
6493    }
6494
6495    /**
6496     * Remove the longpress detection timer.
6497     */
6498    private void removeLongPressCallback() {
6499        if (mPendingCheckForLongPress != null) {
6500          removeCallbacks(mPendingCheckForLongPress);
6501        }
6502    }
6503
6504    /**
6505     * Remove the pending click action
6506     */
6507    private void removePerformClickCallback() {
6508        if (mPerformClick != null) {
6509            removeCallbacks(mPerformClick);
6510        }
6511    }
6512
6513    /**
6514     * Remove the prepress detection timer.
6515     */
6516    private void removeUnsetPressCallback() {
6517        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6518            setPressed(false);
6519            removeCallbacks(mUnsetPressedState);
6520        }
6521    }
6522
6523    /**
6524     * Remove the tap detection timer.
6525     */
6526    private void removeTapCallback() {
6527        if (mPendingCheckForTap != null) {
6528            mPrivateFlags &= ~PREPRESSED;
6529            removeCallbacks(mPendingCheckForTap);
6530        }
6531    }
6532
6533    /**
6534     * Cancels a pending long press.  Your subclass can use this if you
6535     * want the context menu to come up if the user presses and holds
6536     * at the same place, but you don't want it to come up if they press
6537     * and then move around enough to cause scrolling.
6538     */
6539    public void cancelLongPress() {
6540        removeLongPressCallback();
6541
6542        /*
6543         * The prepressed state handled by the tap callback is a display
6544         * construct, but the tap callback will post a long press callback
6545         * less its own timeout. Remove it here.
6546         */
6547        removeTapCallback();
6548    }
6549
6550    /**
6551     * Remove the pending callback for sending a
6552     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6553     */
6554    private void removeSendViewScrolledAccessibilityEventCallback() {
6555        if (mSendViewScrolledAccessibilityEvent != null) {
6556            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6557        }
6558    }
6559
6560    /**
6561     * Sets the TouchDelegate for this View.
6562     */
6563    public void setTouchDelegate(TouchDelegate delegate) {
6564        mTouchDelegate = delegate;
6565    }
6566
6567    /**
6568     * Gets the TouchDelegate for this View.
6569     */
6570    public TouchDelegate getTouchDelegate() {
6571        return mTouchDelegate;
6572    }
6573
6574    /**
6575     * Set flags controlling behavior of this view.
6576     *
6577     * @param flags Constant indicating the value which should be set
6578     * @param mask Constant indicating the bit range that should be changed
6579     */
6580    void setFlags(int flags, int mask) {
6581        int old = mViewFlags;
6582        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6583
6584        int changed = mViewFlags ^ old;
6585        if (changed == 0) {
6586            return;
6587        }
6588        int privateFlags = mPrivateFlags;
6589
6590        /* Check if the FOCUSABLE bit has changed */
6591        if (((changed & FOCUSABLE_MASK) != 0) &&
6592                ((privateFlags & HAS_BOUNDS) !=0)) {
6593            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6594                    && ((privateFlags & FOCUSED) != 0)) {
6595                /* Give up focus if we are no longer focusable */
6596                clearFocus();
6597            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6598                    && ((privateFlags & FOCUSED) == 0)) {
6599                /*
6600                 * Tell the view system that we are now available to take focus
6601                 * if no one else already has it.
6602                 */
6603                if (mParent != null) mParent.focusableViewAvailable(this);
6604            }
6605        }
6606
6607        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6608            if ((changed & VISIBILITY_MASK) != 0) {
6609                /*
6610                 * If this view is becoming visible, invalidate it in case it changed while
6611                 * it was not visible. Marking it drawn ensures that the invalidation will
6612                 * go through.
6613                 */
6614                mPrivateFlags |= DRAWN;
6615                invalidate(true);
6616
6617                needGlobalAttributesUpdate(true);
6618
6619                // a view becoming visible is worth notifying the parent
6620                // about in case nothing has focus.  even if this specific view
6621                // isn't focusable, it may contain something that is, so let
6622                // the root view try to give this focus if nothing else does.
6623                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6624                    mParent.focusableViewAvailable(this);
6625                }
6626            }
6627        }
6628
6629        /* Check if the GONE bit has changed */
6630        if ((changed & GONE) != 0) {
6631            needGlobalAttributesUpdate(false);
6632            requestLayout();
6633
6634            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6635                if (hasFocus()) clearFocus();
6636                destroyDrawingCache();
6637                if (mParent instanceof View) {
6638                    // GONE views noop invalidation, so invalidate the parent
6639                    ((View) mParent).invalidate(true);
6640                }
6641                // Mark the view drawn to ensure that it gets invalidated properly the next
6642                // time it is visible and gets invalidated
6643                mPrivateFlags |= DRAWN;
6644            }
6645            if (mAttachInfo != null) {
6646                mAttachInfo.mViewVisibilityChanged = true;
6647            }
6648        }
6649
6650        /* Check if the VISIBLE bit has changed */
6651        if ((changed & INVISIBLE) != 0) {
6652            needGlobalAttributesUpdate(false);
6653            /*
6654             * If this view is becoming invisible, set the DRAWN flag so that
6655             * the next invalidate() will not be skipped.
6656             */
6657            mPrivateFlags |= DRAWN;
6658
6659            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6660                // root view becoming invisible shouldn't clear focus
6661                if (getRootView() != this) {
6662                    clearFocus();
6663                }
6664            }
6665            if (mAttachInfo != null) {
6666                mAttachInfo.mViewVisibilityChanged = true;
6667            }
6668        }
6669
6670        if ((changed & VISIBILITY_MASK) != 0) {
6671            if (mParent instanceof ViewGroup) {
6672                ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
6673                ((View) mParent).invalidate(true);
6674            } else if (mParent != null) {
6675                mParent.invalidateChild(this, null);
6676            }
6677            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6678        }
6679
6680        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6681            destroyDrawingCache();
6682        }
6683
6684        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6685            destroyDrawingCache();
6686            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6687            invalidateParentCaches();
6688        }
6689
6690        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6691            destroyDrawingCache();
6692            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6693        }
6694
6695        if ((changed & DRAW_MASK) != 0) {
6696            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6697                if (mBGDrawable != null) {
6698                    mPrivateFlags &= ~SKIP_DRAW;
6699                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6700                } else {
6701                    mPrivateFlags |= SKIP_DRAW;
6702                }
6703            } else {
6704                mPrivateFlags &= ~SKIP_DRAW;
6705            }
6706            requestLayout();
6707            invalidate(true);
6708        }
6709
6710        if ((changed & KEEP_SCREEN_ON) != 0) {
6711            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6712                mParent.recomputeViewAttributes(this);
6713            }
6714        }
6715
6716        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6717            requestLayout();
6718        }
6719    }
6720
6721    /**
6722     * Change the view's z order in the tree, so it's on top of other sibling
6723     * views
6724     */
6725    public void bringToFront() {
6726        if (mParent != null) {
6727            mParent.bringChildToFront(this);
6728        }
6729    }
6730
6731    /**
6732     * This is called in response to an internal scroll in this view (i.e., the
6733     * view scrolled its own contents). This is typically as a result of
6734     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6735     * called.
6736     *
6737     * @param l Current horizontal scroll origin.
6738     * @param t Current vertical scroll origin.
6739     * @param oldl Previous horizontal scroll origin.
6740     * @param oldt Previous vertical scroll origin.
6741     */
6742    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6743        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6744            postSendViewScrolledAccessibilityEventCallback();
6745        }
6746
6747        mBackgroundSizeChanged = true;
6748
6749        final AttachInfo ai = mAttachInfo;
6750        if (ai != null) {
6751            ai.mViewScrollChanged = true;
6752        }
6753    }
6754
6755    /**
6756     * Interface definition for a callback to be invoked when the layout bounds of a view
6757     * changes due to layout processing.
6758     */
6759    public interface OnLayoutChangeListener {
6760        /**
6761         * Called when the focus state of a view has changed.
6762         *
6763         * @param v The view whose state has changed.
6764         * @param left The new value of the view's left property.
6765         * @param top The new value of the view's top property.
6766         * @param right The new value of the view's right property.
6767         * @param bottom The new value of the view's bottom property.
6768         * @param oldLeft The previous value of the view's left property.
6769         * @param oldTop The previous value of the view's top property.
6770         * @param oldRight The previous value of the view's right property.
6771         * @param oldBottom The previous value of the view's bottom property.
6772         */
6773        void onLayoutChange(View v, int left, int top, int right, int bottom,
6774            int oldLeft, int oldTop, int oldRight, int oldBottom);
6775    }
6776
6777    /**
6778     * This is called during layout when the size of this view has changed. If
6779     * you were just added to the view hierarchy, you're called with the old
6780     * values of 0.
6781     *
6782     * @param w Current width of this view.
6783     * @param h Current height of this view.
6784     * @param oldw Old width of this view.
6785     * @param oldh Old height of this view.
6786     */
6787    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6788    }
6789
6790    /**
6791     * Called by draw to draw the child views. This may be overridden
6792     * by derived classes to gain control just before its children are drawn
6793     * (but after its own view has been drawn).
6794     * @param canvas the canvas on which to draw the view
6795     */
6796    protected void dispatchDraw(Canvas canvas) {
6797    }
6798
6799    /**
6800     * Gets the parent of this view. Note that the parent is a
6801     * ViewParent and not necessarily a View.
6802     *
6803     * @return Parent of this view.
6804     */
6805    public final ViewParent getParent() {
6806        return mParent;
6807    }
6808
6809    /**
6810     * Set the horizontal scrolled position of your view. This will cause a call to
6811     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6812     * invalidated.
6813     * @param value the x position to scroll to
6814     */
6815    public void setScrollX(int value) {
6816        scrollTo(value, mScrollY);
6817    }
6818
6819    /**
6820     * Set the vertical scrolled position of your view. This will cause a call to
6821     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6822     * invalidated.
6823     * @param value the y position to scroll to
6824     */
6825    public void setScrollY(int value) {
6826        scrollTo(mScrollX, value);
6827    }
6828
6829    /**
6830     * Return the scrolled left position of this view. This is the left edge of
6831     * the displayed part of your view. You do not need to draw any pixels
6832     * farther left, since those are outside of the frame of your view on
6833     * screen.
6834     *
6835     * @return The left edge of the displayed part of your view, in pixels.
6836     */
6837    public final int getScrollX() {
6838        return mScrollX;
6839    }
6840
6841    /**
6842     * Return the scrolled top position of this view. This is the top edge of
6843     * the displayed part of your view. You do not need to draw any pixels above
6844     * it, since those are outside of the frame of your view on screen.
6845     *
6846     * @return The top edge of the displayed part of your view, in pixels.
6847     */
6848    public final int getScrollY() {
6849        return mScrollY;
6850    }
6851
6852    /**
6853     * Return the width of the your view.
6854     *
6855     * @return The width of your view, in pixels.
6856     */
6857    @ViewDebug.ExportedProperty(category = "layout")
6858    public final int getWidth() {
6859        return mRight - mLeft;
6860    }
6861
6862    /**
6863     * Return the height of your view.
6864     *
6865     * @return The height of your view, in pixels.
6866     */
6867    @ViewDebug.ExportedProperty(category = "layout")
6868    public final int getHeight() {
6869        return mBottom - mTop;
6870    }
6871
6872    /**
6873     * Return the visible drawing bounds of your view. Fills in the output
6874     * rectangle with the values from getScrollX(), getScrollY(),
6875     * getWidth(), and getHeight().
6876     *
6877     * @param outRect The (scrolled) drawing bounds of the view.
6878     */
6879    public void getDrawingRect(Rect outRect) {
6880        outRect.left = mScrollX;
6881        outRect.top = mScrollY;
6882        outRect.right = mScrollX + (mRight - mLeft);
6883        outRect.bottom = mScrollY + (mBottom - mTop);
6884    }
6885
6886    /**
6887     * Like {@link #getMeasuredWidthAndState()}, but only returns the
6888     * raw width component (that is the result is masked by
6889     * {@link #MEASURED_SIZE_MASK}).
6890     *
6891     * @return The raw measured width of this view.
6892     */
6893    public final int getMeasuredWidth() {
6894        return mMeasuredWidth & MEASURED_SIZE_MASK;
6895    }
6896
6897    /**
6898     * Return the full width measurement information for this view as computed
6899     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6900     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6901     * This should be used during measurement and layout calculations only. Use
6902     * {@link #getWidth()} to see how wide a view is after layout.
6903     *
6904     * @return The measured width of this view as a bit mask.
6905     */
6906    public final int getMeasuredWidthAndState() {
6907        return mMeasuredWidth;
6908    }
6909
6910    /**
6911     * Like {@link #getMeasuredHeightAndState()}, but only returns the
6912     * raw width component (that is the result is masked by
6913     * {@link #MEASURED_SIZE_MASK}).
6914     *
6915     * @return The raw measured height of this view.
6916     */
6917    public final int getMeasuredHeight() {
6918        return mMeasuredHeight & MEASURED_SIZE_MASK;
6919    }
6920
6921    /**
6922     * Return the full height measurement information for this view as computed
6923     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6924     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6925     * This should be used during measurement and layout calculations only. Use
6926     * {@link #getHeight()} to see how wide a view is after layout.
6927     *
6928     * @return The measured width of this view as a bit mask.
6929     */
6930    public final int getMeasuredHeightAndState() {
6931        return mMeasuredHeight;
6932    }
6933
6934    /**
6935     * Return only the state bits of {@link #getMeasuredWidthAndState()}
6936     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
6937     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
6938     * and the height component is at the shifted bits
6939     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
6940     */
6941    public final int getMeasuredState() {
6942        return (mMeasuredWidth&MEASURED_STATE_MASK)
6943                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
6944                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
6945    }
6946
6947    /**
6948     * The transform matrix of this view, which is calculated based on the current
6949     * roation, scale, and pivot properties.
6950     *
6951     * @see #getRotation()
6952     * @see #getScaleX()
6953     * @see #getScaleY()
6954     * @see #getPivotX()
6955     * @see #getPivotY()
6956     * @return The current transform matrix for the view
6957     */
6958    public Matrix getMatrix() {
6959        if (mTransformationInfo != null) {
6960            updateMatrix();
6961            return mTransformationInfo.mMatrix;
6962        }
6963        return Matrix.IDENTITY_MATRIX;
6964    }
6965
6966    /**
6967     * Utility function to determine if the value is far enough away from zero to be
6968     * considered non-zero.
6969     * @param value A floating point value to check for zero-ness
6970     * @return whether the passed-in value is far enough away from zero to be considered non-zero
6971     */
6972    private static boolean nonzero(float value) {
6973        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
6974    }
6975
6976    /**
6977     * Returns true if the transform matrix is the identity matrix.
6978     * Recomputes the matrix if necessary.
6979     *
6980     * @return True if the transform matrix is the identity matrix, false otherwise.
6981     */
6982    final boolean hasIdentityMatrix() {
6983        if (mTransformationInfo != null) {
6984            updateMatrix();
6985            return mTransformationInfo.mMatrixIsIdentity;
6986        }
6987        return true;
6988    }
6989
6990    void ensureTransformationInfo() {
6991        if (mTransformationInfo == null) {
6992            mTransformationInfo = new TransformationInfo();
6993        }
6994    }
6995
6996    /**
6997     * Recomputes the transform matrix if necessary.
6998     */
6999    private void updateMatrix() {
7000        final TransformationInfo info = mTransformationInfo;
7001        if (info == null) {
7002            return;
7003        }
7004        if (info.mMatrixDirty) {
7005            // transform-related properties have changed since the last time someone
7006            // asked for the matrix; recalculate it with the current values
7007
7008            // Figure out if we need to update the pivot point
7009            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7010                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7011                    info.mPrevWidth = mRight - mLeft;
7012                    info.mPrevHeight = mBottom - mTop;
7013                    info.mPivotX = info.mPrevWidth / 2f;
7014                    info.mPivotY = info.mPrevHeight / 2f;
7015                }
7016            }
7017            info.mMatrix.reset();
7018            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7019                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7020                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7021                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7022            } else {
7023                if (info.mCamera == null) {
7024                    info.mCamera = new Camera();
7025                    info.matrix3D = new Matrix();
7026                }
7027                info.mCamera.save();
7028                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7029                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7030                info.mCamera.getMatrix(info.matrix3D);
7031                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7032                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7033                        info.mPivotY + info.mTranslationY);
7034                info.mMatrix.postConcat(info.matrix3D);
7035                info.mCamera.restore();
7036            }
7037            info.mMatrixDirty = false;
7038            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7039            info.mInverseMatrixDirty = true;
7040        }
7041    }
7042
7043    /**
7044     * Utility method to retrieve the inverse of the current mMatrix property.
7045     * We cache the matrix to avoid recalculating it when transform properties
7046     * have not changed.
7047     *
7048     * @return The inverse of the current matrix of this view.
7049     */
7050    final Matrix getInverseMatrix() {
7051        final TransformationInfo info = mTransformationInfo;
7052        if (info != null) {
7053            updateMatrix();
7054            if (info.mInverseMatrixDirty) {
7055                if (info.mInverseMatrix == null) {
7056                    info.mInverseMatrix = new Matrix();
7057                }
7058                info.mMatrix.invert(info.mInverseMatrix);
7059                info.mInverseMatrixDirty = false;
7060            }
7061            return info.mInverseMatrix;
7062        }
7063        return Matrix.IDENTITY_MATRIX;
7064    }
7065
7066    /**
7067     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7068     * views are drawn) from the camera to this view. The camera's distance
7069     * affects 3D transformations, for instance rotations around the X and Y
7070     * axis. If the rotationX or rotationY properties are changed and this view is
7071     * large (more than half the size of the screen), it is recommended to always
7072     * use a camera distance that's greater than the height (X axis rotation) or
7073     * the width (Y axis rotation) of this view.</p>
7074     *
7075     * <p>The distance of the camera from the view plane can have an affect on the
7076     * perspective distortion of the view when it is rotated around the x or y axis.
7077     * For example, a large distance will result in a large viewing angle, and there
7078     * will not be much perspective distortion of the view as it rotates. A short
7079     * distance may cause much more perspective distortion upon rotation, and can
7080     * also result in some drawing artifacts if the rotated view ends up partially
7081     * behind the camera (which is why the recommendation is to use a distance at
7082     * least as far as the size of the view, if the view is to be rotated.)</p>
7083     *
7084     * <p>The distance is expressed in "depth pixels." The default distance depends
7085     * on the screen density. For instance, on a medium density display, the
7086     * default distance is 1280. On a high density display, the default distance
7087     * is 1920.</p>
7088     *
7089     * <p>If you want to specify a distance that leads to visually consistent
7090     * results across various densities, use the following formula:</p>
7091     * <pre>
7092     * float scale = context.getResources().getDisplayMetrics().density;
7093     * view.setCameraDistance(distance * scale);
7094     * </pre>
7095     *
7096     * <p>The density scale factor of a high density display is 1.5,
7097     * and 1920 = 1280 * 1.5.</p>
7098     *
7099     * @param distance The distance in "depth pixels", if negative the opposite
7100     *        value is used
7101     *
7102     * @see #setRotationX(float)
7103     * @see #setRotationY(float)
7104     */
7105    public void setCameraDistance(float distance) {
7106        invalidateParentCaches();
7107        invalidate(false);
7108
7109        ensureTransformationInfo();
7110        final float dpi = mResources.getDisplayMetrics().densityDpi;
7111        final TransformationInfo info = mTransformationInfo;
7112        if (info.mCamera == null) {
7113            info.mCamera = new Camera();
7114            info.matrix3D = new Matrix();
7115        }
7116
7117        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7118        info.mMatrixDirty = true;
7119
7120        invalidate(false);
7121    }
7122
7123    /**
7124     * The degrees that the view is rotated around the pivot point.
7125     *
7126     * @see #setRotation(float)
7127     * @see #getPivotX()
7128     * @see #getPivotY()
7129     *
7130     * @return The degrees of rotation.
7131     */
7132    public float getRotation() {
7133        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7134    }
7135
7136    /**
7137     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7138     * result in clockwise rotation.
7139     *
7140     * @param rotation The degrees of rotation.
7141     *
7142     * @see #getRotation()
7143     * @see #getPivotX()
7144     * @see #getPivotY()
7145     * @see #setRotationX(float)
7146     * @see #setRotationY(float)
7147     *
7148     * @attr ref android.R.styleable#View_rotation
7149     */
7150    public void setRotation(float rotation) {
7151        ensureTransformationInfo();
7152        final TransformationInfo info = mTransformationInfo;
7153        if (info.mRotation != rotation) {
7154            invalidateParentCaches();
7155            // Double-invalidation is necessary to capture view's old and new areas
7156            invalidate(false);
7157            info.mRotation = rotation;
7158            info.mMatrixDirty = true;
7159            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7160            invalidate(false);
7161        }
7162    }
7163
7164    /**
7165     * The degrees that the view is rotated around the vertical axis through the pivot point.
7166     *
7167     * @see #getPivotX()
7168     * @see #getPivotY()
7169     * @see #setRotationY(float)
7170     *
7171     * @return The degrees of Y rotation.
7172     */
7173    public float getRotationY() {
7174        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7175    }
7176
7177    /**
7178     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7179     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7180     * down the y axis.
7181     *
7182     * When rotating large views, it is recommended to adjust the camera distance
7183     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7184     *
7185     * @param rotationY The degrees of Y rotation.
7186     *
7187     * @see #getRotationY()
7188     * @see #getPivotX()
7189     * @see #getPivotY()
7190     * @see #setRotation(float)
7191     * @see #setRotationX(float)
7192     * @see #setCameraDistance(float)
7193     *
7194     * @attr ref android.R.styleable#View_rotationY
7195     */
7196    public void setRotationY(float rotationY) {
7197        ensureTransformationInfo();
7198        final TransformationInfo info = mTransformationInfo;
7199        if (info.mRotationY != rotationY) {
7200            invalidateParentCaches();
7201            // Double-invalidation is necessary to capture view's old and new areas
7202            invalidate(false);
7203            info.mRotationY = rotationY;
7204            info.mMatrixDirty = true;
7205            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7206            invalidate(false);
7207        }
7208    }
7209
7210    /**
7211     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7212     *
7213     * @see #getPivotX()
7214     * @see #getPivotY()
7215     * @see #setRotationX(float)
7216     *
7217     * @return The degrees of X rotation.
7218     */
7219    public float getRotationX() {
7220        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7221    }
7222
7223    /**
7224     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7225     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7226     * x axis.
7227     *
7228     * When rotating large views, it is recommended to adjust the camera distance
7229     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7230     *
7231     * @param rotationX The degrees of X rotation.
7232     *
7233     * @see #getRotationX()
7234     * @see #getPivotX()
7235     * @see #getPivotY()
7236     * @see #setRotation(float)
7237     * @see #setRotationY(float)
7238     * @see #setCameraDistance(float)
7239     *
7240     * @attr ref android.R.styleable#View_rotationX
7241     */
7242    public void setRotationX(float rotationX) {
7243        ensureTransformationInfo();
7244        final TransformationInfo info = mTransformationInfo;
7245        if (info.mRotationX != rotationX) {
7246            invalidateParentCaches();
7247            // Double-invalidation is necessary to capture view's old and new areas
7248            invalidate(false);
7249            info.mRotationX = rotationX;
7250            info.mMatrixDirty = true;
7251            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7252            invalidate(false);
7253        }
7254    }
7255
7256    /**
7257     * The amount that the view is scaled in x around the pivot point, as a proportion of
7258     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7259     *
7260     * <p>By default, this is 1.0f.
7261     *
7262     * @see #getPivotX()
7263     * @see #getPivotY()
7264     * @return The scaling factor.
7265     */
7266    public float getScaleX() {
7267        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7268    }
7269
7270    /**
7271     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7272     * the view's unscaled width. A value of 1 means that no scaling is applied.
7273     *
7274     * @param scaleX The scaling factor.
7275     * @see #getPivotX()
7276     * @see #getPivotY()
7277     *
7278     * @attr ref android.R.styleable#View_scaleX
7279     */
7280    public void setScaleX(float scaleX) {
7281        ensureTransformationInfo();
7282        final TransformationInfo info = mTransformationInfo;
7283        if (info.mScaleX != scaleX) {
7284            invalidateParentCaches();
7285            // Double-invalidation is necessary to capture view's old and new areas
7286            invalidate(false);
7287            info.mScaleX = scaleX;
7288            info.mMatrixDirty = true;
7289            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7290            invalidate(false);
7291        }
7292    }
7293
7294    /**
7295     * The amount that the view is scaled in y around the pivot point, as a proportion of
7296     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7297     *
7298     * <p>By default, this is 1.0f.
7299     *
7300     * @see #getPivotX()
7301     * @see #getPivotY()
7302     * @return The scaling factor.
7303     */
7304    public float getScaleY() {
7305        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7306    }
7307
7308    /**
7309     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7310     * the view's unscaled width. A value of 1 means that no scaling is applied.
7311     *
7312     * @param scaleY The scaling factor.
7313     * @see #getPivotX()
7314     * @see #getPivotY()
7315     *
7316     * @attr ref android.R.styleable#View_scaleY
7317     */
7318    public void setScaleY(float scaleY) {
7319        ensureTransformationInfo();
7320        final TransformationInfo info = mTransformationInfo;
7321        if (info.mScaleY != scaleY) {
7322            invalidateParentCaches();
7323            // Double-invalidation is necessary to capture view's old and new areas
7324            invalidate(false);
7325            info.mScaleY = scaleY;
7326            info.mMatrixDirty = true;
7327            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7328            invalidate(false);
7329        }
7330    }
7331
7332    /**
7333     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7334     * and {@link #setScaleX(float) scaled}.
7335     *
7336     * @see #getRotation()
7337     * @see #getScaleX()
7338     * @see #getScaleY()
7339     * @see #getPivotY()
7340     * @return The x location of the pivot point.
7341     */
7342    public float getPivotX() {
7343        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7344    }
7345
7346    /**
7347     * Sets the x location of the point around which the view is
7348     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7349     * By default, the pivot point is centered on the object.
7350     * Setting this property disables this behavior and causes the view to use only the
7351     * explicitly set pivotX and pivotY values.
7352     *
7353     * @param pivotX The x location of the pivot point.
7354     * @see #getRotation()
7355     * @see #getScaleX()
7356     * @see #getScaleY()
7357     * @see #getPivotY()
7358     *
7359     * @attr ref android.R.styleable#View_transformPivotX
7360     */
7361    public void setPivotX(float pivotX) {
7362        ensureTransformationInfo();
7363        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7364        final TransformationInfo info = mTransformationInfo;
7365        if (info.mPivotX != pivotX) {
7366            invalidateParentCaches();
7367            // Double-invalidation is necessary to capture view's old and new areas
7368            invalidate(false);
7369            info.mPivotX = pivotX;
7370            info.mMatrixDirty = true;
7371            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7372            invalidate(false);
7373        }
7374    }
7375
7376    /**
7377     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7378     * and {@link #setScaleY(float) scaled}.
7379     *
7380     * @see #getRotation()
7381     * @see #getScaleX()
7382     * @see #getScaleY()
7383     * @see #getPivotY()
7384     * @return The y location of the pivot point.
7385     */
7386    public float getPivotY() {
7387        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7388    }
7389
7390    /**
7391     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7392     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7393     * Setting this property disables this behavior and causes the view to use only the
7394     * explicitly set pivotX and pivotY values.
7395     *
7396     * @param pivotY The y location of the pivot point.
7397     * @see #getRotation()
7398     * @see #getScaleX()
7399     * @see #getScaleY()
7400     * @see #getPivotY()
7401     *
7402     * @attr ref android.R.styleable#View_transformPivotY
7403     */
7404    public void setPivotY(float pivotY) {
7405        ensureTransformationInfo();
7406        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7407        final TransformationInfo info = mTransformationInfo;
7408        if (info.mPivotY != pivotY) {
7409            invalidateParentCaches();
7410            // Double-invalidation is necessary to capture view's old and new areas
7411            invalidate(false);
7412            info.mPivotY = pivotY;
7413            info.mMatrixDirty = true;
7414            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7415            invalidate(false);
7416        }
7417    }
7418
7419    /**
7420     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7421     * completely transparent and 1 means the view is completely opaque.
7422     *
7423     * <p>By default this is 1.0f.
7424     * @return The opacity of the view.
7425     */
7426    public float getAlpha() {
7427        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7428    }
7429
7430    /**
7431     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7432     * completely transparent and 1 means the view is completely opaque.</p>
7433     *
7434     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7435     * responsible for applying the opacity itself. Otherwise, calling this method is
7436     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7437     * setting a hardware layer.</p>
7438     *
7439     * @param alpha The opacity of the view.
7440     *
7441     * @see #setLayerType(int, android.graphics.Paint)
7442     *
7443     * @attr ref android.R.styleable#View_alpha
7444     */
7445    public void setAlpha(float alpha) {
7446        ensureTransformationInfo();
7447        mTransformationInfo.mAlpha = alpha;
7448        invalidateParentCaches();
7449        if (onSetAlpha((int) (alpha * 255))) {
7450            mPrivateFlags |= ALPHA_SET;
7451            // subclass is handling alpha - don't optimize rendering cache invalidation
7452            invalidate(true);
7453        } else {
7454            mPrivateFlags &= ~ALPHA_SET;
7455            invalidate(false);
7456        }
7457    }
7458
7459    /**
7460     * Faster version of setAlpha() which performs the same steps except there are
7461     * no calls to invalidate(). The caller of this function should perform proper invalidation
7462     * on the parent and this object. The return value indicates whether the subclass handles
7463     * alpha (the return value for onSetAlpha()).
7464     *
7465     * @param alpha The new value for the alpha property
7466     * @return true if the View subclass handles alpha (the return value for onSetAlpha())
7467     */
7468    boolean setAlphaNoInvalidation(float alpha) {
7469        ensureTransformationInfo();
7470        mTransformationInfo.mAlpha = alpha;
7471        boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7472        if (subclassHandlesAlpha) {
7473            mPrivateFlags |= ALPHA_SET;
7474        } else {
7475            mPrivateFlags &= ~ALPHA_SET;
7476        }
7477        return subclassHandlesAlpha;
7478    }
7479
7480    /**
7481     * Top position of this view relative to its parent.
7482     *
7483     * @return The top of this view, in pixels.
7484     */
7485    @ViewDebug.CapturedViewProperty
7486    public final int getTop() {
7487        return mTop;
7488    }
7489
7490    /**
7491     * Sets the top position of this view relative to its parent. This method is meant to be called
7492     * by the layout system and should not generally be called otherwise, because the property
7493     * may be changed at any time by the layout.
7494     *
7495     * @param top The top of this view, in pixels.
7496     */
7497    public final void setTop(int top) {
7498        if (top != mTop) {
7499            updateMatrix();
7500            final boolean matrixIsIdentity = mTransformationInfo == null
7501                    || mTransformationInfo.mMatrixIsIdentity;
7502            if (matrixIsIdentity) {
7503                if (mAttachInfo != null) {
7504                    int minTop;
7505                    int yLoc;
7506                    if (top < mTop) {
7507                        minTop = top;
7508                        yLoc = top - mTop;
7509                    } else {
7510                        minTop = mTop;
7511                        yLoc = 0;
7512                    }
7513                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7514                }
7515            } else {
7516                // Double-invalidation is necessary to capture view's old and new areas
7517                invalidate(true);
7518            }
7519
7520            int width = mRight - mLeft;
7521            int oldHeight = mBottom - mTop;
7522
7523            mTop = top;
7524
7525            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7526
7527            if (!matrixIsIdentity) {
7528                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7529                    // A change in dimension means an auto-centered pivot point changes, too
7530                    mTransformationInfo.mMatrixDirty = true;
7531                }
7532                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7533                invalidate(true);
7534            }
7535            mBackgroundSizeChanged = true;
7536            invalidateParentIfNeeded();
7537        }
7538    }
7539
7540    /**
7541     * Bottom position of this view relative to its parent.
7542     *
7543     * @return The bottom of this view, in pixels.
7544     */
7545    @ViewDebug.CapturedViewProperty
7546    public final int getBottom() {
7547        return mBottom;
7548    }
7549
7550    /**
7551     * True if this view has changed since the last time being drawn.
7552     *
7553     * @return The dirty state of this view.
7554     */
7555    public boolean isDirty() {
7556        return (mPrivateFlags & DIRTY_MASK) != 0;
7557    }
7558
7559    /**
7560     * Sets the bottom position of this view relative to its parent. This method is meant to be
7561     * called by the layout system and should not generally be called otherwise, because the
7562     * property may be changed at any time by the layout.
7563     *
7564     * @param bottom The bottom of this view, in pixels.
7565     */
7566    public final void setBottom(int bottom) {
7567        if (bottom != mBottom) {
7568            updateMatrix();
7569            final boolean matrixIsIdentity = mTransformationInfo == null
7570                    || mTransformationInfo.mMatrixIsIdentity;
7571            if (matrixIsIdentity) {
7572                if (mAttachInfo != null) {
7573                    int maxBottom;
7574                    if (bottom < mBottom) {
7575                        maxBottom = mBottom;
7576                    } else {
7577                        maxBottom = bottom;
7578                    }
7579                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7580                }
7581            } else {
7582                // Double-invalidation is necessary to capture view's old and new areas
7583                invalidate(true);
7584            }
7585
7586            int width = mRight - mLeft;
7587            int oldHeight = mBottom - mTop;
7588
7589            mBottom = bottom;
7590
7591            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7592
7593            if (!matrixIsIdentity) {
7594                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7595                    // A change in dimension means an auto-centered pivot point changes, too
7596                    mTransformationInfo.mMatrixDirty = true;
7597                }
7598                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7599                invalidate(true);
7600            }
7601            mBackgroundSizeChanged = true;
7602            invalidateParentIfNeeded();
7603        }
7604    }
7605
7606    /**
7607     * Left position of this view relative to its parent.
7608     *
7609     * @return The left edge of this view, in pixels.
7610     */
7611    @ViewDebug.CapturedViewProperty
7612    public final int getLeft() {
7613        return mLeft;
7614    }
7615
7616    /**
7617     * Sets the left position of this view relative to its parent. This method is meant to be called
7618     * by the layout system and should not generally be called otherwise, because the property
7619     * may be changed at any time by the layout.
7620     *
7621     * @param left The bottom of this view, in pixels.
7622     */
7623    public final void setLeft(int left) {
7624        if (left != mLeft) {
7625            updateMatrix();
7626            final boolean matrixIsIdentity = mTransformationInfo == null
7627                    || mTransformationInfo.mMatrixIsIdentity;
7628            if (matrixIsIdentity) {
7629                if (mAttachInfo != null) {
7630                    int minLeft;
7631                    int xLoc;
7632                    if (left < mLeft) {
7633                        minLeft = left;
7634                        xLoc = left - mLeft;
7635                    } else {
7636                        minLeft = mLeft;
7637                        xLoc = 0;
7638                    }
7639                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7640                }
7641            } else {
7642                // Double-invalidation is necessary to capture view's old and new areas
7643                invalidate(true);
7644            }
7645
7646            int oldWidth = mRight - mLeft;
7647            int height = mBottom - mTop;
7648
7649            mLeft = left;
7650
7651            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7652
7653            if (!matrixIsIdentity) {
7654                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7655                    // A change in dimension means an auto-centered pivot point changes, too
7656                    mTransformationInfo.mMatrixDirty = true;
7657                }
7658                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7659                invalidate(true);
7660            }
7661            mBackgroundSizeChanged = true;
7662            invalidateParentIfNeeded();
7663        }
7664    }
7665
7666    /**
7667     * Right position of this view relative to its parent.
7668     *
7669     * @return The right edge of this view, in pixels.
7670     */
7671    @ViewDebug.CapturedViewProperty
7672    public final int getRight() {
7673        return mRight;
7674    }
7675
7676    /**
7677     * Sets the right position of this view relative to its parent. This method is meant to be called
7678     * by the layout system and should not generally be called otherwise, because the property
7679     * may be changed at any time by the layout.
7680     *
7681     * @param right The bottom of this view, in pixels.
7682     */
7683    public final void setRight(int right) {
7684        if (right != mRight) {
7685            updateMatrix();
7686            final boolean matrixIsIdentity = mTransformationInfo == null
7687                    || mTransformationInfo.mMatrixIsIdentity;
7688            if (matrixIsIdentity) {
7689                if (mAttachInfo != null) {
7690                    int maxRight;
7691                    if (right < mRight) {
7692                        maxRight = mRight;
7693                    } else {
7694                        maxRight = right;
7695                    }
7696                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7697                }
7698            } else {
7699                // Double-invalidation is necessary to capture view's old and new areas
7700                invalidate(true);
7701            }
7702
7703            int oldWidth = mRight - mLeft;
7704            int height = mBottom - mTop;
7705
7706            mRight = right;
7707
7708            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7709
7710            if (!matrixIsIdentity) {
7711                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7712                    // A change in dimension means an auto-centered pivot point changes, too
7713                    mTransformationInfo.mMatrixDirty = true;
7714                }
7715                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7716                invalidate(true);
7717            }
7718            mBackgroundSizeChanged = true;
7719            invalidateParentIfNeeded();
7720        }
7721    }
7722
7723    /**
7724     * The visual x position of this view, in pixels. This is equivalent to the
7725     * {@link #setTranslationX(float) translationX} property plus the current
7726     * {@link #getLeft() left} property.
7727     *
7728     * @return The visual x position of this view, in pixels.
7729     */
7730    public float getX() {
7731        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
7732    }
7733
7734    /**
7735     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7736     * {@link #setTranslationX(float) translationX} property to be the difference between
7737     * the x value passed in and the current {@link #getLeft() left} property.
7738     *
7739     * @param x The visual x position of this view, in pixels.
7740     */
7741    public void setX(float x) {
7742        setTranslationX(x - mLeft);
7743    }
7744
7745    /**
7746     * The visual y position of this view, in pixels. This is equivalent to the
7747     * {@link #setTranslationY(float) translationY} property plus the current
7748     * {@link #getTop() top} property.
7749     *
7750     * @return The visual y position of this view, in pixels.
7751     */
7752    public float getY() {
7753        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
7754    }
7755
7756    /**
7757     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7758     * {@link #setTranslationY(float) translationY} property to be the difference between
7759     * the y value passed in and the current {@link #getTop() top} property.
7760     *
7761     * @param y The visual y position of this view, in pixels.
7762     */
7763    public void setY(float y) {
7764        setTranslationY(y - mTop);
7765    }
7766
7767
7768    /**
7769     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7770     * This position is post-layout, in addition to wherever the object's
7771     * layout placed it.
7772     *
7773     * @return The horizontal position of this view relative to its left position, in pixels.
7774     */
7775    public float getTranslationX() {
7776        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
7777    }
7778
7779    /**
7780     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7781     * This effectively positions the object post-layout, in addition to wherever the object's
7782     * layout placed it.
7783     *
7784     * @param translationX The horizontal position of this view relative to its left position,
7785     * in pixels.
7786     *
7787     * @attr ref android.R.styleable#View_translationX
7788     */
7789    public void setTranslationX(float translationX) {
7790        ensureTransformationInfo();
7791        final TransformationInfo info = mTransformationInfo;
7792        if (info.mTranslationX != translationX) {
7793            invalidateParentCaches();
7794            // Double-invalidation is necessary to capture view's old and new areas
7795            invalidate(false);
7796            info.mTranslationX = translationX;
7797            info.mMatrixDirty = true;
7798            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7799            invalidate(false);
7800        }
7801    }
7802
7803    /**
7804     * The horizontal location of this view relative to its {@link #getTop() top} position.
7805     * This position is post-layout, in addition to wherever the object's
7806     * layout placed it.
7807     *
7808     * @return The vertical position of this view relative to its top position,
7809     * in pixels.
7810     */
7811    public float getTranslationY() {
7812        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
7813    }
7814
7815    /**
7816     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7817     * This effectively positions the object post-layout, in addition to wherever the object's
7818     * layout placed it.
7819     *
7820     * @param translationY The vertical position of this view relative to its top position,
7821     * in pixels.
7822     *
7823     * @attr ref android.R.styleable#View_translationY
7824     */
7825    public void setTranslationY(float translationY) {
7826        ensureTransformationInfo();
7827        final TransformationInfo info = mTransformationInfo;
7828        if (info.mTranslationY != translationY) {
7829            invalidateParentCaches();
7830            // Double-invalidation is necessary to capture view's old and new areas
7831            invalidate(false);
7832            info.mTranslationY = translationY;
7833            info.mMatrixDirty = true;
7834            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7835            invalidate(false);
7836        }
7837    }
7838
7839    /**
7840     * @hide
7841     */
7842    public void setFastTranslationX(float x) {
7843        ensureTransformationInfo();
7844        final TransformationInfo info = mTransformationInfo;
7845        info.mTranslationX = x;
7846        info.mMatrixDirty = true;
7847    }
7848
7849    /**
7850     * @hide
7851     */
7852    public void setFastTranslationY(float y) {
7853        ensureTransformationInfo();
7854        final TransformationInfo info = mTransformationInfo;
7855        info.mTranslationY = y;
7856        info.mMatrixDirty = true;
7857    }
7858
7859    /**
7860     * @hide
7861     */
7862    public void setFastX(float x) {
7863        ensureTransformationInfo();
7864        final TransformationInfo info = mTransformationInfo;
7865        info.mTranslationX = x - mLeft;
7866        info.mMatrixDirty = true;
7867    }
7868
7869    /**
7870     * @hide
7871     */
7872    public void setFastY(float y) {
7873        ensureTransformationInfo();
7874        final TransformationInfo info = mTransformationInfo;
7875        info.mTranslationY = y - mTop;
7876        info.mMatrixDirty = true;
7877    }
7878
7879    /**
7880     * @hide
7881     */
7882    public void setFastScaleX(float x) {
7883        ensureTransformationInfo();
7884        final TransformationInfo info = mTransformationInfo;
7885        info.mScaleX = x;
7886        info.mMatrixDirty = true;
7887    }
7888
7889    /**
7890     * @hide
7891     */
7892    public void setFastScaleY(float y) {
7893        ensureTransformationInfo();
7894        final TransformationInfo info = mTransformationInfo;
7895        info.mScaleY = y;
7896        info.mMatrixDirty = true;
7897    }
7898
7899    /**
7900     * @hide
7901     */
7902    public void setFastAlpha(float alpha) {
7903        ensureTransformationInfo();
7904        mTransformationInfo.mAlpha = alpha;
7905    }
7906
7907    /**
7908     * @hide
7909     */
7910    public void setFastRotationY(float y) {
7911        ensureTransformationInfo();
7912        final TransformationInfo info = mTransformationInfo;
7913        info.mRotationY = y;
7914        info.mMatrixDirty = true;
7915    }
7916
7917    /**
7918     * Hit rectangle in parent's coordinates
7919     *
7920     * @param outRect The hit rectangle of the view.
7921     */
7922    public void getHitRect(Rect outRect) {
7923        updateMatrix();
7924        final TransformationInfo info = mTransformationInfo;
7925        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
7926            outRect.set(mLeft, mTop, mRight, mBottom);
7927        } else {
7928            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
7929            tmpRect.set(-info.mPivotX, -info.mPivotY,
7930                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
7931            info.mMatrix.mapRect(tmpRect);
7932            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
7933                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
7934        }
7935    }
7936
7937    /**
7938     * Determines whether the given point, in local coordinates is inside the view.
7939     */
7940    /*package*/ final boolean pointInView(float localX, float localY) {
7941        return localX >= 0 && localX < (mRight - mLeft)
7942                && localY >= 0 && localY < (mBottom - mTop);
7943    }
7944
7945    /**
7946     * Utility method to determine whether the given point, in local coordinates,
7947     * is inside the view, where the area of the view is expanded by the slop factor.
7948     * This method is called while processing touch-move events to determine if the event
7949     * is still within the view.
7950     */
7951    private boolean pointInView(float localX, float localY, float slop) {
7952        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
7953                localY < ((mBottom - mTop) + slop);
7954    }
7955
7956    /**
7957     * When a view has focus and the user navigates away from it, the next view is searched for
7958     * starting from the rectangle filled in by this method.
7959     *
7960     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
7961     * of the view.  However, if your view maintains some idea of internal selection,
7962     * such as a cursor, or a selected row or column, you should override this method and
7963     * fill in a more specific rectangle.
7964     *
7965     * @param r The rectangle to fill in, in this view's coordinates.
7966     */
7967    public void getFocusedRect(Rect r) {
7968        getDrawingRect(r);
7969    }
7970
7971    /**
7972     * If some part of this view is not clipped by any of its parents, then
7973     * return that area in r in global (root) coordinates. To convert r to local
7974     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
7975     * -globalOffset.y)) If the view is completely clipped or translated out,
7976     * return false.
7977     *
7978     * @param r If true is returned, r holds the global coordinates of the
7979     *        visible portion of this view.
7980     * @param globalOffset If true is returned, globalOffset holds the dx,dy
7981     *        between this view and its root. globalOffet may be null.
7982     * @return true if r is non-empty (i.e. part of the view is visible at the
7983     *         root level.
7984     */
7985    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
7986        int width = mRight - mLeft;
7987        int height = mBottom - mTop;
7988        if (width > 0 && height > 0) {
7989            r.set(0, 0, width, height);
7990            if (globalOffset != null) {
7991                globalOffset.set(-mScrollX, -mScrollY);
7992            }
7993            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
7994        }
7995        return false;
7996    }
7997
7998    public final boolean getGlobalVisibleRect(Rect r) {
7999        return getGlobalVisibleRect(r, null);
8000    }
8001
8002    public final boolean getLocalVisibleRect(Rect r) {
8003        Point offset = new Point();
8004        if (getGlobalVisibleRect(r, offset)) {
8005            r.offset(-offset.x, -offset.y); // make r local
8006            return true;
8007        }
8008        return false;
8009    }
8010
8011    /**
8012     * Offset this view's vertical location by the specified number of pixels.
8013     *
8014     * @param offset the number of pixels to offset the view by
8015     */
8016    public void offsetTopAndBottom(int offset) {
8017        if (offset != 0) {
8018            updateMatrix();
8019            final boolean matrixIsIdentity = mTransformationInfo == null
8020                    || mTransformationInfo.mMatrixIsIdentity;
8021            if (matrixIsIdentity) {
8022                final ViewParent p = mParent;
8023                if (p != null && mAttachInfo != null) {
8024                    final Rect r = mAttachInfo.mTmpInvalRect;
8025                    int minTop;
8026                    int maxBottom;
8027                    int yLoc;
8028                    if (offset < 0) {
8029                        minTop = mTop + offset;
8030                        maxBottom = mBottom;
8031                        yLoc = offset;
8032                    } else {
8033                        minTop = mTop;
8034                        maxBottom = mBottom + offset;
8035                        yLoc = 0;
8036                    }
8037                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8038                    p.invalidateChild(this, r);
8039                }
8040            } else {
8041                invalidate(false);
8042            }
8043
8044            mTop += offset;
8045            mBottom += offset;
8046
8047            if (!matrixIsIdentity) {
8048                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8049                invalidate(false);
8050            }
8051            invalidateParentIfNeeded();
8052        }
8053    }
8054
8055    /**
8056     * Offset this view's horizontal location by the specified amount of pixels.
8057     *
8058     * @param offset the numer of pixels to offset the view by
8059     */
8060    public void offsetLeftAndRight(int offset) {
8061        if (offset != 0) {
8062            updateMatrix();
8063            final boolean matrixIsIdentity = mTransformationInfo == null
8064                    || mTransformationInfo.mMatrixIsIdentity;
8065            if (matrixIsIdentity) {
8066                final ViewParent p = mParent;
8067                if (p != null && mAttachInfo != null) {
8068                    final Rect r = mAttachInfo.mTmpInvalRect;
8069                    int minLeft;
8070                    int maxRight;
8071                    if (offset < 0) {
8072                        minLeft = mLeft + offset;
8073                        maxRight = mRight;
8074                    } else {
8075                        minLeft = mLeft;
8076                        maxRight = mRight + offset;
8077                    }
8078                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8079                    p.invalidateChild(this, r);
8080                }
8081            } else {
8082                invalidate(false);
8083            }
8084
8085            mLeft += offset;
8086            mRight += offset;
8087
8088            if (!matrixIsIdentity) {
8089                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8090                invalidate(false);
8091            }
8092            invalidateParentIfNeeded();
8093        }
8094    }
8095
8096    /**
8097     * Get the LayoutParams associated with this view. All views should have
8098     * layout parameters. These supply parameters to the <i>parent</i> of this
8099     * view specifying how it should be arranged. There are many subclasses of
8100     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8101     * of ViewGroup that are responsible for arranging their children.
8102     *
8103     * This method may return null if this View is not attached to a parent
8104     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8105     * was not invoked successfully. When a View is attached to a parent
8106     * ViewGroup, this method must not return null.
8107     *
8108     * @return The LayoutParams associated with this view, or null if no
8109     *         parameters have been set yet
8110     */
8111    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8112    public ViewGroup.LayoutParams getLayoutParams() {
8113        return mLayoutParams;
8114    }
8115
8116    /**
8117     * Set the layout parameters associated with this view. These supply
8118     * parameters to the <i>parent</i> of this view specifying how it should be
8119     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8120     * correspond to the different subclasses of ViewGroup that are responsible
8121     * for arranging their children.
8122     *
8123     * @param params The layout parameters for this view, cannot be null
8124     */
8125    public void setLayoutParams(ViewGroup.LayoutParams params) {
8126        if (params == null) {
8127            throw new NullPointerException("Layout parameters cannot be null");
8128        }
8129        mLayoutParams = params;
8130        requestLayout();
8131    }
8132
8133    /**
8134     * Set the scrolled position of your view. This will cause a call to
8135     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8136     * invalidated.
8137     * @param x the x position to scroll to
8138     * @param y the y position to scroll to
8139     */
8140    public void scrollTo(int x, int y) {
8141        if (mScrollX != x || mScrollY != y) {
8142            int oldX = mScrollX;
8143            int oldY = mScrollY;
8144            mScrollX = x;
8145            mScrollY = y;
8146            invalidateParentCaches();
8147            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8148            if (!awakenScrollBars()) {
8149                invalidate(true);
8150            }
8151        }
8152    }
8153
8154    /**
8155     * Move the scrolled position of your view. This will cause a call to
8156     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8157     * invalidated.
8158     * @param x the amount of pixels to scroll by horizontally
8159     * @param y the amount of pixels to scroll by vertically
8160     */
8161    public void scrollBy(int x, int y) {
8162        scrollTo(mScrollX + x, mScrollY + y);
8163    }
8164
8165    /**
8166     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8167     * animation to fade the scrollbars out after a default delay. If a subclass
8168     * provides animated scrolling, the start delay should equal the duration
8169     * of the scrolling animation.</p>
8170     *
8171     * <p>The animation starts only if at least one of the scrollbars is
8172     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8173     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8174     * this method returns true, and false otherwise. If the animation is
8175     * started, this method calls {@link #invalidate()}; in that case the
8176     * caller should not call {@link #invalidate()}.</p>
8177     *
8178     * <p>This method should be invoked every time a subclass directly updates
8179     * the scroll parameters.</p>
8180     *
8181     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8182     * and {@link #scrollTo(int, int)}.</p>
8183     *
8184     * @return true if the animation is played, false otherwise
8185     *
8186     * @see #awakenScrollBars(int)
8187     * @see #scrollBy(int, int)
8188     * @see #scrollTo(int, int)
8189     * @see #isHorizontalScrollBarEnabled()
8190     * @see #isVerticalScrollBarEnabled()
8191     * @see #setHorizontalScrollBarEnabled(boolean)
8192     * @see #setVerticalScrollBarEnabled(boolean)
8193     */
8194    protected boolean awakenScrollBars() {
8195        return mScrollCache != null &&
8196                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8197    }
8198
8199    /**
8200     * Trigger the scrollbars to draw.
8201     * This method differs from awakenScrollBars() only in its default duration.
8202     * initialAwakenScrollBars() will show the scroll bars for longer than
8203     * usual to give the user more of a chance to notice them.
8204     *
8205     * @return true if the animation is played, false otherwise.
8206     */
8207    private boolean initialAwakenScrollBars() {
8208        return mScrollCache != null &&
8209                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8210    }
8211
8212    /**
8213     * <p>
8214     * Trigger the scrollbars to draw. When invoked this method starts an
8215     * animation to fade the scrollbars out after a fixed delay. If a subclass
8216     * provides animated scrolling, the start delay should equal the duration of
8217     * the scrolling animation.
8218     * </p>
8219     *
8220     * <p>
8221     * The animation starts only if at least one of the scrollbars is enabled,
8222     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8223     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8224     * this method returns true, and false otherwise. If the animation is
8225     * started, this method calls {@link #invalidate()}; in that case the caller
8226     * should not call {@link #invalidate()}.
8227     * </p>
8228     *
8229     * <p>
8230     * This method should be invoked everytime a subclass directly updates the
8231     * scroll parameters.
8232     * </p>
8233     *
8234     * @param startDelay the delay, in milliseconds, after which the animation
8235     *        should start; when the delay is 0, the animation starts
8236     *        immediately
8237     * @return true if the animation is played, false otherwise
8238     *
8239     * @see #scrollBy(int, int)
8240     * @see #scrollTo(int, int)
8241     * @see #isHorizontalScrollBarEnabled()
8242     * @see #isVerticalScrollBarEnabled()
8243     * @see #setHorizontalScrollBarEnabled(boolean)
8244     * @see #setVerticalScrollBarEnabled(boolean)
8245     */
8246    protected boolean awakenScrollBars(int startDelay) {
8247        return awakenScrollBars(startDelay, true);
8248    }
8249
8250    /**
8251     * <p>
8252     * Trigger the scrollbars to draw. When invoked this method starts an
8253     * animation to fade the scrollbars out after a fixed delay. If a subclass
8254     * provides animated scrolling, the start delay should equal the duration of
8255     * the scrolling animation.
8256     * </p>
8257     *
8258     * <p>
8259     * The animation starts only if at least one of the scrollbars is enabled,
8260     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8261     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8262     * this method returns true, and false otherwise. If the animation is
8263     * started, this method calls {@link #invalidate()} if the invalidate parameter
8264     * is set to true; in that case the caller
8265     * should not call {@link #invalidate()}.
8266     * </p>
8267     *
8268     * <p>
8269     * This method should be invoked everytime a subclass directly updates the
8270     * scroll parameters.
8271     * </p>
8272     *
8273     * @param startDelay the delay, in milliseconds, after which the animation
8274     *        should start; when the delay is 0, the animation starts
8275     *        immediately
8276     *
8277     * @param invalidate Wheter this method should call invalidate
8278     *
8279     * @return true if the animation is played, false otherwise
8280     *
8281     * @see #scrollBy(int, int)
8282     * @see #scrollTo(int, int)
8283     * @see #isHorizontalScrollBarEnabled()
8284     * @see #isVerticalScrollBarEnabled()
8285     * @see #setHorizontalScrollBarEnabled(boolean)
8286     * @see #setVerticalScrollBarEnabled(boolean)
8287     */
8288    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8289        final ScrollabilityCache scrollCache = mScrollCache;
8290
8291        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8292            return false;
8293        }
8294
8295        if (scrollCache.scrollBar == null) {
8296            scrollCache.scrollBar = new ScrollBarDrawable();
8297        }
8298
8299        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8300
8301            if (invalidate) {
8302                // Invalidate to show the scrollbars
8303                invalidate(true);
8304            }
8305
8306            if (scrollCache.state == ScrollabilityCache.OFF) {
8307                // FIXME: this is copied from WindowManagerService.
8308                // We should get this value from the system when it
8309                // is possible to do so.
8310                final int KEY_REPEAT_FIRST_DELAY = 750;
8311                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8312            }
8313
8314            // Tell mScrollCache when we should start fading. This may
8315            // extend the fade start time if one was already scheduled
8316            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8317            scrollCache.fadeStartTime = fadeStartTime;
8318            scrollCache.state = ScrollabilityCache.ON;
8319
8320            // Schedule our fader to run, unscheduling any old ones first
8321            if (mAttachInfo != null) {
8322                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8323                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8324            }
8325
8326            return true;
8327        }
8328
8329        return false;
8330    }
8331
8332    /**
8333     * Do not invalidate views which are not visible and which are not running an animation. They
8334     * will not get drawn and they should not set dirty flags as if they will be drawn
8335     */
8336    private boolean skipInvalidate() {
8337        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8338                (!(mParent instanceof ViewGroup) ||
8339                        !((ViewGroup) mParent).isViewTransitioning(this));
8340    }
8341    /**
8342     * Mark the the area defined by dirty as needing to be drawn. If the view is
8343     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8344     * in the future. This must be called from a UI thread. To call from a non-UI
8345     * thread, call {@link #postInvalidate()}.
8346     *
8347     * WARNING: This method is destructive to dirty.
8348     * @param dirty the rectangle representing the bounds of the dirty region
8349     */
8350    public void invalidate(Rect dirty) {
8351        if (ViewDebug.TRACE_HIERARCHY) {
8352            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8353        }
8354
8355        if (skipInvalidate()) {
8356            return;
8357        }
8358        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8359                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8360                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8361            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8362            mPrivateFlags |= INVALIDATED;
8363            mPrivateFlags |= DIRTY;
8364            final ViewParent p = mParent;
8365            final AttachInfo ai = mAttachInfo;
8366            //noinspection PointlessBooleanExpression,ConstantConditions
8367            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8368                if (p != null && ai != null && ai.mHardwareAccelerated) {
8369                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8370                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8371                    p.invalidateChild(this, null);
8372                    return;
8373                }
8374            }
8375            if (p != null && ai != null) {
8376                final int scrollX = mScrollX;
8377                final int scrollY = mScrollY;
8378                final Rect r = ai.mTmpInvalRect;
8379                r.set(dirty.left - scrollX, dirty.top - scrollY,
8380                        dirty.right - scrollX, dirty.bottom - scrollY);
8381                mParent.invalidateChild(this, r);
8382            }
8383        }
8384    }
8385
8386    /**
8387     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
8388     * The coordinates of the dirty rect are relative to the view.
8389     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8390     * will be called at some point in the future. This must be called from
8391     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8392     * @param l the left position of the dirty region
8393     * @param t the top position of the dirty region
8394     * @param r the right position of the dirty region
8395     * @param b the bottom position of the dirty region
8396     */
8397    public void invalidate(int l, int t, int r, int b) {
8398        if (ViewDebug.TRACE_HIERARCHY) {
8399            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8400        }
8401
8402        if (skipInvalidate()) {
8403            return;
8404        }
8405        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8406                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8407                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8408            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8409            mPrivateFlags |= INVALIDATED;
8410            mPrivateFlags |= DIRTY;
8411            final ViewParent p = mParent;
8412            final AttachInfo ai = mAttachInfo;
8413            //noinspection PointlessBooleanExpression,ConstantConditions
8414            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8415                if (p != null && ai != null && ai.mHardwareAccelerated) {
8416                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8417                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8418                    p.invalidateChild(this, null);
8419                    return;
8420                }
8421            }
8422            if (p != null && ai != null && l < r && t < b) {
8423                final int scrollX = mScrollX;
8424                final int scrollY = mScrollY;
8425                final Rect tmpr = ai.mTmpInvalRect;
8426                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8427                p.invalidateChild(this, tmpr);
8428            }
8429        }
8430    }
8431
8432    /**
8433     * Invalidate the whole view. If the view is visible,
8434     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8435     * the future. This must be called from a UI thread. To call from a non-UI thread,
8436     * call {@link #postInvalidate()}.
8437     */
8438    public void invalidate() {
8439        invalidate(true);
8440    }
8441
8442    /**
8443     * This is where the invalidate() work actually happens. A full invalidate()
8444     * causes the drawing cache to be invalidated, but this function can be called with
8445     * invalidateCache set to false to skip that invalidation step for cases that do not
8446     * need it (for example, a component that remains at the same dimensions with the same
8447     * content).
8448     *
8449     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8450     * well. This is usually true for a full invalidate, but may be set to false if the
8451     * View's contents or dimensions have not changed.
8452     */
8453    void invalidate(boolean invalidateCache) {
8454        if (ViewDebug.TRACE_HIERARCHY) {
8455            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8456        }
8457
8458        if (skipInvalidate()) {
8459            return;
8460        }
8461        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8462                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8463                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8464            mLastIsOpaque = isOpaque();
8465            mPrivateFlags &= ~DRAWN;
8466            mPrivateFlags |= DIRTY;
8467            if (invalidateCache) {
8468                mPrivateFlags |= INVALIDATED;
8469                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8470            }
8471            final AttachInfo ai = mAttachInfo;
8472            final ViewParent p = mParent;
8473            //noinspection PointlessBooleanExpression,ConstantConditions
8474            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8475                if (p != null && ai != null && ai.mHardwareAccelerated) {
8476                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8477                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8478                    p.invalidateChild(this, null);
8479                    return;
8480                }
8481            }
8482
8483            if (p != null && ai != null) {
8484                final Rect r = ai.mTmpInvalRect;
8485                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8486                // Don't call invalidate -- we don't want to internally scroll
8487                // our own bounds
8488                p.invalidateChild(this, r);
8489            }
8490        }
8491    }
8492
8493    /**
8494     * @hide
8495     */
8496    public void fastInvalidate() {
8497        if (skipInvalidate()) {
8498            return;
8499        }
8500        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8501            (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8502            (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8503            if (mParent instanceof View) {
8504                ((View) mParent).mPrivateFlags |= INVALIDATED;
8505            }
8506            mPrivateFlags &= ~DRAWN;
8507            mPrivateFlags |= DIRTY;
8508            mPrivateFlags |= INVALIDATED;
8509            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8510            if (mParent != null && mAttachInfo != null) {
8511                if (mAttachInfo.mHardwareAccelerated) {
8512                    mParent.invalidateChild(this, null);
8513                } else {
8514                    final Rect r = mAttachInfo.mTmpInvalRect;
8515                    r.set(0, 0, mRight - mLeft, mBottom - mTop);
8516                    // Don't call invalidate -- we don't want to internally scroll
8517                    // our own bounds
8518                    mParent.invalidateChild(this, r);
8519                }
8520            }
8521        }
8522    }
8523
8524    /**
8525     * Used to indicate that the parent of this view should clear its caches. This functionality
8526     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8527     * which is necessary when various parent-managed properties of the view change, such as
8528     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8529     * clears the parent caches and does not causes an invalidate event.
8530     *
8531     * @hide
8532     */
8533    protected void invalidateParentCaches() {
8534        if (mParent instanceof View) {
8535            ((View) mParent).mPrivateFlags |= INVALIDATED;
8536        }
8537    }
8538
8539    /**
8540     * Used to indicate that the parent of this view should be invalidated. This functionality
8541     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8542     * which is necessary when various parent-managed properties of the view change, such as
8543     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8544     * an invalidation event to the parent.
8545     *
8546     * @hide
8547     */
8548    protected void invalidateParentIfNeeded() {
8549        if (isHardwareAccelerated() && mParent instanceof View) {
8550            ((View) mParent).invalidate(true);
8551        }
8552    }
8553
8554    /**
8555     * Indicates whether this View is opaque. An opaque View guarantees that it will
8556     * draw all the pixels overlapping its bounds using a fully opaque color.
8557     *
8558     * Subclasses of View should override this method whenever possible to indicate
8559     * whether an instance is opaque. Opaque Views are treated in a special way by
8560     * the View hierarchy, possibly allowing it to perform optimizations during
8561     * invalidate/draw passes.
8562     *
8563     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8564     */
8565    @ViewDebug.ExportedProperty(category = "drawing")
8566    public boolean isOpaque() {
8567        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8568                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8569                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8570    }
8571
8572    /**
8573     * @hide
8574     */
8575    protected void computeOpaqueFlags() {
8576        // Opaque if:
8577        //   - Has a background
8578        //   - Background is opaque
8579        //   - Doesn't have scrollbars or scrollbars are inside overlay
8580
8581        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8582            mPrivateFlags |= OPAQUE_BACKGROUND;
8583        } else {
8584            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8585        }
8586
8587        final int flags = mViewFlags;
8588        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8589                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8590            mPrivateFlags |= OPAQUE_SCROLLBARS;
8591        } else {
8592            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8593        }
8594    }
8595
8596    /**
8597     * @hide
8598     */
8599    protected boolean hasOpaqueScrollbars() {
8600        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8601    }
8602
8603    /**
8604     * @return A handler associated with the thread running the View. This
8605     * handler can be used to pump events in the UI events queue.
8606     */
8607    public Handler getHandler() {
8608        if (mAttachInfo != null) {
8609            return mAttachInfo.mHandler;
8610        }
8611        return null;
8612    }
8613
8614    /**
8615     * <p>Causes the Runnable to be added to the message queue.
8616     * The runnable will be run on the user interface thread.</p>
8617     *
8618     * <p>This method can be invoked from outside of the UI thread
8619     * only when this View is attached to a window.</p>
8620     *
8621     * @param action The Runnable that will be executed.
8622     *
8623     * @return Returns true if the Runnable was successfully placed in to the
8624     *         message queue.  Returns false on failure, usually because the
8625     *         looper processing the message queue is exiting.
8626     */
8627    public boolean post(Runnable action) {
8628        Handler handler;
8629        AttachInfo attachInfo = mAttachInfo;
8630        if (attachInfo != null) {
8631            handler = attachInfo.mHandler;
8632        } else {
8633            // Assume that post will succeed later
8634            ViewRootImpl.getRunQueue().post(action);
8635            return true;
8636        }
8637
8638        return handler.post(action);
8639    }
8640
8641    /**
8642     * <p>Causes the Runnable to be added to the message queue, to be run
8643     * after the specified amount of time elapses.
8644     * The runnable will be run on the user interface thread.</p>
8645     *
8646     * <p>This method can be invoked from outside of the UI thread
8647     * only when this View is attached to a window.</p>
8648     *
8649     * @param action The Runnable that will be executed.
8650     * @param delayMillis The delay (in milliseconds) until the Runnable
8651     *        will be executed.
8652     *
8653     * @return true if the Runnable was successfully placed in to the
8654     *         message queue.  Returns false on failure, usually because the
8655     *         looper processing the message queue is exiting.  Note that a
8656     *         result of true does not mean the Runnable will be processed --
8657     *         if the looper is quit before the delivery time of the message
8658     *         occurs then the message will be dropped.
8659     */
8660    public boolean postDelayed(Runnable action, long delayMillis) {
8661        Handler handler;
8662        AttachInfo attachInfo = mAttachInfo;
8663        if (attachInfo != null) {
8664            handler = attachInfo.mHandler;
8665        } else {
8666            // Assume that post will succeed later
8667            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8668            return true;
8669        }
8670
8671        return handler.postDelayed(action, delayMillis);
8672    }
8673
8674    /**
8675     * <p>Removes the specified Runnable from the message queue.</p>
8676     *
8677     * <p>This method can be invoked from outside of the UI thread
8678     * only when this View is attached to a window.</p>
8679     *
8680     * @param action The Runnable to remove from the message handling queue
8681     *
8682     * @return true if this view could ask the Handler to remove the Runnable,
8683     *         false otherwise. When the returned value is true, the Runnable
8684     *         may or may not have been actually removed from the message queue
8685     *         (for instance, if the Runnable was not in the queue already.)
8686     */
8687    public boolean removeCallbacks(Runnable action) {
8688        Handler handler;
8689        AttachInfo attachInfo = mAttachInfo;
8690        if (attachInfo != null) {
8691            handler = attachInfo.mHandler;
8692        } else {
8693            // Assume that post will succeed later
8694            ViewRootImpl.getRunQueue().removeCallbacks(action);
8695            return true;
8696        }
8697
8698        handler.removeCallbacks(action);
8699        return true;
8700    }
8701
8702    /**
8703     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8704     * Use this to invalidate the View from a non-UI thread.</p>
8705     *
8706     * <p>This method can be invoked from outside of the UI thread
8707     * only when this View is attached to a window.</p>
8708     *
8709     * @see #invalidate()
8710     */
8711    public void postInvalidate() {
8712        postInvalidateDelayed(0);
8713    }
8714
8715    /**
8716     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8717     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8718     *
8719     * <p>This method can be invoked from outside of the UI thread
8720     * only when this View is attached to a window.</p>
8721     *
8722     * @param left The left coordinate of the rectangle to invalidate.
8723     * @param top The top coordinate of the rectangle to invalidate.
8724     * @param right The right coordinate of the rectangle to invalidate.
8725     * @param bottom The bottom coordinate of the rectangle to invalidate.
8726     *
8727     * @see #invalidate(int, int, int, int)
8728     * @see #invalidate(Rect)
8729     */
8730    public void postInvalidate(int left, int top, int right, int bottom) {
8731        postInvalidateDelayed(0, left, top, right, bottom);
8732    }
8733
8734    /**
8735     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8736     * loop. Waits for the specified amount of time.</p>
8737     *
8738     * <p>This method can be invoked from outside of the UI thread
8739     * only when this View is attached to a window.</p>
8740     *
8741     * @param delayMilliseconds the duration in milliseconds to delay the
8742     *         invalidation by
8743     */
8744    public void postInvalidateDelayed(long delayMilliseconds) {
8745        // We try only with the AttachInfo because there's no point in invalidating
8746        // if we are not attached to our window
8747        AttachInfo attachInfo = mAttachInfo;
8748        if (attachInfo != null) {
8749            Message msg = Message.obtain();
8750            msg.what = AttachInfo.INVALIDATE_MSG;
8751            msg.obj = this;
8752            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8753        }
8754    }
8755
8756    /**
8757     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8758     * through the event loop. Waits for the specified amount of time.</p>
8759     *
8760     * <p>This method can be invoked from outside of the UI thread
8761     * only when this View is attached to a window.</p>
8762     *
8763     * @param delayMilliseconds the duration in milliseconds to delay the
8764     *         invalidation by
8765     * @param left The left coordinate of the rectangle to invalidate.
8766     * @param top The top coordinate of the rectangle to invalidate.
8767     * @param right The right coordinate of the rectangle to invalidate.
8768     * @param bottom The bottom coordinate of the rectangle to invalidate.
8769     */
8770    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8771            int right, int bottom) {
8772
8773        // We try only with the AttachInfo because there's no point in invalidating
8774        // if we are not attached to our window
8775        AttachInfo attachInfo = mAttachInfo;
8776        if (attachInfo != null) {
8777            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8778            info.target = this;
8779            info.left = left;
8780            info.top = top;
8781            info.right = right;
8782            info.bottom = bottom;
8783
8784            final Message msg = Message.obtain();
8785            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8786            msg.obj = info;
8787            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8788        }
8789    }
8790
8791    /**
8792     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8793     * This event is sent at most once every
8794     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8795     */
8796    private void postSendViewScrolledAccessibilityEventCallback() {
8797        if (mSendViewScrolledAccessibilityEvent == null) {
8798            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8799        }
8800        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8801            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8802            postDelayed(mSendViewScrolledAccessibilityEvent,
8803                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8804        }
8805    }
8806
8807    /**
8808     * Called by a parent to request that a child update its values for mScrollX
8809     * and mScrollY if necessary. This will typically be done if the child is
8810     * animating a scroll using a {@link android.widget.Scroller Scroller}
8811     * object.
8812     */
8813    public void computeScroll() {
8814    }
8815
8816    /**
8817     * <p>Indicate whether the horizontal edges are faded when the view is
8818     * scrolled horizontally.</p>
8819     *
8820     * @return true if the horizontal edges should are faded on scroll, false
8821     *         otherwise
8822     *
8823     * @see #setHorizontalFadingEdgeEnabled(boolean)
8824     * @attr ref android.R.styleable#View_requiresFadingEdge
8825     */
8826    public boolean isHorizontalFadingEdgeEnabled() {
8827        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8828    }
8829
8830    /**
8831     * <p>Define whether the horizontal edges should be faded when this view
8832     * is scrolled horizontally.</p>
8833     *
8834     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8835     *                                    be faded when the view is scrolled
8836     *                                    horizontally
8837     *
8838     * @see #isHorizontalFadingEdgeEnabled()
8839     * @attr ref android.R.styleable#View_requiresFadingEdge
8840     */
8841    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8842        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8843            if (horizontalFadingEdgeEnabled) {
8844                initScrollCache();
8845            }
8846
8847            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8848        }
8849    }
8850
8851    /**
8852     * <p>Indicate whether the vertical edges are faded when the view is
8853     * scrolled horizontally.</p>
8854     *
8855     * @return true if the vertical edges should are faded on scroll, false
8856     *         otherwise
8857     *
8858     * @see #setVerticalFadingEdgeEnabled(boolean)
8859     * @attr ref android.R.styleable#View_requiresFadingEdge
8860     */
8861    public boolean isVerticalFadingEdgeEnabled() {
8862        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8863    }
8864
8865    /**
8866     * <p>Define whether the vertical edges should be faded when this view
8867     * is scrolled vertically.</p>
8868     *
8869     * @param verticalFadingEdgeEnabled true if the vertical edges should
8870     *                                  be faded when the view is scrolled
8871     *                                  vertically
8872     *
8873     * @see #isVerticalFadingEdgeEnabled()
8874     * @attr ref android.R.styleable#View_requiresFadingEdge
8875     */
8876    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8877        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8878            if (verticalFadingEdgeEnabled) {
8879                initScrollCache();
8880            }
8881
8882            mViewFlags ^= FADING_EDGE_VERTICAL;
8883        }
8884    }
8885
8886    /**
8887     * Returns the strength, or intensity, of the top faded edge. The strength is
8888     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8889     * returns 0.0 or 1.0 but no value in between.
8890     *
8891     * Subclasses should override this method to provide a smoother fade transition
8892     * when scrolling occurs.
8893     *
8894     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8895     */
8896    protected float getTopFadingEdgeStrength() {
8897        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8898    }
8899
8900    /**
8901     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8902     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8903     * returns 0.0 or 1.0 but no value in between.
8904     *
8905     * Subclasses should override this method to provide a smoother fade transition
8906     * when scrolling occurs.
8907     *
8908     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8909     */
8910    protected float getBottomFadingEdgeStrength() {
8911        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8912                computeVerticalScrollRange() ? 1.0f : 0.0f;
8913    }
8914
8915    /**
8916     * Returns the strength, or intensity, of the left faded edge. The strength is
8917     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8918     * returns 0.0 or 1.0 but no value in between.
8919     *
8920     * Subclasses should override this method to provide a smoother fade transition
8921     * when scrolling occurs.
8922     *
8923     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8924     */
8925    protected float getLeftFadingEdgeStrength() {
8926        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8927    }
8928
8929    /**
8930     * Returns the strength, or intensity, of the right faded edge. The strength is
8931     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8932     * returns 0.0 or 1.0 but no value in between.
8933     *
8934     * Subclasses should override this method to provide a smoother fade transition
8935     * when scrolling occurs.
8936     *
8937     * @return the intensity of the right fade as a float between 0.0f and 1.0f
8938     */
8939    protected float getRightFadingEdgeStrength() {
8940        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
8941                computeHorizontalScrollRange() ? 1.0f : 0.0f;
8942    }
8943
8944    /**
8945     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
8946     * scrollbar is not drawn by default.</p>
8947     *
8948     * @return true if the horizontal scrollbar should be painted, false
8949     *         otherwise
8950     *
8951     * @see #setHorizontalScrollBarEnabled(boolean)
8952     */
8953    public boolean isHorizontalScrollBarEnabled() {
8954        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8955    }
8956
8957    /**
8958     * <p>Define whether the horizontal scrollbar should be drawn or not. The
8959     * scrollbar is not drawn by default.</p>
8960     *
8961     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
8962     *                                   be painted
8963     *
8964     * @see #isHorizontalScrollBarEnabled()
8965     */
8966    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
8967        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
8968            mViewFlags ^= SCROLLBARS_HORIZONTAL;
8969            computeOpaqueFlags();
8970            resolvePadding();
8971        }
8972    }
8973
8974    /**
8975     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
8976     * scrollbar is not drawn by default.</p>
8977     *
8978     * @return true if the vertical scrollbar should be painted, false
8979     *         otherwise
8980     *
8981     * @see #setVerticalScrollBarEnabled(boolean)
8982     */
8983    public boolean isVerticalScrollBarEnabled() {
8984        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
8985    }
8986
8987    /**
8988     * <p>Define whether the vertical scrollbar should be drawn or not. The
8989     * scrollbar is not drawn by default.</p>
8990     *
8991     * @param verticalScrollBarEnabled true if the vertical scrollbar should
8992     *                                 be painted
8993     *
8994     * @see #isVerticalScrollBarEnabled()
8995     */
8996    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
8997        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
8998            mViewFlags ^= SCROLLBARS_VERTICAL;
8999            computeOpaqueFlags();
9000            resolvePadding();
9001        }
9002    }
9003
9004    /**
9005     * @hide
9006     */
9007    protected void recomputePadding() {
9008        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9009    }
9010
9011    /**
9012     * Define whether scrollbars will fade when the view is not scrolling.
9013     *
9014     * @param fadeScrollbars wheter to enable fading
9015     *
9016     */
9017    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9018        initScrollCache();
9019        final ScrollabilityCache scrollabilityCache = mScrollCache;
9020        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9021        if (fadeScrollbars) {
9022            scrollabilityCache.state = ScrollabilityCache.OFF;
9023        } else {
9024            scrollabilityCache.state = ScrollabilityCache.ON;
9025        }
9026    }
9027
9028    /**
9029     *
9030     * Returns true if scrollbars will fade when this view is not scrolling
9031     *
9032     * @return true if scrollbar fading is enabled
9033     */
9034    public boolean isScrollbarFadingEnabled() {
9035        return mScrollCache != null && mScrollCache.fadeScrollBars;
9036    }
9037
9038    /**
9039     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9040     * inset. When inset, they add to the padding of the view. And the scrollbars
9041     * can be drawn inside the padding area or on the edge of the view. For example,
9042     * if a view has a background drawable and you want to draw the scrollbars
9043     * inside the padding specified by the drawable, you can use
9044     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9045     * appear at the edge of the view, ignoring the padding, then you can use
9046     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9047     * @param style the style of the scrollbars. Should be one of
9048     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9049     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9050     * @see #SCROLLBARS_INSIDE_OVERLAY
9051     * @see #SCROLLBARS_INSIDE_INSET
9052     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9053     * @see #SCROLLBARS_OUTSIDE_INSET
9054     */
9055    public void setScrollBarStyle(int style) {
9056        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9057            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9058            computeOpaqueFlags();
9059            resolvePadding();
9060        }
9061    }
9062
9063    /**
9064     * <p>Returns the current scrollbar style.</p>
9065     * @return the current scrollbar style
9066     * @see #SCROLLBARS_INSIDE_OVERLAY
9067     * @see #SCROLLBARS_INSIDE_INSET
9068     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9069     * @see #SCROLLBARS_OUTSIDE_INSET
9070     */
9071    @ViewDebug.ExportedProperty(mapping = {
9072            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9073            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9074            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9075            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9076    })
9077    public int getScrollBarStyle() {
9078        return mViewFlags & SCROLLBARS_STYLE_MASK;
9079    }
9080
9081    /**
9082     * <p>Compute the horizontal range that the horizontal scrollbar
9083     * represents.</p>
9084     *
9085     * <p>The range is expressed in arbitrary units that must be the same as the
9086     * units used by {@link #computeHorizontalScrollExtent()} and
9087     * {@link #computeHorizontalScrollOffset()}.</p>
9088     *
9089     * <p>The default range is the drawing width of this view.</p>
9090     *
9091     * @return the total horizontal range represented by the horizontal
9092     *         scrollbar
9093     *
9094     * @see #computeHorizontalScrollExtent()
9095     * @see #computeHorizontalScrollOffset()
9096     * @see android.widget.ScrollBarDrawable
9097     */
9098    protected int computeHorizontalScrollRange() {
9099        return getWidth();
9100    }
9101
9102    /**
9103     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9104     * within the horizontal range. This value is used to compute the position
9105     * of the thumb within the scrollbar's track.</p>
9106     *
9107     * <p>The range is expressed in arbitrary units that must be the same as the
9108     * units used by {@link #computeHorizontalScrollRange()} and
9109     * {@link #computeHorizontalScrollExtent()}.</p>
9110     *
9111     * <p>The default offset is the scroll offset of this view.</p>
9112     *
9113     * @return the horizontal offset of the scrollbar's thumb
9114     *
9115     * @see #computeHorizontalScrollRange()
9116     * @see #computeHorizontalScrollExtent()
9117     * @see android.widget.ScrollBarDrawable
9118     */
9119    protected int computeHorizontalScrollOffset() {
9120        return mScrollX;
9121    }
9122
9123    /**
9124     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9125     * within the horizontal range. This value is used to compute the length
9126     * of the thumb within the scrollbar's track.</p>
9127     *
9128     * <p>The range is expressed in arbitrary units that must be the same as the
9129     * units used by {@link #computeHorizontalScrollRange()} and
9130     * {@link #computeHorizontalScrollOffset()}.</p>
9131     *
9132     * <p>The default extent is the drawing width of this view.</p>
9133     *
9134     * @return the horizontal extent of the scrollbar's thumb
9135     *
9136     * @see #computeHorizontalScrollRange()
9137     * @see #computeHorizontalScrollOffset()
9138     * @see android.widget.ScrollBarDrawable
9139     */
9140    protected int computeHorizontalScrollExtent() {
9141        return getWidth();
9142    }
9143
9144    /**
9145     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9146     *
9147     * <p>The range is expressed in arbitrary units that must be the same as the
9148     * units used by {@link #computeVerticalScrollExtent()} and
9149     * {@link #computeVerticalScrollOffset()}.</p>
9150     *
9151     * @return the total vertical range represented by the vertical scrollbar
9152     *
9153     * <p>The default range is the drawing height of this view.</p>
9154     *
9155     * @see #computeVerticalScrollExtent()
9156     * @see #computeVerticalScrollOffset()
9157     * @see android.widget.ScrollBarDrawable
9158     */
9159    protected int computeVerticalScrollRange() {
9160        return getHeight();
9161    }
9162
9163    /**
9164     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9165     * within the horizontal range. This value is used to compute the position
9166     * of the thumb within the scrollbar's track.</p>
9167     *
9168     * <p>The range is expressed in arbitrary units that must be the same as the
9169     * units used by {@link #computeVerticalScrollRange()} and
9170     * {@link #computeVerticalScrollExtent()}.</p>
9171     *
9172     * <p>The default offset is the scroll offset of this view.</p>
9173     *
9174     * @return the vertical offset of the scrollbar's thumb
9175     *
9176     * @see #computeVerticalScrollRange()
9177     * @see #computeVerticalScrollExtent()
9178     * @see android.widget.ScrollBarDrawable
9179     */
9180    protected int computeVerticalScrollOffset() {
9181        return mScrollY;
9182    }
9183
9184    /**
9185     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9186     * within the vertical range. This value is used to compute the length
9187     * of the thumb within the scrollbar's track.</p>
9188     *
9189     * <p>The range is expressed in arbitrary units that must be the same as the
9190     * units used by {@link #computeVerticalScrollRange()} and
9191     * {@link #computeVerticalScrollOffset()}.</p>
9192     *
9193     * <p>The default extent is the drawing height of this view.</p>
9194     *
9195     * @return the vertical extent of the scrollbar's thumb
9196     *
9197     * @see #computeVerticalScrollRange()
9198     * @see #computeVerticalScrollOffset()
9199     * @see android.widget.ScrollBarDrawable
9200     */
9201    protected int computeVerticalScrollExtent() {
9202        return getHeight();
9203    }
9204
9205    /**
9206     * Check if this view can be scrolled horizontally in a certain direction.
9207     *
9208     * @param direction Negative to check scrolling left, positive to check scrolling right.
9209     * @return true if this view can be scrolled in the specified direction, false otherwise.
9210     */
9211    public boolean canScrollHorizontally(int direction) {
9212        final int offset = computeHorizontalScrollOffset();
9213        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9214        if (range == 0) return false;
9215        if (direction < 0) {
9216            return offset > 0;
9217        } else {
9218            return offset < range - 1;
9219        }
9220    }
9221
9222    /**
9223     * Check if this view can be scrolled vertically in a certain direction.
9224     *
9225     * @param direction Negative to check scrolling up, positive to check scrolling down.
9226     * @return true if this view can be scrolled in the specified direction, false otherwise.
9227     */
9228    public boolean canScrollVertically(int direction) {
9229        final int offset = computeVerticalScrollOffset();
9230        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9231        if (range == 0) return false;
9232        if (direction < 0) {
9233            return offset > 0;
9234        } else {
9235            return offset < range - 1;
9236        }
9237    }
9238
9239    /**
9240     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9241     * scrollbars are painted only if they have been awakened first.</p>
9242     *
9243     * @param canvas the canvas on which to draw the scrollbars
9244     *
9245     * @see #awakenScrollBars(int)
9246     */
9247    protected final void onDrawScrollBars(Canvas canvas) {
9248        // scrollbars are drawn only when the animation is running
9249        final ScrollabilityCache cache = mScrollCache;
9250        if (cache != null) {
9251
9252            int state = cache.state;
9253
9254            if (state == ScrollabilityCache.OFF) {
9255                return;
9256            }
9257
9258            boolean invalidate = false;
9259
9260            if (state == ScrollabilityCache.FADING) {
9261                // We're fading -- get our fade interpolation
9262                if (cache.interpolatorValues == null) {
9263                    cache.interpolatorValues = new float[1];
9264                }
9265
9266                float[] values = cache.interpolatorValues;
9267
9268                // Stops the animation if we're done
9269                if (cache.scrollBarInterpolator.timeToValues(values) ==
9270                        Interpolator.Result.FREEZE_END) {
9271                    cache.state = ScrollabilityCache.OFF;
9272                } else {
9273                    cache.scrollBar.setAlpha(Math.round(values[0]));
9274                }
9275
9276                // This will make the scroll bars inval themselves after
9277                // drawing. We only want this when we're fading so that
9278                // we prevent excessive redraws
9279                invalidate = true;
9280            } else {
9281                // We're just on -- but we may have been fading before so
9282                // reset alpha
9283                cache.scrollBar.setAlpha(255);
9284            }
9285
9286
9287            final int viewFlags = mViewFlags;
9288
9289            final boolean drawHorizontalScrollBar =
9290                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9291            final boolean drawVerticalScrollBar =
9292                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9293                && !isVerticalScrollBarHidden();
9294
9295            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9296                final int width = mRight - mLeft;
9297                final int height = mBottom - mTop;
9298
9299                final ScrollBarDrawable scrollBar = cache.scrollBar;
9300
9301                final int scrollX = mScrollX;
9302                final int scrollY = mScrollY;
9303                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9304
9305                int left, top, right, bottom;
9306
9307                if (drawHorizontalScrollBar) {
9308                    int size = scrollBar.getSize(false);
9309                    if (size <= 0) {
9310                        size = cache.scrollBarSize;
9311                    }
9312
9313                    scrollBar.setParameters(computeHorizontalScrollRange(),
9314                                            computeHorizontalScrollOffset(),
9315                                            computeHorizontalScrollExtent(), false);
9316                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9317                            getVerticalScrollbarWidth() : 0;
9318                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9319                    left = scrollX + (mPaddingLeft & inside);
9320                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9321                    bottom = top + size;
9322                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9323                    if (invalidate) {
9324                        invalidate(left, top, right, bottom);
9325                    }
9326                }
9327
9328                if (drawVerticalScrollBar) {
9329                    int size = scrollBar.getSize(true);
9330                    if (size <= 0) {
9331                        size = cache.scrollBarSize;
9332                    }
9333
9334                    scrollBar.setParameters(computeVerticalScrollRange(),
9335                                            computeVerticalScrollOffset(),
9336                                            computeVerticalScrollExtent(), true);
9337                    switch (mVerticalScrollbarPosition) {
9338                        default:
9339                        case SCROLLBAR_POSITION_DEFAULT:
9340                        case SCROLLBAR_POSITION_RIGHT:
9341                            left = scrollX + width - size - (mUserPaddingRight & inside);
9342                            break;
9343                        case SCROLLBAR_POSITION_LEFT:
9344                            left = scrollX + (mUserPaddingLeft & inside);
9345                            break;
9346                    }
9347                    top = scrollY + (mPaddingTop & inside);
9348                    right = left + size;
9349                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9350                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9351                    if (invalidate) {
9352                        invalidate(left, top, right, bottom);
9353                    }
9354                }
9355            }
9356        }
9357    }
9358
9359    /**
9360     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9361     * FastScroller is visible.
9362     * @return whether to temporarily hide the vertical scrollbar
9363     * @hide
9364     */
9365    protected boolean isVerticalScrollBarHidden() {
9366        return false;
9367    }
9368
9369    /**
9370     * <p>Draw the horizontal scrollbar if
9371     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9372     *
9373     * @param canvas the canvas on which to draw the scrollbar
9374     * @param scrollBar the scrollbar's drawable
9375     *
9376     * @see #isHorizontalScrollBarEnabled()
9377     * @see #computeHorizontalScrollRange()
9378     * @see #computeHorizontalScrollExtent()
9379     * @see #computeHorizontalScrollOffset()
9380     * @see android.widget.ScrollBarDrawable
9381     * @hide
9382     */
9383    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9384            int l, int t, int r, int b) {
9385        scrollBar.setBounds(l, t, r, b);
9386        scrollBar.draw(canvas);
9387    }
9388
9389    /**
9390     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9391     * returns true.</p>
9392     *
9393     * @param canvas the canvas on which to draw the scrollbar
9394     * @param scrollBar the scrollbar's drawable
9395     *
9396     * @see #isVerticalScrollBarEnabled()
9397     * @see #computeVerticalScrollRange()
9398     * @see #computeVerticalScrollExtent()
9399     * @see #computeVerticalScrollOffset()
9400     * @see android.widget.ScrollBarDrawable
9401     * @hide
9402     */
9403    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9404            int l, int t, int r, int b) {
9405        scrollBar.setBounds(l, t, r, b);
9406        scrollBar.draw(canvas);
9407    }
9408
9409    /**
9410     * Implement this to do your drawing.
9411     *
9412     * @param canvas the canvas on which the background will be drawn
9413     */
9414    protected void onDraw(Canvas canvas) {
9415    }
9416
9417    /*
9418     * Caller is responsible for calling requestLayout if necessary.
9419     * (This allows addViewInLayout to not request a new layout.)
9420     */
9421    void assignParent(ViewParent parent) {
9422        if (mParent == null) {
9423            mParent = parent;
9424        } else if (parent == null) {
9425            mParent = null;
9426        } else {
9427            throw new RuntimeException("view " + this + " being added, but"
9428                    + " it already has a parent");
9429        }
9430    }
9431
9432    /**
9433     * This is called when the view is attached to a window.  At this point it
9434     * has a Surface and will start drawing.  Note that this function is
9435     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9436     * however it may be called any time before the first onDraw -- including
9437     * before or after {@link #onMeasure(int, int)}.
9438     *
9439     * @see #onDetachedFromWindow()
9440     */
9441    protected void onAttachedToWindow() {
9442        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9443            mParent.requestTransparentRegion(this);
9444        }
9445        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9446            initialAwakenScrollBars();
9447            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9448        }
9449        jumpDrawablesToCurrentState();
9450        // Order is important here: LayoutDirection MUST be resolved before Padding
9451        // and TextDirection
9452        resolveLayoutDirectionIfNeeded();
9453        resolvePadding();
9454        resolveTextDirection();
9455        if (isFocused()) {
9456            InputMethodManager imm = InputMethodManager.peekInstance();
9457            imm.focusIn(this);
9458        }
9459    }
9460
9461    /**
9462     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9463     * that the parent directionality can and will be resolved before its children.
9464     */
9465    private void resolveLayoutDirectionIfNeeded() {
9466        // Do not resolve if it is not needed
9467        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9468
9469        // Clear any previous layout direction resolution
9470        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9471
9472        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9473        // TextDirectionHeuristic
9474        resetResolvedTextDirection();
9475
9476        // Set resolved depending on layout direction
9477        switch (getLayoutDirection()) {
9478            case LAYOUT_DIRECTION_INHERIT:
9479                // We cannot do the resolution if there is no parent
9480                if (mParent == null) return;
9481
9482                // If this is root view, no need to look at parent's layout dir.
9483                if (mParent instanceof ViewGroup) {
9484                    ViewGroup viewGroup = ((ViewGroup) mParent);
9485
9486                    // Check if the parent view group can resolve
9487                    if (! viewGroup.canResolveLayoutDirection()) {
9488                        return;
9489                    }
9490                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9491                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9492                    }
9493                }
9494                break;
9495            case LAYOUT_DIRECTION_RTL:
9496                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9497                break;
9498            case LAYOUT_DIRECTION_LOCALE:
9499                if(isLayoutDirectionRtl(Locale.getDefault())) {
9500                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9501                }
9502                break;
9503            default:
9504                // Nothing to do, LTR by default
9505        }
9506
9507        // Set to resolved
9508        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9509    }
9510
9511    /**
9512     * @hide
9513     */
9514    protected void resolvePadding() {
9515        // If the user specified the absolute padding (either with android:padding or
9516        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9517        // use the default padding or the padding from the background drawable
9518        // (stored at this point in mPadding*)
9519        switch (getResolvedLayoutDirection()) {
9520            case LAYOUT_DIRECTION_RTL:
9521                // Start user padding override Right user padding. Otherwise, if Right user
9522                // padding is not defined, use the default Right padding. If Right user padding
9523                // is defined, just use it.
9524                if (mUserPaddingStart >= 0) {
9525                    mUserPaddingRight = mUserPaddingStart;
9526                } else if (mUserPaddingRight < 0) {
9527                    mUserPaddingRight = mPaddingRight;
9528                }
9529                if (mUserPaddingEnd >= 0) {
9530                    mUserPaddingLeft = mUserPaddingEnd;
9531                } else if (mUserPaddingLeft < 0) {
9532                    mUserPaddingLeft = mPaddingLeft;
9533                }
9534                break;
9535            case LAYOUT_DIRECTION_LTR:
9536            default:
9537                // Start user padding override Left user padding. Otherwise, if Left user
9538                // padding is not defined, use the default left padding. If Left user padding
9539                // is defined, just use it.
9540                if (mUserPaddingStart >= 0) {
9541                    mUserPaddingLeft = mUserPaddingStart;
9542                } else if (mUserPaddingLeft < 0) {
9543                    mUserPaddingLeft = mPaddingLeft;
9544                }
9545                if (mUserPaddingEnd >= 0) {
9546                    mUserPaddingRight = mUserPaddingEnd;
9547                } else if (mUserPaddingRight < 0) {
9548                    mUserPaddingRight = mPaddingRight;
9549                }
9550        }
9551
9552        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9553
9554        recomputePadding();
9555    }
9556
9557    /**
9558     * Return true if layout direction resolution can be done
9559     *
9560     * @hide
9561     */
9562    protected boolean canResolveLayoutDirection() {
9563        switch (getLayoutDirection()) {
9564            case LAYOUT_DIRECTION_INHERIT:
9565                return (mParent != null);
9566            default:
9567                return true;
9568        }
9569    }
9570
9571    /**
9572     * Reset the resolved layout direction.
9573     *
9574     * Subclasses need to override this method to clear cached information that depends on the
9575     * resolved layout direction, or to inform child views that inherit their layout direction.
9576     * Overrides must also call the superclass implementation at the start of their implementation.
9577     *
9578     * @hide
9579     */
9580    protected void resetResolvedLayoutDirection() {
9581        // Reset the current View resolution
9582        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9583    }
9584
9585    /**
9586     * Check if a Locale is corresponding to a RTL script.
9587     *
9588     * @param locale Locale to check
9589     * @return true if a Locale is corresponding to a RTL script.
9590     *
9591     * @hide
9592     */
9593    protected static boolean isLayoutDirectionRtl(Locale locale) {
9594        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9595                LocaleUtil.getLayoutDirectionFromLocale(locale));
9596    }
9597
9598    /**
9599     * This is called when the view is detached from a window.  At this point it
9600     * no longer has a surface for drawing.
9601     *
9602     * @see #onAttachedToWindow()
9603     */
9604    protected void onDetachedFromWindow() {
9605        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9606
9607        removeUnsetPressCallback();
9608        removeLongPressCallback();
9609        removePerformClickCallback();
9610        removeSendViewScrolledAccessibilityEventCallback();
9611
9612        destroyDrawingCache();
9613
9614        destroyLayer();
9615
9616        if (mDisplayList != null) {
9617            mDisplayList.invalidate();
9618        }
9619
9620        if (mAttachInfo != null) {
9621            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9622        }
9623
9624        mCurrentAnimation = null;
9625
9626        resetResolvedLayoutDirection();
9627        resetResolvedTextDirection();
9628    }
9629
9630    /**
9631     * @return The number of times this view has been attached to a window
9632     */
9633    protected int getWindowAttachCount() {
9634        return mWindowAttachCount;
9635    }
9636
9637    /**
9638     * Retrieve a unique token identifying the window this view is attached to.
9639     * @return Return the window's token for use in
9640     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9641     */
9642    public IBinder getWindowToken() {
9643        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9644    }
9645
9646    /**
9647     * Retrieve a unique token identifying the top-level "real" window of
9648     * the window that this view is attached to.  That is, this is like
9649     * {@link #getWindowToken}, except if the window this view in is a panel
9650     * window (attached to another containing window), then the token of
9651     * the containing window is returned instead.
9652     *
9653     * @return Returns the associated window token, either
9654     * {@link #getWindowToken()} or the containing window's token.
9655     */
9656    public IBinder getApplicationWindowToken() {
9657        AttachInfo ai = mAttachInfo;
9658        if (ai != null) {
9659            IBinder appWindowToken = ai.mPanelParentWindowToken;
9660            if (appWindowToken == null) {
9661                appWindowToken = ai.mWindowToken;
9662            }
9663            return appWindowToken;
9664        }
9665        return null;
9666    }
9667
9668    /**
9669     * Retrieve private session object this view hierarchy is using to
9670     * communicate with the window manager.
9671     * @return the session object to communicate with the window manager
9672     */
9673    /*package*/ IWindowSession getWindowSession() {
9674        return mAttachInfo != null ? mAttachInfo.mSession : null;
9675    }
9676
9677    /**
9678     * @param info the {@link android.view.View.AttachInfo} to associated with
9679     *        this view
9680     */
9681    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9682        //System.out.println("Attached! " + this);
9683        mAttachInfo = info;
9684        mWindowAttachCount++;
9685        // We will need to evaluate the drawable state at least once.
9686        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9687        if (mFloatingTreeObserver != null) {
9688            info.mTreeObserver.merge(mFloatingTreeObserver);
9689            mFloatingTreeObserver = null;
9690        }
9691        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9692            mAttachInfo.mScrollContainers.add(this);
9693            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9694        }
9695        performCollectViewAttributes(visibility);
9696        onAttachedToWindow();
9697
9698        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9699                mOnAttachStateChangeListeners;
9700        if (listeners != null && listeners.size() > 0) {
9701            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9702            // perform the dispatching. The iterator is a safe guard against listeners that
9703            // could mutate the list by calling the various add/remove methods. This prevents
9704            // the array from being modified while we iterate it.
9705            for (OnAttachStateChangeListener listener : listeners) {
9706                listener.onViewAttachedToWindow(this);
9707            }
9708        }
9709
9710        int vis = info.mWindowVisibility;
9711        if (vis != GONE) {
9712            onWindowVisibilityChanged(vis);
9713        }
9714        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9715            // If nobody has evaluated the drawable state yet, then do it now.
9716            refreshDrawableState();
9717        }
9718    }
9719
9720    void dispatchDetachedFromWindow() {
9721        AttachInfo info = mAttachInfo;
9722        if (info != null) {
9723            int vis = info.mWindowVisibility;
9724            if (vis != GONE) {
9725                onWindowVisibilityChanged(GONE);
9726            }
9727        }
9728
9729        onDetachedFromWindow();
9730
9731        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9732                mOnAttachStateChangeListeners;
9733        if (listeners != null && listeners.size() > 0) {
9734            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9735            // perform the dispatching. The iterator is a safe guard against listeners that
9736            // could mutate the list by calling the various add/remove methods. This prevents
9737            // the array from being modified while we iterate it.
9738            for (OnAttachStateChangeListener listener : listeners) {
9739                listener.onViewDetachedFromWindow(this);
9740            }
9741        }
9742
9743        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9744            mAttachInfo.mScrollContainers.remove(this);
9745            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9746        }
9747
9748        mAttachInfo = null;
9749    }
9750
9751    /**
9752     * Store this view hierarchy's frozen state into the given container.
9753     *
9754     * @param container The SparseArray in which to save the view's state.
9755     *
9756     * @see #restoreHierarchyState(android.util.SparseArray)
9757     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9758     * @see #onSaveInstanceState()
9759     */
9760    public void saveHierarchyState(SparseArray<Parcelable> container) {
9761        dispatchSaveInstanceState(container);
9762    }
9763
9764    /**
9765     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9766     * this view and its children. May be overridden to modify how freezing happens to a
9767     * view's children; for example, some views may want to not store state for their children.
9768     *
9769     * @param container The SparseArray in which to save the view's state.
9770     *
9771     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9772     * @see #saveHierarchyState(android.util.SparseArray)
9773     * @see #onSaveInstanceState()
9774     */
9775    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9776        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9777            mPrivateFlags &= ~SAVE_STATE_CALLED;
9778            Parcelable state = onSaveInstanceState();
9779            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9780                throw new IllegalStateException(
9781                        "Derived class did not call super.onSaveInstanceState()");
9782            }
9783            if (state != null) {
9784                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9785                // + ": " + state);
9786                container.put(mID, state);
9787            }
9788        }
9789    }
9790
9791    /**
9792     * Hook allowing a view to generate a representation of its internal state
9793     * that can later be used to create a new instance with that same state.
9794     * This state should only contain information that is not persistent or can
9795     * not be reconstructed later. For example, you will never store your
9796     * current position on screen because that will be computed again when a
9797     * new instance of the view is placed in its view hierarchy.
9798     * <p>
9799     * Some examples of things you may store here: the current cursor position
9800     * in a text view (but usually not the text itself since that is stored in a
9801     * content provider or other persistent storage), the currently selected
9802     * item in a list view.
9803     *
9804     * @return Returns a Parcelable object containing the view's current dynamic
9805     *         state, or null if there is nothing interesting to save. The
9806     *         default implementation returns null.
9807     * @see #onRestoreInstanceState(android.os.Parcelable)
9808     * @see #saveHierarchyState(android.util.SparseArray)
9809     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9810     * @see #setSaveEnabled(boolean)
9811     */
9812    protected Parcelable onSaveInstanceState() {
9813        mPrivateFlags |= SAVE_STATE_CALLED;
9814        return BaseSavedState.EMPTY_STATE;
9815    }
9816
9817    /**
9818     * Restore this view hierarchy's frozen state from the given container.
9819     *
9820     * @param container The SparseArray which holds previously frozen states.
9821     *
9822     * @see #saveHierarchyState(android.util.SparseArray)
9823     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9824     * @see #onRestoreInstanceState(android.os.Parcelable)
9825     */
9826    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9827        dispatchRestoreInstanceState(container);
9828    }
9829
9830    /**
9831     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9832     * state for this view and its children. May be overridden to modify how restoring
9833     * happens to a view's children; for example, some views may want to not store state
9834     * for their children.
9835     *
9836     * @param container The SparseArray which holds previously saved state.
9837     *
9838     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9839     * @see #restoreHierarchyState(android.util.SparseArray)
9840     * @see #onRestoreInstanceState(android.os.Parcelable)
9841     */
9842    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9843        if (mID != NO_ID) {
9844            Parcelable state = container.get(mID);
9845            if (state != null) {
9846                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9847                // + ": " + state);
9848                mPrivateFlags &= ~SAVE_STATE_CALLED;
9849                onRestoreInstanceState(state);
9850                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9851                    throw new IllegalStateException(
9852                            "Derived class did not call super.onRestoreInstanceState()");
9853                }
9854            }
9855        }
9856    }
9857
9858    /**
9859     * Hook allowing a view to re-apply a representation of its internal state that had previously
9860     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9861     * null state.
9862     *
9863     * @param state The frozen state that had previously been returned by
9864     *        {@link #onSaveInstanceState}.
9865     *
9866     * @see #onSaveInstanceState()
9867     * @see #restoreHierarchyState(android.util.SparseArray)
9868     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9869     */
9870    protected void onRestoreInstanceState(Parcelable state) {
9871        mPrivateFlags |= SAVE_STATE_CALLED;
9872        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9873            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9874                    + "received " + state.getClass().toString() + " instead. This usually happens "
9875                    + "when two views of different type have the same id in the same hierarchy. "
9876                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9877                    + "other views do not use the same id.");
9878        }
9879    }
9880
9881    /**
9882     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9883     *
9884     * @return the drawing start time in milliseconds
9885     */
9886    public long getDrawingTime() {
9887        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9888    }
9889
9890    /**
9891     * <p>Enables or disables the duplication of the parent's state into this view. When
9892     * duplication is enabled, this view gets its drawable state from its parent rather
9893     * than from its own internal properties.</p>
9894     *
9895     * <p>Note: in the current implementation, setting this property to true after the
9896     * view was added to a ViewGroup might have no effect at all. This property should
9897     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9898     *
9899     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9900     * property is enabled, an exception will be thrown.</p>
9901     *
9902     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9903     * parent, these states should not be affected by this method.</p>
9904     *
9905     * @param enabled True to enable duplication of the parent's drawable state, false
9906     *                to disable it.
9907     *
9908     * @see #getDrawableState()
9909     * @see #isDuplicateParentStateEnabled()
9910     */
9911    public void setDuplicateParentStateEnabled(boolean enabled) {
9912        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9913    }
9914
9915    /**
9916     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9917     *
9918     * @return True if this view's drawable state is duplicated from the parent,
9919     *         false otherwise
9920     *
9921     * @see #getDrawableState()
9922     * @see #setDuplicateParentStateEnabled(boolean)
9923     */
9924    public boolean isDuplicateParentStateEnabled() {
9925        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9926    }
9927
9928    /**
9929     * <p>Specifies the type of layer backing this view. The layer can be
9930     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9931     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
9932     *
9933     * <p>A layer is associated with an optional {@link android.graphics.Paint}
9934     * instance that controls how the layer is composed on screen. The following
9935     * properties of the paint are taken into account when composing the layer:</p>
9936     * <ul>
9937     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
9938     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
9939     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
9940     * </ul>
9941     *
9942     * <p>If this view has an alpha value set to < 1.0 by calling
9943     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
9944     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
9945     * equivalent to setting a hardware layer on this view and providing a paint with
9946     * the desired alpha value.<p>
9947     *
9948     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
9949     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
9950     * for more information on when and how to use layers.</p>
9951     *
9952     * @param layerType The ype of layer to use with this view, must be one of
9953     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9954     *        {@link #LAYER_TYPE_HARDWARE}
9955     * @param paint The paint used to compose the layer. This argument is optional
9956     *        and can be null. It is ignored when the layer type is
9957     *        {@link #LAYER_TYPE_NONE}
9958     *
9959     * @see #getLayerType()
9960     * @see #LAYER_TYPE_NONE
9961     * @see #LAYER_TYPE_SOFTWARE
9962     * @see #LAYER_TYPE_HARDWARE
9963     * @see #setAlpha(float)
9964     *
9965     * @attr ref android.R.styleable#View_layerType
9966     */
9967    public void setLayerType(int layerType, Paint paint) {
9968        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
9969            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
9970                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
9971        }
9972
9973        if (layerType == mLayerType) {
9974            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
9975                mLayerPaint = paint == null ? new Paint() : paint;
9976                invalidateParentCaches();
9977                invalidate(true);
9978            }
9979            return;
9980        }
9981
9982        // Destroy any previous software drawing cache if needed
9983        switch (mLayerType) {
9984            case LAYER_TYPE_HARDWARE:
9985                destroyLayer();
9986                // fall through - unaccelerated views may use software layer mechanism instead
9987            case LAYER_TYPE_SOFTWARE:
9988                destroyDrawingCache();
9989                break;
9990            default:
9991                break;
9992        }
9993
9994        mLayerType = layerType;
9995        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
9996        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
9997        mLocalDirtyRect = layerDisabled ? null : new Rect();
9998
9999        invalidateParentCaches();
10000        invalidate(true);
10001    }
10002
10003    /**
10004     * Indicates what type of layer is currently associated with this view. By default
10005     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10006     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10007     * for more information on the different types of layers.
10008     *
10009     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10010     *         {@link #LAYER_TYPE_HARDWARE}
10011     *
10012     * @see #setLayerType(int, android.graphics.Paint)
10013     * @see #buildLayer()
10014     * @see #LAYER_TYPE_NONE
10015     * @see #LAYER_TYPE_SOFTWARE
10016     * @see #LAYER_TYPE_HARDWARE
10017     */
10018    public int getLayerType() {
10019        return mLayerType;
10020    }
10021
10022    /**
10023     * Forces this view's layer to be created and this view to be rendered
10024     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10025     * invoking this method will have no effect.
10026     *
10027     * This method can for instance be used to render a view into its layer before
10028     * starting an animation. If this view is complex, rendering into the layer
10029     * before starting the animation will avoid skipping frames.
10030     *
10031     * @throws IllegalStateException If this view is not attached to a window
10032     *
10033     * @see #setLayerType(int, android.graphics.Paint)
10034     */
10035    public void buildLayer() {
10036        if (mLayerType == LAYER_TYPE_NONE) return;
10037
10038        if (mAttachInfo == null) {
10039            throw new IllegalStateException("This view must be attached to a window first");
10040        }
10041
10042        switch (mLayerType) {
10043            case LAYER_TYPE_HARDWARE:
10044                getHardwareLayer();
10045                break;
10046            case LAYER_TYPE_SOFTWARE:
10047                buildDrawingCache(true);
10048                break;
10049        }
10050    }
10051
10052    /**
10053     * <p>Returns a hardware layer that can be used to draw this view again
10054     * without executing its draw method.</p>
10055     *
10056     * @return A HardwareLayer ready to render, or null if an error occurred.
10057     */
10058    HardwareLayer getHardwareLayer() {
10059        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10060                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10061            return null;
10062        }
10063
10064        final int width = mRight - mLeft;
10065        final int height = mBottom - mTop;
10066
10067        if (width == 0 || height == 0) {
10068            return null;
10069        }
10070
10071        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10072            if (mHardwareLayer == null) {
10073                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10074                        width, height, isOpaque());
10075                mLocalDirtyRect.setEmpty();
10076            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10077                mHardwareLayer.resize(width, height);
10078                mLocalDirtyRect.setEmpty();
10079            }
10080
10081            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
10082            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
10083            mAttachInfo.mHardwareCanvas = canvas;
10084            try {
10085                canvas.setViewport(width, height);
10086                canvas.onPreDraw(mLocalDirtyRect);
10087                mLocalDirtyRect.setEmpty();
10088
10089                final int restoreCount = canvas.save();
10090
10091                computeScroll();
10092                canvas.translate(-mScrollX, -mScrollY);
10093
10094                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10095
10096                // Fast path for layouts with no backgrounds
10097                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10098                    mPrivateFlags &= ~DIRTY_MASK;
10099                    dispatchDraw(canvas);
10100                } else {
10101                    draw(canvas);
10102                }
10103
10104                canvas.restoreToCount(restoreCount);
10105            } finally {
10106                canvas.onPostDraw();
10107                mHardwareLayer.end(currentCanvas);
10108                mAttachInfo.mHardwareCanvas = currentCanvas;
10109            }
10110        }
10111
10112        return mHardwareLayer;
10113    }
10114
10115    boolean destroyLayer() {
10116        if (mHardwareLayer != null) {
10117            mHardwareLayer.destroy();
10118            mHardwareLayer = null;
10119            return true;
10120        }
10121        return false;
10122    }
10123
10124    /**
10125     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10126     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10127     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10128     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10129     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10130     * null.</p>
10131     *
10132     * <p>Enabling the drawing cache is similar to
10133     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10134     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10135     * drawing cache has no effect on rendering because the system uses a different mechanism
10136     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10137     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10138     * for information on how to enable software and hardware layers.</p>
10139     *
10140     * <p>This API can be used to manually generate
10141     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10142     * {@link #getDrawingCache()}.</p>
10143     *
10144     * @param enabled true to enable the drawing cache, false otherwise
10145     *
10146     * @see #isDrawingCacheEnabled()
10147     * @see #getDrawingCache()
10148     * @see #buildDrawingCache()
10149     * @see #setLayerType(int, android.graphics.Paint)
10150     */
10151    public void setDrawingCacheEnabled(boolean enabled) {
10152        mCachingFailed = false;
10153        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10154    }
10155
10156    /**
10157     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10158     *
10159     * @return true if the drawing cache is enabled
10160     *
10161     * @see #setDrawingCacheEnabled(boolean)
10162     * @see #getDrawingCache()
10163     */
10164    @ViewDebug.ExportedProperty(category = "drawing")
10165    public boolean isDrawingCacheEnabled() {
10166        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10167    }
10168
10169    /**
10170     * Debugging utility which recursively outputs the dirty state of a view and its
10171     * descendants.
10172     *
10173     * @hide
10174     */
10175    @SuppressWarnings({"UnusedDeclaration"})
10176    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10177        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10178                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10179                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10180                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10181        if (clear) {
10182            mPrivateFlags &= clearMask;
10183        }
10184        if (this instanceof ViewGroup) {
10185            ViewGroup parent = (ViewGroup) this;
10186            final int count = parent.getChildCount();
10187            for (int i = 0; i < count; i++) {
10188                final View child = parent.getChildAt(i);
10189                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10190            }
10191        }
10192    }
10193
10194    /**
10195     * This method is used by ViewGroup to cause its children to restore or recreate their
10196     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10197     * to recreate its own display list, which would happen if it went through the normal
10198     * draw/dispatchDraw mechanisms.
10199     *
10200     * @hide
10201     */
10202    protected void dispatchGetDisplayList() {}
10203
10204    /**
10205     * A view that is not attached or hardware accelerated cannot create a display list.
10206     * This method checks these conditions and returns the appropriate result.
10207     *
10208     * @return true if view has the ability to create a display list, false otherwise.
10209     *
10210     * @hide
10211     */
10212    public boolean canHaveDisplayList() {
10213        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10214    }
10215
10216    /**
10217     * <p>Returns a display list that can be used to draw this view again
10218     * without executing its draw method.</p>
10219     *
10220     * @return A DisplayList ready to replay, or null if caching is not enabled.
10221     *
10222     * @hide
10223     */
10224    public DisplayList getDisplayList() {
10225        if (!canHaveDisplayList()) {
10226            return null;
10227        }
10228
10229        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10230                mDisplayList == null || !mDisplayList.isValid() ||
10231                mRecreateDisplayList)) {
10232            // Don't need to recreate the display list, just need to tell our
10233            // children to restore/recreate theirs
10234            if (mDisplayList != null && mDisplayList.isValid() &&
10235                    !mRecreateDisplayList) {
10236                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10237                mPrivateFlags &= ~DIRTY_MASK;
10238                dispatchGetDisplayList();
10239
10240                return mDisplayList;
10241            }
10242
10243            // If we got here, we're recreating it. Mark it as such to ensure that
10244            // we copy in child display lists into ours in drawChild()
10245            mRecreateDisplayList = true;
10246            if (mDisplayList == null) {
10247                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
10248                // If we're creating a new display list, make sure our parent gets invalidated
10249                // since they will need to recreate their display list to account for this
10250                // new child display list.
10251                invalidateParentCaches();
10252            }
10253
10254            final HardwareCanvas canvas = mDisplayList.start();
10255            int restoreCount = 0;
10256            try {
10257                int width = mRight - mLeft;
10258                int height = mBottom - mTop;
10259
10260                canvas.setViewport(width, height);
10261                // The dirty rect should always be null for a display list
10262                canvas.onPreDraw(null);
10263
10264                computeScroll();
10265
10266                restoreCount = canvas.save();
10267                canvas.translate(-mScrollX, -mScrollY);
10268                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10269                mPrivateFlags &= ~DIRTY_MASK;
10270
10271                // Fast path for layouts with no backgrounds
10272                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10273                    dispatchDraw(canvas);
10274                } else {
10275                    draw(canvas);
10276                }
10277            } finally {
10278                canvas.restoreToCount(restoreCount);
10279                canvas.onPostDraw();
10280
10281                mDisplayList.end();
10282            }
10283        } else {
10284            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10285            mPrivateFlags &= ~DIRTY_MASK;
10286        }
10287
10288        return mDisplayList;
10289    }
10290
10291    /**
10292     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10293     *
10294     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10295     *
10296     * @see #getDrawingCache(boolean)
10297     */
10298    public Bitmap getDrawingCache() {
10299        return getDrawingCache(false);
10300    }
10301
10302    /**
10303     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10304     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10305     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10306     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10307     * request the drawing cache by calling this method and draw it on screen if the
10308     * returned bitmap is not null.</p>
10309     *
10310     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10311     * this method will create a bitmap of the same size as this view. Because this bitmap
10312     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10313     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10314     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10315     * size than the view. This implies that your application must be able to handle this
10316     * size.</p>
10317     *
10318     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10319     *        the current density of the screen when the application is in compatibility
10320     *        mode.
10321     *
10322     * @return A bitmap representing this view or null if cache is disabled.
10323     *
10324     * @see #setDrawingCacheEnabled(boolean)
10325     * @see #isDrawingCacheEnabled()
10326     * @see #buildDrawingCache(boolean)
10327     * @see #destroyDrawingCache()
10328     */
10329    public Bitmap getDrawingCache(boolean autoScale) {
10330        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10331            return null;
10332        }
10333        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10334            buildDrawingCache(autoScale);
10335        }
10336        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10337    }
10338
10339    /**
10340     * <p>Frees the resources used by the drawing cache. If you call
10341     * {@link #buildDrawingCache()} manually without calling
10342     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10343     * should cleanup the cache with this method afterwards.</p>
10344     *
10345     * @see #setDrawingCacheEnabled(boolean)
10346     * @see #buildDrawingCache()
10347     * @see #getDrawingCache()
10348     */
10349    public void destroyDrawingCache() {
10350        if (mDrawingCache != null) {
10351            mDrawingCache.recycle();
10352            mDrawingCache = null;
10353        }
10354        if (mUnscaledDrawingCache != null) {
10355            mUnscaledDrawingCache.recycle();
10356            mUnscaledDrawingCache = null;
10357        }
10358    }
10359
10360    /**
10361     * Setting a solid background color for the drawing cache's bitmaps will improve
10362     * performance and memory usage. Note, though that this should only be used if this
10363     * view will always be drawn on top of a solid color.
10364     *
10365     * @param color The background color to use for the drawing cache's bitmap
10366     *
10367     * @see #setDrawingCacheEnabled(boolean)
10368     * @see #buildDrawingCache()
10369     * @see #getDrawingCache()
10370     */
10371    public void setDrawingCacheBackgroundColor(int color) {
10372        if (color != mDrawingCacheBackgroundColor) {
10373            mDrawingCacheBackgroundColor = color;
10374            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10375        }
10376    }
10377
10378    /**
10379     * @see #setDrawingCacheBackgroundColor(int)
10380     *
10381     * @return The background color to used for the drawing cache's bitmap
10382     */
10383    public int getDrawingCacheBackgroundColor() {
10384        return mDrawingCacheBackgroundColor;
10385    }
10386
10387    /**
10388     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10389     *
10390     * @see #buildDrawingCache(boolean)
10391     */
10392    public void buildDrawingCache() {
10393        buildDrawingCache(false);
10394    }
10395
10396    /**
10397     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10398     *
10399     * <p>If you call {@link #buildDrawingCache()} manually without calling
10400     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10401     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10402     *
10403     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10404     * this method will create a bitmap of the same size as this view. Because this bitmap
10405     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10406     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10407     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10408     * size than the view. This implies that your application must be able to handle this
10409     * size.</p>
10410     *
10411     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10412     * you do not need the drawing cache bitmap, calling this method will increase memory
10413     * usage and cause the view to be rendered in software once, thus negatively impacting
10414     * performance.</p>
10415     *
10416     * @see #getDrawingCache()
10417     * @see #destroyDrawingCache()
10418     */
10419    public void buildDrawingCache(boolean autoScale) {
10420        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10421                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10422            mCachingFailed = false;
10423
10424            if (ViewDebug.TRACE_HIERARCHY) {
10425                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10426            }
10427
10428            int width = mRight - mLeft;
10429            int height = mBottom - mTop;
10430
10431            final AttachInfo attachInfo = mAttachInfo;
10432            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10433
10434            if (autoScale && scalingRequired) {
10435                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10436                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10437            }
10438
10439            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10440            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10441            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10442
10443            if (width <= 0 || height <= 0 ||
10444                     // Projected bitmap size in bytes
10445                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10446                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10447                destroyDrawingCache();
10448                mCachingFailed = true;
10449                return;
10450            }
10451
10452            boolean clear = true;
10453            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10454
10455            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10456                Bitmap.Config quality;
10457                if (!opaque) {
10458                    // Never pick ARGB_4444 because it looks awful
10459                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10460                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10461                        case DRAWING_CACHE_QUALITY_AUTO:
10462                            quality = Bitmap.Config.ARGB_8888;
10463                            break;
10464                        case DRAWING_CACHE_QUALITY_LOW:
10465                            quality = Bitmap.Config.ARGB_8888;
10466                            break;
10467                        case DRAWING_CACHE_QUALITY_HIGH:
10468                            quality = Bitmap.Config.ARGB_8888;
10469                            break;
10470                        default:
10471                            quality = Bitmap.Config.ARGB_8888;
10472                            break;
10473                    }
10474                } else {
10475                    // Optimization for translucent windows
10476                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10477                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10478                }
10479
10480                // Try to cleanup memory
10481                if (bitmap != null) bitmap.recycle();
10482
10483                try {
10484                    bitmap = Bitmap.createBitmap(width, height, quality);
10485                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10486                    if (autoScale) {
10487                        mDrawingCache = bitmap;
10488                    } else {
10489                        mUnscaledDrawingCache = bitmap;
10490                    }
10491                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10492                } catch (OutOfMemoryError e) {
10493                    // If there is not enough memory to create the bitmap cache, just
10494                    // ignore the issue as bitmap caches are not required to draw the
10495                    // view hierarchy
10496                    if (autoScale) {
10497                        mDrawingCache = null;
10498                    } else {
10499                        mUnscaledDrawingCache = null;
10500                    }
10501                    mCachingFailed = true;
10502                    return;
10503                }
10504
10505                clear = drawingCacheBackgroundColor != 0;
10506            }
10507
10508            Canvas canvas;
10509            if (attachInfo != null) {
10510                canvas = attachInfo.mCanvas;
10511                if (canvas == null) {
10512                    canvas = new Canvas();
10513                }
10514                canvas.setBitmap(bitmap);
10515                // Temporarily clobber the cached Canvas in case one of our children
10516                // is also using a drawing cache. Without this, the children would
10517                // steal the canvas by attaching their own bitmap to it and bad, bad
10518                // thing would happen (invisible views, corrupted drawings, etc.)
10519                attachInfo.mCanvas = null;
10520            } else {
10521                // This case should hopefully never or seldom happen
10522                canvas = new Canvas(bitmap);
10523            }
10524
10525            if (clear) {
10526                bitmap.eraseColor(drawingCacheBackgroundColor);
10527            }
10528
10529            computeScroll();
10530            final int restoreCount = canvas.save();
10531
10532            if (autoScale && scalingRequired) {
10533                final float scale = attachInfo.mApplicationScale;
10534                canvas.scale(scale, scale);
10535            }
10536
10537            canvas.translate(-mScrollX, -mScrollY);
10538
10539            mPrivateFlags |= DRAWN;
10540            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10541                    mLayerType != LAYER_TYPE_NONE) {
10542                mPrivateFlags |= DRAWING_CACHE_VALID;
10543            }
10544
10545            // Fast path for layouts with no backgrounds
10546            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10547                if (ViewDebug.TRACE_HIERARCHY) {
10548                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10549                }
10550                mPrivateFlags &= ~DIRTY_MASK;
10551                dispatchDraw(canvas);
10552            } else {
10553                draw(canvas);
10554            }
10555
10556            canvas.restoreToCount(restoreCount);
10557            canvas.setBitmap(null);
10558
10559            if (attachInfo != null) {
10560                // Restore the cached Canvas for our siblings
10561                attachInfo.mCanvas = canvas;
10562            }
10563        }
10564    }
10565
10566    /**
10567     * Create a snapshot of the view into a bitmap.  We should probably make
10568     * some form of this public, but should think about the API.
10569     */
10570    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10571        int width = mRight - mLeft;
10572        int height = mBottom - mTop;
10573
10574        final AttachInfo attachInfo = mAttachInfo;
10575        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10576        width = (int) ((width * scale) + 0.5f);
10577        height = (int) ((height * scale) + 0.5f);
10578
10579        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10580        if (bitmap == null) {
10581            throw new OutOfMemoryError();
10582        }
10583
10584        Resources resources = getResources();
10585        if (resources != null) {
10586            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10587        }
10588
10589        Canvas canvas;
10590        if (attachInfo != null) {
10591            canvas = attachInfo.mCanvas;
10592            if (canvas == null) {
10593                canvas = new Canvas();
10594            }
10595            canvas.setBitmap(bitmap);
10596            // Temporarily clobber the cached Canvas in case one of our children
10597            // is also using a drawing cache. Without this, the children would
10598            // steal the canvas by attaching their own bitmap to it and bad, bad
10599            // things would happen (invisible views, corrupted drawings, etc.)
10600            attachInfo.mCanvas = null;
10601        } else {
10602            // This case should hopefully never or seldom happen
10603            canvas = new Canvas(bitmap);
10604        }
10605
10606        if ((backgroundColor & 0xff000000) != 0) {
10607            bitmap.eraseColor(backgroundColor);
10608        }
10609
10610        computeScroll();
10611        final int restoreCount = canvas.save();
10612        canvas.scale(scale, scale);
10613        canvas.translate(-mScrollX, -mScrollY);
10614
10615        // Temporarily remove the dirty mask
10616        int flags = mPrivateFlags;
10617        mPrivateFlags &= ~DIRTY_MASK;
10618
10619        // Fast path for layouts with no backgrounds
10620        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10621            dispatchDraw(canvas);
10622        } else {
10623            draw(canvas);
10624        }
10625
10626        mPrivateFlags = flags;
10627
10628        canvas.restoreToCount(restoreCount);
10629        canvas.setBitmap(null);
10630
10631        if (attachInfo != null) {
10632            // Restore the cached Canvas for our siblings
10633            attachInfo.mCanvas = canvas;
10634        }
10635
10636        return bitmap;
10637    }
10638
10639    /**
10640     * Indicates whether this View is currently in edit mode. A View is usually
10641     * in edit mode when displayed within a developer tool. For instance, if
10642     * this View is being drawn by a visual user interface builder, this method
10643     * should return true.
10644     *
10645     * Subclasses should check the return value of this method to provide
10646     * different behaviors if their normal behavior might interfere with the
10647     * host environment. For instance: the class spawns a thread in its
10648     * constructor, the drawing code relies on device-specific features, etc.
10649     *
10650     * This method is usually checked in the drawing code of custom widgets.
10651     *
10652     * @return True if this View is in edit mode, false otherwise.
10653     */
10654    public boolean isInEditMode() {
10655        return false;
10656    }
10657
10658    /**
10659     * If the View draws content inside its padding and enables fading edges,
10660     * it needs to support padding offsets. Padding offsets are added to the
10661     * fading edges to extend the length of the fade so that it covers pixels
10662     * drawn inside the padding.
10663     *
10664     * Subclasses of this class should override this method if they need
10665     * to draw content inside the padding.
10666     *
10667     * @return True if padding offset must be applied, false otherwise.
10668     *
10669     * @see #getLeftPaddingOffset()
10670     * @see #getRightPaddingOffset()
10671     * @see #getTopPaddingOffset()
10672     * @see #getBottomPaddingOffset()
10673     *
10674     * @since CURRENT
10675     */
10676    protected boolean isPaddingOffsetRequired() {
10677        return false;
10678    }
10679
10680    /**
10681     * Amount by which to extend the left fading region. Called only when
10682     * {@link #isPaddingOffsetRequired()} returns true.
10683     *
10684     * @return The left padding offset in pixels.
10685     *
10686     * @see #isPaddingOffsetRequired()
10687     *
10688     * @since CURRENT
10689     */
10690    protected int getLeftPaddingOffset() {
10691        return 0;
10692    }
10693
10694    /**
10695     * Amount by which to extend the right fading region. Called only when
10696     * {@link #isPaddingOffsetRequired()} returns true.
10697     *
10698     * @return The right padding offset in pixels.
10699     *
10700     * @see #isPaddingOffsetRequired()
10701     *
10702     * @since CURRENT
10703     */
10704    protected int getRightPaddingOffset() {
10705        return 0;
10706    }
10707
10708    /**
10709     * Amount by which to extend the top fading region. Called only when
10710     * {@link #isPaddingOffsetRequired()} returns true.
10711     *
10712     * @return The top padding offset in pixels.
10713     *
10714     * @see #isPaddingOffsetRequired()
10715     *
10716     * @since CURRENT
10717     */
10718    protected int getTopPaddingOffset() {
10719        return 0;
10720    }
10721
10722    /**
10723     * Amount by which to extend the bottom fading region. Called only when
10724     * {@link #isPaddingOffsetRequired()} returns true.
10725     *
10726     * @return The bottom padding offset in pixels.
10727     *
10728     * @see #isPaddingOffsetRequired()
10729     *
10730     * @since CURRENT
10731     */
10732    protected int getBottomPaddingOffset() {
10733        return 0;
10734    }
10735
10736    /**
10737     * @hide
10738     * @param offsetRequired
10739     */
10740    protected int getFadeTop(boolean offsetRequired) {
10741        int top = mPaddingTop;
10742        if (offsetRequired) top += getTopPaddingOffset();
10743        return top;
10744    }
10745
10746    /**
10747     * @hide
10748     * @param offsetRequired
10749     */
10750    protected int getFadeHeight(boolean offsetRequired) {
10751        int padding = mPaddingTop;
10752        if (offsetRequired) padding += getTopPaddingOffset();
10753        return mBottom - mTop - mPaddingBottom - padding;
10754    }
10755
10756    /**
10757     * <p>Indicates whether this view is attached to an hardware accelerated
10758     * window or not.</p>
10759     *
10760     * <p>Even if this method returns true, it does not mean that every call
10761     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10762     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10763     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10764     * window is hardware accelerated,
10765     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10766     * return false, and this method will return true.</p>
10767     *
10768     * @return True if the view is attached to a window and the window is
10769     *         hardware accelerated; false in any other case.
10770     */
10771    public boolean isHardwareAccelerated() {
10772        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10773    }
10774
10775    /**
10776     * Manually render this view (and all of its children) to the given Canvas.
10777     * The view must have already done a full layout before this function is
10778     * called.  When implementing a view, implement
10779     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
10780     * If you do need to override this method, call the superclass version.
10781     *
10782     * @param canvas The Canvas to which the View is rendered.
10783     */
10784    public void draw(Canvas canvas) {
10785        if (ViewDebug.TRACE_HIERARCHY) {
10786            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10787        }
10788
10789        final int privateFlags = mPrivateFlags;
10790        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
10791                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
10792        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
10793
10794        /*
10795         * Draw traversal performs several drawing steps which must be executed
10796         * in the appropriate order:
10797         *
10798         *      1. Draw the background
10799         *      2. If necessary, save the canvas' layers to prepare for fading
10800         *      3. Draw view's content
10801         *      4. Draw children
10802         *      5. If necessary, draw the fading edges and restore layers
10803         *      6. Draw decorations (scrollbars for instance)
10804         */
10805
10806        // Step 1, draw the background, if needed
10807        int saveCount;
10808
10809        if (!dirtyOpaque) {
10810            final Drawable background = mBGDrawable;
10811            if (background != null) {
10812                final int scrollX = mScrollX;
10813                final int scrollY = mScrollY;
10814
10815                if (mBackgroundSizeChanged) {
10816                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
10817                    mBackgroundSizeChanged = false;
10818                }
10819
10820                if ((scrollX | scrollY) == 0) {
10821                    background.draw(canvas);
10822                } else {
10823                    canvas.translate(scrollX, scrollY);
10824                    background.draw(canvas);
10825                    canvas.translate(-scrollX, -scrollY);
10826                }
10827            }
10828        }
10829
10830        // skip step 2 & 5 if possible (common case)
10831        final int viewFlags = mViewFlags;
10832        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
10833        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
10834        if (!verticalEdges && !horizontalEdges) {
10835            // Step 3, draw the content
10836            if (!dirtyOpaque) onDraw(canvas);
10837
10838            // Step 4, draw the children
10839            dispatchDraw(canvas);
10840
10841            // Step 6, draw decorations (scrollbars)
10842            onDrawScrollBars(canvas);
10843
10844            // we're done...
10845            return;
10846        }
10847
10848        /*
10849         * Here we do the full fledged routine...
10850         * (this is an uncommon case where speed matters less,
10851         * this is why we repeat some of the tests that have been
10852         * done above)
10853         */
10854
10855        boolean drawTop = false;
10856        boolean drawBottom = false;
10857        boolean drawLeft = false;
10858        boolean drawRight = false;
10859
10860        float topFadeStrength = 0.0f;
10861        float bottomFadeStrength = 0.0f;
10862        float leftFadeStrength = 0.0f;
10863        float rightFadeStrength = 0.0f;
10864
10865        // Step 2, save the canvas' layers
10866        int paddingLeft = mPaddingLeft;
10867
10868        final boolean offsetRequired = isPaddingOffsetRequired();
10869        if (offsetRequired) {
10870            paddingLeft += getLeftPaddingOffset();
10871        }
10872
10873        int left = mScrollX + paddingLeft;
10874        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
10875        int top = mScrollY + getFadeTop(offsetRequired);
10876        int bottom = top + getFadeHeight(offsetRequired);
10877
10878        if (offsetRequired) {
10879            right += getRightPaddingOffset();
10880            bottom += getBottomPaddingOffset();
10881        }
10882
10883        final ScrollabilityCache scrollabilityCache = mScrollCache;
10884        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
10885        int length = (int) fadeHeight;
10886
10887        // clip the fade length if top and bottom fades overlap
10888        // overlapping fades produce odd-looking artifacts
10889        if (verticalEdges && (top + length > bottom - length)) {
10890            length = (bottom - top) / 2;
10891        }
10892
10893        // also clip horizontal fades if necessary
10894        if (horizontalEdges && (left + length > right - length)) {
10895            length = (right - left) / 2;
10896        }
10897
10898        if (verticalEdges) {
10899            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
10900            drawTop = topFadeStrength * fadeHeight > 1.0f;
10901            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
10902            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
10903        }
10904
10905        if (horizontalEdges) {
10906            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
10907            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
10908            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
10909            drawRight = rightFadeStrength * fadeHeight > 1.0f;
10910        }
10911
10912        saveCount = canvas.getSaveCount();
10913
10914        int solidColor = getSolidColor();
10915        if (solidColor == 0) {
10916            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
10917
10918            if (drawTop) {
10919                canvas.saveLayer(left, top, right, top + length, null, flags);
10920            }
10921
10922            if (drawBottom) {
10923                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
10924            }
10925
10926            if (drawLeft) {
10927                canvas.saveLayer(left, top, left + length, bottom, null, flags);
10928            }
10929
10930            if (drawRight) {
10931                canvas.saveLayer(right - length, top, right, bottom, null, flags);
10932            }
10933        } else {
10934            scrollabilityCache.setFadeColor(solidColor);
10935        }
10936
10937        // Step 3, draw the content
10938        if (!dirtyOpaque) onDraw(canvas);
10939
10940        // Step 4, draw the children
10941        dispatchDraw(canvas);
10942
10943        // Step 5, draw the fade effect and restore layers
10944        final Paint p = scrollabilityCache.paint;
10945        final Matrix matrix = scrollabilityCache.matrix;
10946        final Shader fade = scrollabilityCache.shader;
10947
10948        if (drawTop) {
10949            matrix.setScale(1, fadeHeight * topFadeStrength);
10950            matrix.postTranslate(left, top);
10951            fade.setLocalMatrix(matrix);
10952            canvas.drawRect(left, top, right, top + length, p);
10953        }
10954
10955        if (drawBottom) {
10956            matrix.setScale(1, fadeHeight * bottomFadeStrength);
10957            matrix.postRotate(180);
10958            matrix.postTranslate(left, bottom);
10959            fade.setLocalMatrix(matrix);
10960            canvas.drawRect(left, bottom - length, right, bottom, p);
10961        }
10962
10963        if (drawLeft) {
10964            matrix.setScale(1, fadeHeight * leftFadeStrength);
10965            matrix.postRotate(-90);
10966            matrix.postTranslate(left, top);
10967            fade.setLocalMatrix(matrix);
10968            canvas.drawRect(left, top, left + length, bottom, p);
10969        }
10970
10971        if (drawRight) {
10972            matrix.setScale(1, fadeHeight * rightFadeStrength);
10973            matrix.postRotate(90);
10974            matrix.postTranslate(right, top);
10975            fade.setLocalMatrix(matrix);
10976            canvas.drawRect(right - length, top, right, bottom, p);
10977        }
10978
10979        canvas.restoreToCount(saveCount);
10980
10981        // Step 6, draw decorations (scrollbars)
10982        onDrawScrollBars(canvas);
10983    }
10984
10985    /**
10986     * Override this if your view is known to always be drawn on top of a solid color background,
10987     * and needs to draw fading edges. Returning a non-zero color enables the view system to
10988     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
10989     * should be set to 0xFF.
10990     *
10991     * @see #setVerticalFadingEdgeEnabled(boolean)
10992     * @see #setHorizontalFadingEdgeEnabled(boolean)
10993     *
10994     * @return The known solid color background for this view, or 0 if the color may vary
10995     */
10996    @ViewDebug.ExportedProperty(category = "drawing")
10997    public int getSolidColor() {
10998        return 0;
10999    }
11000
11001    /**
11002     * Build a human readable string representation of the specified view flags.
11003     *
11004     * @param flags the view flags to convert to a string
11005     * @return a String representing the supplied flags
11006     */
11007    private static String printFlags(int flags) {
11008        String output = "";
11009        int numFlags = 0;
11010        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11011            output += "TAKES_FOCUS";
11012            numFlags++;
11013        }
11014
11015        switch (flags & VISIBILITY_MASK) {
11016        case INVISIBLE:
11017            if (numFlags > 0) {
11018                output += " ";
11019            }
11020            output += "INVISIBLE";
11021            // USELESS HERE numFlags++;
11022            break;
11023        case GONE:
11024            if (numFlags > 0) {
11025                output += " ";
11026            }
11027            output += "GONE";
11028            // USELESS HERE numFlags++;
11029            break;
11030        default:
11031            break;
11032        }
11033        return output;
11034    }
11035
11036    /**
11037     * Build a human readable string representation of the specified private
11038     * view flags.
11039     *
11040     * @param privateFlags the private view flags to convert to a string
11041     * @return a String representing the supplied flags
11042     */
11043    private static String printPrivateFlags(int privateFlags) {
11044        String output = "";
11045        int numFlags = 0;
11046
11047        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11048            output += "WANTS_FOCUS";
11049            numFlags++;
11050        }
11051
11052        if ((privateFlags & FOCUSED) == FOCUSED) {
11053            if (numFlags > 0) {
11054                output += " ";
11055            }
11056            output += "FOCUSED";
11057            numFlags++;
11058        }
11059
11060        if ((privateFlags & SELECTED) == SELECTED) {
11061            if (numFlags > 0) {
11062                output += " ";
11063            }
11064            output += "SELECTED";
11065            numFlags++;
11066        }
11067
11068        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11069            if (numFlags > 0) {
11070                output += " ";
11071            }
11072            output += "IS_ROOT_NAMESPACE";
11073            numFlags++;
11074        }
11075
11076        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11077            if (numFlags > 0) {
11078                output += " ";
11079            }
11080            output += "HAS_BOUNDS";
11081            numFlags++;
11082        }
11083
11084        if ((privateFlags & DRAWN) == DRAWN) {
11085            if (numFlags > 0) {
11086                output += " ";
11087            }
11088            output += "DRAWN";
11089            // USELESS HERE numFlags++;
11090        }
11091        return output;
11092    }
11093
11094    /**
11095     * <p>Indicates whether or not this view's layout will be requested during
11096     * the next hierarchy layout pass.</p>
11097     *
11098     * @return true if the layout will be forced during next layout pass
11099     */
11100    public boolean isLayoutRequested() {
11101        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11102    }
11103
11104    /**
11105     * Assign a size and position to a view and all of its
11106     * descendants
11107     *
11108     * <p>This is the second phase of the layout mechanism.
11109     * (The first is measuring). In this phase, each parent calls
11110     * layout on all of its children to position them.
11111     * This is typically done using the child measurements
11112     * that were stored in the measure pass().</p>
11113     *
11114     * <p>Derived classes should not override this method.
11115     * Derived classes with children should override
11116     * onLayout. In that method, they should
11117     * call layout on each of their children.</p>
11118     *
11119     * @param l Left position, relative to parent
11120     * @param t Top position, relative to parent
11121     * @param r Right position, relative to parent
11122     * @param b Bottom position, relative to parent
11123     */
11124    @SuppressWarnings({"unchecked"})
11125    public void layout(int l, int t, int r, int b) {
11126        int oldL = mLeft;
11127        int oldT = mTop;
11128        int oldB = mBottom;
11129        int oldR = mRight;
11130        boolean changed = setFrame(l, t, r, b);
11131        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11132            if (ViewDebug.TRACE_HIERARCHY) {
11133                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11134            }
11135
11136            onLayout(changed, l, t, r, b);
11137            mPrivateFlags &= ~LAYOUT_REQUIRED;
11138
11139            if (mOnLayoutChangeListeners != null) {
11140                ArrayList<OnLayoutChangeListener> listenersCopy =
11141                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
11142                int numListeners = listenersCopy.size();
11143                for (int i = 0; i < numListeners; ++i) {
11144                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11145                }
11146            }
11147        }
11148        mPrivateFlags &= ~FORCE_LAYOUT;
11149    }
11150
11151    /**
11152     * Called from layout when this view should
11153     * assign a size and position to each of its children.
11154     *
11155     * Derived classes with children should override
11156     * this method and call layout on each of
11157     * their children.
11158     * @param changed This is a new size or position for this view
11159     * @param left Left position, relative to parent
11160     * @param top Top position, relative to parent
11161     * @param right Right position, relative to parent
11162     * @param bottom Bottom position, relative to parent
11163     */
11164    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11165    }
11166
11167    /**
11168     * Assign a size and position to this view.
11169     *
11170     * This is called from layout.
11171     *
11172     * @param left Left position, relative to parent
11173     * @param top Top position, relative to parent
11174     * @param right Right position, relative to parent
11175     * @param bottom Bottom position, relative to parent
11176     * @return true if the new size and position are different than the
11177     *         previous ones
11178     * {@hide}
11179     */
11180    protected boolean setFrame(int left, int top, int right, int bottom) {
11181        boolean changed = false;
11182
11183        if (DBG) {
11184            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11185                    + right + "," + bottom + ")");
11186        }
11187
11188        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11189            changed = true;
11190
11191            // Remember our drawn bit
11192            int drawn = mPrivateFlags & DRAWN;
11193
11194            int oldWidth = mRight - mLeft;
11195            int oldHeight = mBottom - mTop;
11196            int newWidth = right - left;
11197            int newHeight = bottom - top;
11198            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11199
11200            // Invalidate our old position
11201            invalidate(sizeChanged);
11202
11203            mLeft = left;
11204            mTop = top;
11205            mRight = right;
11206            mBottom = bottom;
11207
11208            mPrivateFlags |= HAS_BOUNDS;
11209
11210
11211            if (sizeChanged) {
11212                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11213                    // A change in dimension means an auto-centered pivot point changes, too
11214                    if (mTransformationInfo != null) {
11215                        mTransformationInfo.mMatrixDirty = true;
11216                    }
11217                }
11218                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11219            }
11220
11221            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11222                // If we are visible, force the DRAWN bit to on so that
11223                // this invalidate will go through (at least to our parent).
11224                // This is because someone may have invalidated this view
11225                // before this call to setFrame came in, thereby clearing
11226                // the DRAWN bit.
11227                mPrivateFlags |= DRAWN;
11228                invalidate(sizeChanged);
11229                // parent display list may need to be recreated based on a change in the bounds
11230                // of any child
11231                invalidateParentCaches();
11232            }
11233
11234            // Reset drawn bit to original value (invalidate turns it off)
11235            mPrivateFlags |= drawn;
11236
11237            mBackgroundSizeChanged = true;
11238        }
11239        return changed;
11240    }
11241
11242    /**
11243     * Finalize inflating a view from XML.  This is called as the last phase
11244     * of inflation, after all child views have been added.
11245     *
11246     * <p>Even if the subclass overrides onFinishInflate, they should always be
11247     * sure to call the super method, so that we get called.
11248     */
11249    protected void onFinishInflate() {
11250    }
11251
11252    /**
11253     * Returns the resources associated with this view.
11254     *
11255     * @return Resources object.
11256     */
11257    public Resources getResources() {
11258        return mResources;
11259    }
11260
11261    /**
11262     * Invalidates the specified Drawable.
11263     *
11264     * @param drawable the drawable to invalidate
11265     */
11266    public void invalidateDrawable(Drawable drawable) {
11267        if (verifyDrawable(drawable)) {
11268            final Rect dirty = drawable.getBounds();
11269            final int scrollX = mScrollX;
11270            final int scrollY = mScrollY;
11271
11272            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11273                    dirty.right + scrollX, dirty.bottom + scrollY);
11274        }
11275    }
11276
11277    /**
11278     * Schedules an action on a drawable to occur at a specified time.
11279     *
11280     * @param who the recipient of the action
11281     * @param what the action to run on the drawable
11282     * @param when the time at which the action must occur. Uses the
11283     *        {@link SystemClock#uptimeMillis} timebase.
11284     */
11285    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11286        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11287            mAttachInfo.mHandler.postAtTime(what, who, when);
11288        }
11289    }
11290
11291    /**
11292     * Cancels a scheduled action on a drawable.
11293     *
11294     * @param who the recipient of the action
11295     * @param what the action to cancel
11296     */
11297    public void unscheduleDrawable(Drawable who, Runnable what) {
11298        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11299            mAttachInfo.mHandler.removeCallbacks(what, who);
11300        }
11301    }
11302
11303    /**
11304     * Unschedule any events associated with the given Drawable.  This can be
11305     * used when selecting a new Drawable into a view, so that the previous
11306     * one is completely unscheduled.
11307     *
11308     * @param who The Drawable to unschedule.
11309     *
11310     * @see #drawableStateChanged
11311     */
11312    public void unscheduleDrawable(Drawable who) {
11313        if (mAttachInfo != null) {
11314            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11315        }
11316    }
11317
11318    /**
11319    * Return the layout direction of a given Drawable.
11320    *
11321    * @param who the Drawable to query
11322    *
11323    * @hide
11324    */
11325    public int getResolvedLayoutDirection(Drawable who) {
11326        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11327    }
11328
11329    /**
11330     * If your view subclass is displaying its own Drawable objects, it should
11331     * override this function and return true for any Drawable it is
11332     * displaying.  This allows animations for those drawables to be
11333     * scheduled.
11334     *
11335     * <p>Be sure to call through to the super class when overriding this
11336     * function.
11337     *
11338     * @param who The Drawable to verify.  Return true if it is one you are
11339     *            displaying, else return the result of calling through to the
11340     *            super class.
11341     *
11342     * @return boolean If true than the Drawable is being displayed in the
11343     *         view; else false and it is not allowed to animate.
11344     *
11345     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11346     * @see #drawableStateChanged()
11347     */
11348    protected boolean verifyDrawable(Drawable who) {
11349        return who == mBGDrawable;
11350    }
11351
11352    /**
11353     * This function is called whenever the state of the view changes in such
11354     * a way that it impacts the state of drawables being shown.
11355     *
11356     * <p>Be sure to call through to the superclass when overriding this
11357     * function.
11358     *
11359     * @see Drawable#setState(int[])
11360     */
11361    protected void drawableStateChanged() {
11362        Drawable d = mBGDrawable;
11363        if (d != null && d.isStateful()) {
11364            d.setState(getDrawableState());
11365        }
11366    }
11367
11368    /**
11369     * Call this to force a view to update its drawable state. This will cause
11370     * drawableStateChanged to be called on this view. Views that are interested
11371     * in the new state should call getDrawableState.
11372     *
11373     * @see #drawableStateChanged
11374     * @see #getDrawableState
11375     */
11376    public void refreshDrawableState() {
11377        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11378        drawableStateChanged();
11379
11380        ViewParent parent = mParent;
11381        if (parent != null) {
11382            parent.childDrawableStateChanged(this);
11383        }
11384    }
11385
11386    /**
11387     * Return an array of resource IDs of the drawable states representing the
11388     * current state of the view.
11389     *
11390     * @return The current drawable state
11391     *
11392     * @see Drawable#setState(int[])
11393     * @see #drawableStateChanged()
11394     * @see #onCreateDrawableState(int)
11395     */
11396    public final int[] getDrawableState() {
11397        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11398            return mDrawableState;
11399        } else {
11400            mDrawableState = onCreateDrawableState(0);
11401            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11402            return mDrawableState;
11403        }
11404    }
11405
11406    /**
11407     * Generate the new {@link android.graphics.drawable.Drawable} state for
11408     * this view. This is called by the view
11409     * system when the cached Drawable state is determined to be invalid.  To
11410     * retrieve the current state, you should use {@link #getDrawableState}.
11411     *
11412     * @param extraSpace if non-zero, this is the number of extra entries you
11413     * would like in the returned array in which you can place your own
11414     * states.
11415     *
11416     * @return Returns an array holding the current {@link Drawable} state of
11417     * the view.
11418     *
11419     * @see #mergeDrawableStates(int[], int[])
11420     */
11421    protected int[] onCreateDrawableState(int extraSpace) {
11422        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11423                mParent instanceof View) {
11424            return ((View) mParent).onCreateDrawableState(extraSpace);
11425        }
11426
11427        int[] drawableState;
11428
11429        int privateFlags = mPrivateFlags;
11430
11431        int viewStateIndex = 0;
11432        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11433        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11434        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11435        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11436        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11437        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11438        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11439                HardwareRenderer.isAvailable()) {
11440            // This is set if HW acceleration is requested, even if the current
11441            // process doesn't allow it.  This is just to allow app preview
11442            // windows to better match their app.
11443            viewStateIndex |= VIEW_STATE_ACCELERATED;
11444        }
11445        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11446
11447        final int privateFlags2 = mPrivateFlags2;
11448        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11449        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11450
11451        drawableState = VIEW_STATE_SETS[viewStateIndex];
11452
11453        //noinspection ConstantIfStatement
11454        if (false) {
11455            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11456            Log.i("View", toString()
11457                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11458                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11459                    + " fo=" + hasFocus()
11460                    + " sl=" + ((privateFlags & SELECTED) != 0)
11461                    + " wf=" + hasWindowFocus()
11462                    + ": " + Arrays.toString(drawableState));
11463        }
11464
11465        if (extraSpace == 0) {
11466            return drawableState;
11467        }
11468
11469        final int[] fullState;
11470        if (drawableState != null) {
11471            fullState = new int[drawableState.length + extraSpace];
11472            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11473        } else {
11474            fullState = new int[extraSpace];
11475        }
11476
11477        return fullState;
11478    }
11479
11480    /**
11481     * Merge your own state values in <var>additionalState</var> into the base
11482     * state values <var>baseState</var> that were returned by
11483     * {@link #onCreateDrawableState(int)}.
11484     *
11485     * @param baseState The base state values returned by
11486     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11487     * own additional state values.
11488     *
11489     * @param additionalState The additional state values you would like
11490     * added to <var>baseState</var>; this array is not modified.
11491     *
11492     * @return As a convenience, the <var>baseState</var> array you originally
11493     * passed into the function is returned.
11494     *
11495     * @see #onCreateDrawableState(int)
11496     */
11497    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11498        final int N = baseState.length;
11499        int i = N - 1;
11500        while (i >= 0 && baseState[i] == 0) {
11501            i--;
11502        }
11503        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11504        return baseState;
11505    }
11506
11507    /**
11508     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
11509     * on all Drawable objects associated with this view.
11510     */
11511    public void jumpDrawablesToCurrentState() {
11512        if (mBGDrawable != null) {
11513            mBGDrawable.jumpToCurrentState();
11514        }
11515    }
11516
11517    /**
11518     * Sets the background color for this view.
11519     * @param color the color of the background
11520     */
11521    @RemotableViewMethod
11522    public void setBackgroundColor(int color) {
11523        if (mBGDrawable instanceof ColorDrawable) {
11524            ((ColorDrawable) mBGDrawable).setColor(color);
11525        } else {
11526            setBackgroundDrawable(new ColorDrawable(color));
11527        }
11528    }
11529
11530    /**
11531     * Set the background to a given resource. The resource should refer to
11532     * a Drawable object or 0 to remove the background.
11533     * @param resid The identifier of the resource.
11534     * @attr ref android.R.styleable#View_background
11535     */
11536    @RemotableViewMethod
11537    public void setBackgroundResource(int resid) {
11538        if (resid != 0 && resid == mBackgroundResource) {
11539            return;
11540        }
11541
11542        Drawable d= null;
11543        if (resid != 0) {
11544            d = mResources.getDrawable(resid);
11545        }
11546        setBackgroundDrawable(d);
11547
11548        mBackgroundResource = resid;
11549    }
11550
11551    /**
11552     * Set the background to a given Drawable, or remove the background. If the
11553     * background has padding, this View's padding is set to the background's
11554     * padding. However, when a background is removed, this View's padding isn't
11555     * touched. If setting the padding is desired, please use
11556     * {@link #setPadding(int, int, int, int)}.
11557     *
11558     * @param d The Drawable to use as the background, or null to remove the
11559     *        background
11560     */
11561    public void setBackgroundDrawable(Drawable d) {
11562        if (d == mBGDrawable) {
11563            return;
11564        }
11565
11566        boolean requestLayout = false;
11567
11568        mBackgroundResource = 0;
11569
11570        /*
11571         * Regardless of whether we're setting a new background or not, we want
11572         * to clear the previous drawable.
11573         */
11574        if (mBGDrawable != null) {
11575            mBGDrawable.setCallback(null);
11576            unscheduleDrawable(mBGDrawable);
11577        }
11578
11579        if (d != null) {
11580            Rect padding = sThreadLocal.get();
11581            if (padding == null) {
11582                padding = new Rect();
11583                sThreadLocal.set(padding);
11584            }
11585            if (d.getPadding(padding)) {
11586                switch (d.getResolvedLayoutDirectionSelf()) {
11587                    case LAYOUT_DIRECTION_RTL:
11588                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
11589                        break;
11590                    case LAYOUT_DIRECTION_LTR:
11591                    default:
11592                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
11593                }
11594            }
11595
11596            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
11597            // if it has a different minimum size, we should layout again
11598            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
11599                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
11600                requestLayout = true;
11601            }
11602
11603            d.setCallback(this);
11604            if (d.isStateful()) {
11605                d.setState(getDrawableState());
11606            }
11607            d.setVisible(getVisibility() == VISIBLE, false);
11608            mBGDrawable = d;
11609
11610            if ((mPrivateFlags & SKIP_DRAW) != 0) {
11611                mPrivateFlags &= ~SKIP_DRAW;
11612                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
11613                requestLayout = true;
11614            }
11615        } else {
11616            /* Remove the background */
11617            mBGDrawable = null;
11618
11619            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
11620                /*
11621                 * This view ONLY drew the background before and we're removing
11622                 * the background, so now it won't draw anything
11623                 * (hence we SKIP_DRAW)
11624                 */
11625                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
11626                mPrivateFlags |= SKIP_DRAW;
11627            }
11628
11629            /*
11630             * When the background is set, we try to apply its padding to this
11631             * View. When the background is removed, we don't touch this View's
11632             * padding. This is noted in the Javadocs. Hence, we don't need to
11633             * requestLayout(), the invalidate() below is sufficient.
11634             */
11635
11636            // The old background's minimum size could have affected this
11637            // View's layout, so let's requestLayout
11638            requestLayout = true;
11639        }
11640
11641        computeOpaqueFlags();
11642
11643        if (requestLayout) {
11644            requestLayout();
11645        }
11646
11647        mBackgroundSizeChanged = true;
11648        invalidate(true);
11649    }
11650
11651    /**
11652     * Gets the background drawable
11653     * @return The drawable used as the background for this view, if any.
11654     */
11655    public Drawable getBackground() {
11656        return mBGDrawable;
11657    }
11658
11659    /**
11660     * Sets the padding. The view may add on the space required to display
11661     * the scrollbars, depending on the style and visibility of the scrollbars.
11662     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
11663     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
11664     * from the values set in this call.
11665     *
11666     * @attr ref android.R.styleable#View_padding
11667     * @attr ref android.R.styleable#View_paddingBottom
11668     * @attr ref android.R.styleable#View_paddingLeft
11669     * @attr ref android.R.styleable#View_paddingRight
11670     * @attr ref android.R.styleable#View_paddingTop
11671     * @param left the left padding in pixels
11672     * @param top the top padding in pixels
11673     * @param right the right padding in pixels
11674     * @param bottom the bottom padding in pixels
11675     */
11676    public void setPadding(int left, int top, int right, int bottom) {
11677        boolean changed = false;
11678
11679        mUserPaddingRelative = false;
11680
11681        mUserPaddingLeft = left;
11682        mUserPaddingRight = right;
11683        mUserPaddingBottom = bottom;
11684
11685        final int viewFlags = mViewFlags;
11686
11687        // Common case is there are no scroll bars.
11688        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
11689            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
11690                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
11691                        ? 0 : getVerticalScrollbarWidth();
11692                switch (mVerticalScrollbarPosition) {
11693                    case SCROLLBAR_POSITION_DEFAULT:
11694                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11695                            left += offset;
11696                        } else {
11697                            right += offset;
11698                        }
11699                        break;
11700                    case SCROLLBAR_POSITION_RIGHT:
11701                        right += offset;
11702                        break;
11703                    case SCROLLBAR_POSITION_LEFT:
11704                        left += offset;
11705                        break;
11706                }
11707            }
11708            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
11709                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
11710                        ? 0 : getHorizontalScrollbarHeight();
11711            }
11712        }
11713
11714        if (mPaddingLeft != left) {
11715            changed = true;
11716            mPaddingLeft = left;
11717        }
11718        if (mPaddingTop != top) {
11719            changed = true;
11720            mPaddingTop = top;
11721        }
11722        if (mPaddingRight != right) {
11723            changed = true;
11724            mPaddingRight = right;
11725        }
11726        if (mPaddingBottom != bottom) {
11727            changed = true;
11728            mPaddingBottom = bottom;
11729        }
11730
11731        if (changed) {
11732            requestLayout();
11733        }
11734    }
11735
11736    /**
11737     * Sets the relative padding. The view may add on the space required to display
11738     * the scrollbars, depending on the style and visibility of the scrollbars.
11739     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
11740     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
11741     * from the values set in this call.
11742     *
11743     * @attr ref android.R.styleable#View_padding
11744     * @attr ref android.R.styleable#View_paddingBottom
11745     * @attr ref android.R.styleable#View_paddingStart
11746     * @attr ref android.R.styleable#View_paddingEnd
11747     * @attr ref android.R.styleable#View_paddingTop
11748     * @param start the start padding in pixels
11749     * @param top the top padding in pixels
11750     * @param end the end padding in pixels
11751     * @param bottom the bottom padding in pixels
11752     *
11753     * @hide
11754     */
11755    public void setPaddingRelative(int start, int top, int end, int bottom) {
11756        mUserPaddingRelative = true;
11757
11758        mUserPaddingStart = start;
11759        mUserPaddingEnd = end;
11760
11761        switch(getResolvedLayoutDirection()) {
11762            case LAYOUT_DIRECTION_RTL:
11763                setPadding(end, top, start, bottom);
11764                break;
11765            case LAYOUT_DIRECTION_LTR:
11766            default:
11767                setPadding(start, top, end, bottom);
11768        }
11769    }
11770
11771    /**
11772     * Returns the top padding of this view.
11773     *
11774     * @return the top padding in pixels
11775     */
11776    public int getPaddingTop() {
11777        return mPaddingTop;
11778    }
11779
11780    /**
11781     * Returns the bottom padding of this view. If there are inset and enabled
11782     * scrollbars, this value may include the space required to display the
11783     * scrollbars as well.
11784     *
11785     * @return the bottom padding in pixels
11786     */
11787    public int getPaddingBottom() {
11788        return mPaddingBottom;
11789    }
11790
11791    /**
11792     * Returns the left padding of this view. If there are inset and enabled
11793     * scrollbars, this value may include the space required to display the
11794     * scrollbars as well.
11795     *
11796     * @return the left padding in pixels
11797     */
11798    public int getPaddingLeft() {
11799        return mPaddingLeft;
11800    }
11801
11802    /**
11803     * Returns the start padding of this view. If there are inset and enabled
11804     * scrollbars, this value may include the space required to display the
11805     * scrollbars as well.
11806     *
11807     * @return the start padding in pixels
11808     *
11809     * @hide
11810     */
11811    public int getPaddingStart() {
11812        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11813                mPaddingRight : mPaddingLeft;
11814    }
11815
11816    /**
11817     * Returns the right padding of this view. If there are inset and enabled
11818     * scrollbars, this value may include the space required to display the
11819     * scrollbars as well.
11820     *
11821     * @return the right padding in pixels
11822     */
11823    public int getPaddingRight() {
11824        return mPaddingRight;
11825    }
11826
11827    /**
11828     * Returns the end padding of this view. If there are inset and enabled
11829     * scrollbars, this value may include the space required to display the
11830     * scrollbars as well.
11831     *
11832     * @return the end padding in pixels
11833     *
11834     * @hide
11835     */
11836    public int getPaddingEnd() {
11837        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11838                mPaddingLeft : mPaddingRight;
11839    }
11840
11841    /**
11842     * Return if the padding as been set thru relative values
11843     * {@link #setPaddingRelative(int, int, int, int)} or thru
11844     * @attr ref android.R.styleable#View_paddingStart or
11845     * @attr ref android.R.styleable#View_paddingEnd
11846     *
11847     * @return true if the padding is relative or false if it is not.
11848     *
11849     * @hide
11850     */
11851    public boolean isPaddingRelative() {
11852        return mUserPaddingRelative;
11853    }
11854
11855    /**
11856     * Changes the selection state of this view. A view can be selected or not.
11857     * Note that selection is not the same as focus. Views are typically
11858     * selected in the context of an AdapterView like ListView or GridView;
11859     * the selected view is the view that is highlighted.
11860     *
11861     * @param selected true if the view must be selected, false otherwise
11862     */
11863    public void setSelected(boolean selected) {
11864        if (((mPrivateFlags & SELECTED) != 0) != selected) {
11865            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
11866            if (!selected) resetPressedState();
11867            invalidate(true);
11868            refreshDrawableState();
11869            dispatchSetSelected(selected);
11870        }
11871    }
11872
11873    /**
11874     * Dispatch setSelected to all of this View's children.
11875     *
11876     * @see #setSelected(boolean)
11877     *
11878     * @param selected The new selected state
11879     */
11880    protected void dispatchSetSelected(boolean selected) {
11881    }
11882
11883    /**
11884     * Indicates the selection state of this view.
11885     *
11886     * @return true if the view is selected, false otherwise
11887     */
11888    @ViewDebug.ExportedProperty
11889    public boolean isSelected() {
11890        return (mPrivateFlags & SELECTED) != 0;
11891    }
11892
11893    /**
11894     * Changes the activated state of this view. A view can be activated or not.
11895     * Note that activation is not the same as selection.  Selection is
11896     * a transient property, representing the view (hierarchy) the user is
11897     * currently interacting with.  Activation is a longer-term state that the
11898     * user can move views in and out of.  For example, in a list view with
11899     * single or multiple selection enabled, the views in the current selection
11900     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
11901     * here.)  The activated state is propagated down to children of the view it
11902     * is set on.
11903     *
11904     * @param activated true if the view must be activated, false otherwise
11905     */
11906    public void setActivated(boolean activated) {
11907        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
11908            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
11909            invalidate(true);
11910            refreshDrawableState();
11911            dispatchSetActivated(activated);
11912        }
11913    }
11914
11915    /**
11916     * Dispatch setActivated to all of this View's children.
11917     *
11918     * @see #setActivated(boolean)
11919     *
11920     * @param activated The new activated state
11921     */
11922    protected void dispatchSetActivated(boolean activated) {
11923    }
11924
11925    /**
11926     * Indicates the activation state of this view.
11927     *
11928     * @return true if the view is activated, false otherwise
11929     */
11930    @ViewDebug.ExportedProperty
11931    public boolean isActivated() {
11932        return (mPrivateFlags & ACTIVATED) != 0;
11933    }
11934
11935    /**
11936     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
11937     * observer can be used to get notifications when global events, like
11938     * layout, happen.
11939     *
11940     * The returned ViewTreeObserver observer is not guaranteed to remain
11941     * valid for the lifetime of this View. If the caller of this method keeps
11942     * a long-lived reference to ViewTreeObserver, it should always check for
11943     * the return value of {@link ViewTreeObserver#isAlive()}.
11944     *
11945     * @return The ViewTreeObserver for this view's hierarchy.
11946     */
11947    public ViewTreeObserver getViewTreeObserver() {
11948        if (mAttachInfo != null) {
11949            return mAttachInfo.mTreeObserver;
11950        }
11951        if (mFloatingTreeObserver == null) {
11952            mFloatingTreeObserver = new ViewTreeObserver();
11953        }
11954        return mFloatingTreeObserver;
11955    }
11956
11957    /**
11958     * <p>Finds the topmost view in the current view hierarchy.</p>
11959     *
11960     * @return the topmost view containing this view
11961     */
11962    public View getRootView() {
11963        if (mAttachInfo != null) {
11964            final View v = mAttachInfo.mRootView;
11965            if (v != null) {
11966                return v;
11967            }
11968        }
11969
11970        View parent = this;
11971
11972        while (parent.mParent != null && parent.mParent instanceof View) {
11973            parent = (View) parent.mParent;
11974        }
11975
11976        return parent;
11977    }
11978
11979    /**
11980     * <p>Computes the coordinates of this view on the screen. The argument
11981     * must be an array of two integers. After the method returns, the array
11982     * contains the x and y location in that order.</p>
11983     *
11984     * @param location an array of two integers in which to hold the coordinates
11985     */
11986    public void getLocationOnScreen(int[] location) {
11987        getLocationInWindow(location);
11988
11989        final AttachInfo info = mAttachInfo;
11990        if (info != null) {
11991            location[0] += info.mWindowLeft;
11992            location[1] += info.mWindowTop;
11993        }
11994    }
11995
11996    /**
11997     * <p>Computes the coordinates of this view in its window. The argument
11998     * must be an array of two integers. After the method returns, the array
11999     * contains the x and y location in that order.</p>
12000     *
12001     * @param location an array of two integers in which to hold the coordinates
12002     */
12003    public void getLocationInWindow(int[] location) {
12004        if (location == null || location.length < 2) {
12005            throw new IllegalArgumentException("location must be an array of "
12006                    + "two integers");
12007        }
12008
12009        location[0] = mLeft;
12010        location[1] = mTop;
12011        if (mTransformationInfo != null) {
12012            location[0] += (int) (mTransformationInfo.mTranslationX + 0.5f);
12013            location[1] += (int) (mTransformationInfo.mTranslationY + 0.5f);
12014        }
12015
12016        ViewParent viewParent = mParent;
12017        while (viewParent instanceof View) {
12018            final View view = (View)viewParent;
12019            location[0] += view.mLeft - view.mScrollX;
12020            location[1] += view.mTop - view.mScrollY;
12021            if (view.mTransformationInfo != null) {
12022                location[0] += (int) (view.mTransformationInfo.mTranslationX + 0.5f);
12023                location[1] += (int) (view.mTransformationInfo.mTranslationY + 0.5f);
12024            }
12025            viewParent = view.mParent;
12026        }
12027
12028        if (viewParent instanceof ViewRootImpl) {
12029            // *cough*
12030            final ViewRootImpl vr = (ViewRootImpl)viewParent;
12031            location[1] -= vr.mCurScrollY;
12032        }
12033    }
12034
12035    /**
12036     * {@hide}
12037     * @param id the id of the view to be found
12038     * @return the view of the specified id, null if cannot be found
12039     */
12040    protected View findViewTraversal(int id) {
12041        if (id == mID) {
12042            return this;
12043        }
12044        return null;
12045    }
12046
12047    /**
12048     * {@hide}
12049     * @param tag the tag of the view to be found
12050     * @return the view of specified tag, null if cannot be found
12051     */
12052    protected View findViewWithTagTraversal(Object tag) {
12053        if (tag != null && tag.equals(mTag)) {
12054            return this;
12055        }
12056        return null;
12057    }
12058
12059    /**
12060     * {@hide}
12061     * @param predicate The predicate to evaluate.
12062     * @param childToSkip If not null, ignores this child during the recursive traversal.
12063     * @return The first view that matches the predicate or null.
12064     */
12065    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12066        if (predicate.apply(this)) {
12067            return this;
12068        }
12069        return null;
12070    }
12071
12072    /**
12073     * Look for a child view with the given id.  If this view has the given
12074     * id, return this view.
12075     *
12076     * @param id The id to search for.
12077     * @return The view that has the given id in the hierarchy or null
12078     */
12079    public final View findViewById(int id) {
12080        if (id < 0) {
12081            return null;
12082        }
12083        return findViewTraversal(id);
12084    }
12085
12086    /**
12087     * Look for a child view with the given tag.  If this view has the given
12088     * tag, return this view.
12089     *
12090     * @param tag The tag to search for, using "tag.equals(getTag())".
12091     * @return The View that has the given tag in the hierarchy or null
12092     */
12093    public final View findViewWithTag(Object tag) {
12094        if (tag == null) {
12095            return null;
12096        }
12097        return findViewWithTagTraversal(tag);
12098    }
12099
12100    /**
12101     * {@hide}
12102     * Look for a child view that matches the specified predicate.
12103     * If this view matches the predicate, return this view.
12104     *
12105     * @param predicate The predicate to evaluate.
12106     * @return The first view that matches the predicate or null.
12107     */
12108    public final View findViewByPredicate(Predicate<View> predicate) {
12109        return findViewByPredicateTraversal(predicate, null);
12110    }
12111
12112    /**
12113     * {@hide}
12114     * Look for a child view that matches the specified predicate,
12115     * starting with the specified view and its descendents and then
12116     * recusively searching the ancestors and siblings of that view
12117     * until this view is reached.
12118     *
12119     * This method is useful in cases where the predicate does not match
12120     * a single unique view (perhaps multiple views use the same id)
12121     * and we are trying to find the view that is "closest" in scope to the
12122     * starting view.
12123     *
12124     * @param start The view to start from.
12125     * @param predicate The predicate to evaluate.
12126     * @return The first view that matches the predicate or null.
12127     */
12128    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12129        View childToSkip = null;
12130        for (;;) {
12131            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12132            if (view != null || start == this) {
12133                return view;
12134            }
12135
12136            ViewParent parent = start.getParent();
12137            if (parent == null || !(parent instanceof View)) {
12138                return null;
12139            }
12140
12141            childToSkip = start;
12142            start = (View) parent;
12143        }
12144    }
12145
12146    /**
12147     * Sets the identifier for this view. The identifier does not have to be
12148     * unique in this view's hierarchy. The identifier should be a positive
12149     * number.
12150     *
12151     * @see #NO_ID
12152     * @see #getId()
12153     * @see #findViewById(int)
12154     *
12155     * @param id a number used to identify the view
12156     *
12157     * @attr ref android.R.styleable#View_id
12158     */
12159    public void setId(int id) {
12160        mID = id;
12161    }
12162
12163    /**
12164     * {@hide}
12165     *
12166     * @param isRoot true if the view belongs to the root namespace, false
12167     *        otherwise
12168     */
12169    public void setIsRootNamespace(boolean isRoot) {
12170        if (isRoot) {
12171            mPrivateFlags |= IS_ROOT_NAMESPACE;
12172        } else {
12173            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12174        }
12175    }
12176
12177    /**
12178     * {@hide}
12179     *
12180     * @return true if the view belongs to the root namespace, false otherwise
12181     */
12182    public boolean isRootNamespace() {
12183        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12184    }
12185
12186    /**
12187     * Returns this view's identifier.
12188     *
12189     * @return a positive integer used to identify the view or {@link #NO_ID}
12190     *         if the view has no ID
12191     *
12192     * @see #setId(int)
12193     * @see #findViewById(int)
12194     * @attr ref android.R.styleable#View_id
12195     */
12196    @ViewDebug.CapturedViewProperty
12197    public int getId() {
12198        return mID;
12199    }
12200
12201    /**
12202     * Returns this view's tag.
12203     *
12204     * @return the Object stored in this view as a tag
12205     *
12206     * @see #setTag(Object)
12207     * @see #getTag(int)
12208     */
12209    @ViewDebug.ExportedProperty
12210    public Object getTag() {
12211        return mTag;
12212    }
12213
12214    /**
12215     * Sets the tag associated with this view. A tag can be used to mark
12216     * a view in its hierarchy and does not have to be unique within the
12217     * hierarchy. Tags can also be used to store data within a view without
12218     * resorting to another data structure.
12219     *
12220     * @param tag an Object to tag the view with
12221     *
12222     * @see #getTag()
12223     * @see #setTag(int, Object)
12224     */
12225    public void setTag(final Object tag) {
12226        mTag = tag;
12227    }
12228
12229    /**
12230     * Returns the tag associated with this view and the specified key.
12231     *
12232     * @param key The key identifying the tag
12233     *
12234     * @return the Object stored in this view as a tag
12235     *
12236     * @see #setTag(int, Object)
12237     * @see #getTag()
12238     */
12239    public Object getTag(int key) {
12240        if (mKeyedTags != null) return mKeyedTags.get(key);
12241        return null;
12242    }
12243
12244    /**
12245     * Sets a tag associated with this view and a key. A tag can be used
12246     * to mark a view in its hierarchy and does not have to be unique within
12247     * the hierarchy. Tags can also be used to store data within a view
12248     * without resorting to another data structure.
12249     *
12250     * The specified key should be an id declared in the resources of the
12251     * application to ensure it is unique (see the <a
12252     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
12253     * Keys identified as belonging to
12254     * the Android framework or not associated with any package will cause
12255     * an {@link IllegalArgumentException} to be thrown.
12256     *
12257     * @param key The key identifying the tag
12258     * @param tag An Object to tag the view with
12259     *
12260     * @throws IllegalArgumentException If they specified key is not valid
12261     *
12262     * @see #setTag(Object)
12263     * @see #getTag(int)
12264     */
12265    public void setTag(int key, final Object tag) {
12266        // If the package id is 0x00 or 0x01, it's either an undefined package
12267        // or a framework id
12268        if ((key >>> 24) < 2) {
12269            throw new IllegalArgumentException("The key must be an application-specific "
12270                    + "resource id.");
12271        }
12272
12273        setKeyedTag(key, tag);
12274    }
12275
12276    /**
12277     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12278     * framework id.
12279     *
12280     * @hide
12281     */
12282    public void setTagInternal(int key, Object tag) {
12283        if ((key >>> 24) != 0x1) {
12284            throw new IllegalArgumentException("The key must be a framework-specific "
12285                    + "resource id.");
12286        }
12287
12288        setKeyedTag(key, tag);
12289    }
12290
12291    private void setKeyedTag(int key, Object tag) {
12292        if (mKeyedTags == null) {
12293            mKeyedTags = new SparseArray<Object>();
12294        }
12295
12296        mKeyedTags.put(key, tag);
12297    }
12298
12299    /**
12300     * @param consistency The type of consistency. See ViewDebug for more information.
12301     *
12302     * @hide
12303     */
12304    protected boolean dispatchConsistencyCheck(int consistency) {
12305        return onConsistencyCheck(consistency);
12306    }
12307
12308    /**
12309     * Method that subclasses should implement to check their consistency. The type of
12310     * consistency check is indicated by the bit field passed as a parameter.
12311     *
12312     * @param consistency The type of consistency. See ViewDebug for more information.
12313     *
12314     * @throws IllegalStateException if the view is in an inconsistent state.
12315     *
12316     * @hide
12317     */
12318    protected boolean onConsistencyCheck(int consistency) {
12319        boolean result = true;
12320
12321        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12322        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12323
12324        if (checkLayout) {
12325            if (getParent() == null) {
12326                result = false;
12327                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12328                        "View " + this + " does not have a parent.");
12329            }
12330
12331            if (mAttachInfo == null) {
12332                result = false;
12333                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12334                        "View " + this + " is not attached to a window.");
12335            }
12336        }
12337
12338        if (checkDrawing) {
12339            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12340            // from their draw() method
12341
12342            if ((mPrivateFlags & DRAWN) != DRAWN &&
12343                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12344                result = false;
12345                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12346                        "View " + this + " was invalidated but its drawing cache is valid.");
12347            }
12348        }
12349
12350        return result;
12351    }
12352
12353    /**
12354     * Prints information about this view in the log output, with the tag
12355     * {@link #VIEW_LOG_TAG}.
12356     *
12357     * @hide
12358     */
12359    public void debug() {
12360        debug(0);
12361    }
12362
12363    /**
12364     * Prints information about this view in the log output, with the tag
12365     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12366     * indentation defined by the <code>depth</code>.
12367     *
12368     * @param depth the indentation level
12369     *
12370     * @hide
12371     */
12372    protected void debug(int depth) {
12373        String output = debugIndent(depth - 1);
12374
12375        output += "+ " + this;
12376        int id = getId();
12377        if (id != -1) {
12378            output += " (id=" + id + ")";
12379        }
12380        Object tag = getTag();
12381        if (tag != null) {
12382            output += " (tag=" + tag + ")";
12383        }
12384        Log.d(VIEW_LOG_TAG, output);
12385
12386        if ((mPrivateFlags & FOCUSED) != 0) {
12387            output = debugIndent(depth) + " FOCUSED";
12388            Log.d(VIEW_LOG_TAG, output);
12389        }
12390
12391        output = debugIndent(depth);
12392        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12393                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12394                + "} ";
12395        Log.d(VIEW_LOG_TAG, output);
12396
12397        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12398                || mPaddingBottom != 0) {
12399            output = debugIndent(depth);
12400            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12401                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12402            Log.d(VIEW_LOG_TAG, output);
12403        }
12404
12405        output = debugIndent(depth);
12406        output += "mMeasureWidth=" + mMeasuredWidth +
12407                " mMeasureHeight=" + mMeasuredHeight;
12408        Log.d(VIEW_LOG_TAG, output);
12409
12410        output = debugIndent(depth);
12411        if (mLayoutParams == null) {
12412            output += "BAD! no layout params";
12413        } else {
12414            output = mLayoutParams.debug(output);
12415        }
12416        Log.d(VIEW_LOG_TAG, output);
12417
12418        output = debugIndent(depth);
12419        output += "flags={";
12420        output += View.printFlags(mViewFlags);
12421        output += "}";
12422        Log.d(VIEW_LOG_TAG, output);
12423
12424        output = debugIndent(depth);
12425        output += "privateFlags={";
12426        output += View.printPrivateFlags(mPrivateFlags);
12427        output += "}";
12428        Log.d(VIEW_LOG_TAG, output);
12429    }
12430
12431    /**
12432     * Creates an string of whitespaces used for indentation.
12433     *
12434     * @param depth the indentation level
12435     * @return a String containing (depth * 2 + 3) * 2 white spaces
12436     *
12437     * @hide
12438     */
12439    protected static String debugIndent(int depth) {
12440        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12441        for (int i = 0; i < (depth * 2) + 3; i++) {
12442            spaces.append(' ').append(' ');
12443        }
12444        return spaces.toString();
12445    }
12446
12447    /**
12448     * <p>Return the offset of the widget's text baseline from the widget's top
12449     * boundary. If this widget does not support baseline alignment, this
12450     * method returns -1. </p>
12451     *
12452     * @return the offset of the baseline within the widget's bounds or -1
12453     *         if baseline alignment is not supported
12454     */
12455    @ViewDebug.ExportedProperty(category = "layout")
12456    public int getBaseline() {
12457        return -1;
12458    }
12459
12460    /**
12461     * Call this when something has changed which has invalidated the
12462     * layout of this view. This will schedule a layout pass of the view
12463     * tree.
12464     */
12465    public void requestLayout() {
12466        if (ViewDebug.TRACE_HIERARCHY) {
12467            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
12468        }
12469
12470        mPrivateFlags |= FORCE_LAYOUT;
12471        mPrivateFlags |= INVALIDATED;
12472
12473        if (mParent != null) {
12474            if (mLayoutParams != null) {
12475                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
12476            }
12477            if (!mParent.isLayoutRequested()) {
12478                mParent.requestLayout();
12479            }
12480        }
12481    }
12482
12483    /**
12484     * Forces this view to be laid out during the next layout pass.
12485     * This method does not call requestLayout() or forceLayout()
12486     * on the parent.
12487     */
12488    public void forceLayout() {
12489        mPrivateFlags |= FORCE_LAYOUT;
12490        mPrivateFlags |= INVALIDATED;
12491    }
12492
12493    /**
12494     * <p>
12495     * This is called to find out how big a view should be. The parent
12496     * supplies constraint information in the width and height parameters.
12497     * </p>
12498     *
12499     * <p>
12500     * The actual mesurement work of a view is performed in
12501     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
12502     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
12503     * </p>
12504     *
12505     *
12506     * @param widthMeasureSpec Horizontal space requirements as imposed by the
12507     *        parent
12508     * @param heightMeasureSpec Vertical space requirements as imposed by the
12509     *        parent
12510     *
12511     * @see #onMeasure(int, int)
12512     */
12513    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
12514        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
12515                widthMeasureSpec != mOldWidthMeasureSpec ||
12516                heightMeasureSpec != mOldHeightMeasureSpec) {
12517
12518            // first clears the measured dimension flag
12519            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
12520
12521            if (ViewDebug.TRACE_HIERARCHY) {
12522                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
12523            }
12524
12525            // measure ourselves, this should set the measured dimension flag back
12526            onMeasure(widthMeasureSpec, heightMeasureSpec);
12527
12528            // flag not set, setMeasuredDimension() was not invoked, we raise
12529            // an exception to warn the developer
12530            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
12531                throw new IllegalStateException("onMeasure() did not set the"
12532                        + " measured dimension by calling"
12533                        + " setMeasuredDimension()");
12534            }
12535
12536            mPrivateFlags |= LAYOUT_REQUIRED;
12537        }
12538
12539        mOldWidthMeasureSpec = widthMeasureSpec;
12540        mOldHeightMeasureSpec = heightMeasureSpec;
12541    }
12542
12543    /**
12544     * <p>
12545     * Measure the view and its content to determine the measured width and the
12546     * measured height. This method is invoked by {@link #measure(int, int)} and
12547     * should be overriden by subclasses to provide accurate and efficient
12548     * measurement of their contents.
12549     * </p>
12550     *
12551     * <p>
12552     * <strong>CONTRACT:</strong> When overriding this method, you
12553     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
12554     * measured width and height of this view. Failure to do so will trigger an
12555     * <code>IllegalStateException</code>, thrown by
12556     * {@link #measure(int, int)}. Calling the superclass'
12557     * {@link #onMeasure(int, int)} is a valid use.
12558     * </p>
12559     *
12560     * <p>
12561     * The base class implementation of measure defaults to the background size,
12562     * unless a larger size is allowed by the MeasureSpec. Subclasses should
12563     * override {@link #onMeasure(int, int)} to provide better measurements of
12564     * their content.
12565     * </p>
12566     *
12567     * <p>
12568     * If this method is overridden, it is the subclass's responsibility to make
12569     * sure the measured height and width are at least the view's minimum height
12570     * and width ({@link #getSuggestedMinimumHeight()} and
12571     * {@link #getSuggestedMinimumWidth()}).
12572     * </p>
12573     *
12574     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
12575     *                         The requirements are encoded with
12576     *                         {@link android.view.View.MeasureSpec}.
12577     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
12578     *                         The requirements are encoded with
12579     *                         {@link android.view.View.MeasureSpec}.
12580     *
12581     * @see #getMeasuredWidth()
12582     * @see #getMeasuredHeight()
12583     * @see #setMeasuredDimension(int, int)
12584     * @see #getSuggestedMinimumHeight()
12585     * @see #getSuggestedMinimumWidth()
12586     * @see android.view.View.MeasureSpec#getMode(int)
12587     * @see android.view.View.MeasureSpec#getSize(int)
12588     */
12589    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12590        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
12591                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
12592    }
12593
12594    /**
12595     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
12596     * measured width and measured height. Failing to do so will trigger an
12597     * exception at measurement time.</p>
12598     *
12599     * @param measuredWidth The measured width of this view.  May be a complex
12600     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12601     * {@link #MEASURED_STATE_TOO_SMALL}.
12602     * @param measuredHeight The measured height of this view.  May be a complex
12603     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12604     * {@link #MEASURED_STATE_TOO_SMALL}.
12605     */
12606    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
12607        mMeasuredWidth = measuredWidth;
12608        mMeasuredHeight = measuredHeight;
12609
12610        mPrivateFlags |= MEASURED_DIMENSION_SET;
12611    }
12612
12613    /**
12614     * Merge two states as returned by {@link #getMeasuredState()}.
12615     * @param curState The current state as returned from a view or the result
12616     * of combining multiple views.
12617     * @param newState The new view state to combine.
12618     * @return Returns a new integer reflecting the combination of the two
12619     * states.
12620     */
12621    public static int combineMeasuredStates(int curState, int newState) {
12622        return curState | newState;
12623    }
12624
12625    /**
12626     * Version of {@link #resolveSizeAndState(int, int, int)}
12627     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
12628     */
12629    public static int resolveSize(int size, int measureSpec) {
12630        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
12631    }
12632
12633    /**
12634     * Utility to reconcile a desired size and state, with constraints imposed
12635     * by a MeasureSpec.  Will take the desired size, unless a different size
12636     * is imposed by the constraints.  The returned value is a compound integer,
12637     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
12638     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
12639     * size is smaller than the size the view wants to be.
12640     *
12641     * @param size How big the view wants to be
12642     * @param measureSpec Constraints imposed by the parent
12643     * @return Size information bit mask as defined by
12644     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12645     */
12646    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
12647        int result = size;
12648        int specMode = MeasureSpec.getMode(measureSpec);
12649        int specSize =  MeasureSpec.getSize(measureSpec);
12650        switch (specMode) {
12651        case MeasureSpec.UNSPECIFIED:
12652            result = size;
12653            break;
12654        case MeasureSpec.AT_MOST:
12655            if (specSize < size) {
12656                result = specSize | MEASURED_STATE_TOO_SMALL;
12657            } else {
12658                result = size;
12659            }
12660            break;
12661        case MeasureSpec.EXACTLY:
12662            result = specSize;
12663            break;
12664        }
12665        return result | (childMeasuredState&MEASURED_STATE_MASK);
12666    }
12667
12668    /**
12669     * Utility to return a default size. Uses the supplied size if the
12670     * MeasureSpec imposed no constraints. Will get larger if allowed
12671     * by the MeasureSpec.
12672     *
12673     * @param size Default size for this view
12674     * @param measureSpec Constraints imposed by the parent
12675     * @return The size this view should be.
12676     */
12677    public static int getDefaultSize(int size, int measureSpec) {
12678        int result = size;
12679        int specMode = MeasureSpec.getMode(measureSpec);
12680        int specSize = MeasureSpec.getSize(measureSpec);
12681
12682        switch (specMode) {
12683        case MeasureSpec.UNSPECIFIED:
12684            result = size;
12685            break;
12686        case MeasureSpec.AT_MOST:
12687        case MeasureSpec.EXACTLY:
12688            result = specSize;
12689            break;
12690        }
12691        return result;
12692    }
12693
12694    /**
12695     * Returns the suggested minimum height that the view should use. This
12696     * returns the maximum of the view's minimum height
12697     * and the background's minimum height
12698     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
12699     * <p>
12700     * When being used in {@link #onMeasure(int, int)}, the caller should still
12701     * ensure the returned height is within the requirements of the parent.
12702     *
12703     * @return The suggested minimum height of the view.
12704     */
12705    protected int getSuggestedMinimumHeight() {
12706        int suggestedMinHeight = mMinHeight;
12707
12708        if (mBGDrawable != null) {
12709            final int bgMinHeight = mBGDrawable.getMinimumHeight();
12710            if (suggestedMinHeight < bgMinHeight) {
12711                suggestedMinHeight = bgMinHeight;
12712            }
12713        }
12714
12715        return suggestedMinHeight;
12716    }
12717
12718    /**
12719     * Returns the suggested minimum width that the view should use. This
12720     * returns the maximum of the view's minimum width)
12721     * and the background's minimum width
12722     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
12723     * <p>
12724     * When being used in {@link #onMeasure(int, int)}, the caller should still
12725     * ensure the returned width is within the requirements of the parent.
12726     *
12727     * @return The suggested minimum width of the view.
12728     */
12729    protected int getSuggestedMinimumWidth() {
12730        int suggestedMinWidth = mMinWidth;
12731
12732        if (mBGDrawable != null) {
12733            final int bgMinWidth = mBGDrawable.getMinimumWidth();
12734            if (suggestedMinWidth < bgMinWidth) {
12735                suggestedMinWidth = bgMinWidth;
12736            }
12737        }
12738
12739        return suggestedMinWidth;
12740    }
12741
12742    /**
12743     * Sets the minimum height of the view. It is not guaranteed the view will
12744     * be able to achieve this minimum height (for example, if its parent layout
12745     * constrains it with less available height).
12746     *
12747     * @param minHeight The minimum height the view will try to be.
12748     */
12749    public void setMinimumHeight(int minHeight) {
12750        mMinHeight = minHeight;
12751    }
12752
12753    /**
12754     * Sets the minimum width of the view. It is not guaranteed the view will
12755     * be able to achieve this minimum width (for example, if its parent layout
12756     * constrains it with less available width).
12757     *
12758     * @param minWidth The minimum width the view will try to be.
12759     */
12760    public void setMinimumWidth(int minWidth) {
12761        mMinWidth = minWidth;
12762    }
12763
12764    /**
12765     * Get the animation currently associated with this view.
12766     *
12767     * @return The animation that is currently playing or
12768     *         scheduled to play for this view.
12769     */
12770    public Animation getAnimation() {
12771        return mCurrentAnimation;
12772    }
12773
12774    /**
12775     * Start the specified animation now.
12776     *
12777     * @param animation the animation to start now
12778     */
12779    public void startAnimation(Animation animation) {
12780        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
12781        setAnimation(animation);
12782        invalidateParentCaches();
12783        invalidate(true);
12784    }
12785
12786    /**
12787     * Cancels any animations for this view.
12788     */
12789    public void clearAnimation() {
12790        if (mCurrentAnimation != null) {
12791            mCurrentAnimation.detach();
12792        }
12793        mCurrentAnimation = null;
12794        invalidateParentIfNeeded();
12795    }
12796
12797    /**
12798     * Sets the next animation to play for this view.
12799     * If you want the animation to play immediately, use
12800     * startAnimation. This method provides allows fine-grained
12801     * control over the start time and invalidation, but you
12802     * must make sure that 1) the animation has a start time set, and
12803     * 2) the view will be invalidated when the animation is supposed to
12804     * start.
12805     *
12806     * @param animation The next animation, or null.
12807     */
12808    public void setAnimation(Animation animation) {
12809        mCurrentAnimation = animation;
12810        if (animation != null) {
12811            animation.reset();
12812        }
12813    }
12814
12815    /**
12816     * Invoked by a parent ViewGroup to notify the start of the animation
12817     * currently associated with this view. If you override this method,
12818     * always call super.onAnimationStart();
12819     *
12820     * @see #setAnimation(android.view.animation.Animation)
12821     * @see #getAnimation()
12822     */
12823    protected void onAnimationStart() {
12824        mPrivateFlags |= ANIMATION_STARTED;
12825    }
12826
12827    /**
12828     * Invoked by a parent ViewGroup to notify the end of the animation
12829     * currently associated with this view. If you override this method,
12830     * always call super.onAnimationEnd();
12831     *
12832     * @see #setAnimation(android.view.animation.Animation)
12833     * @see #getAnimation()
12834     */
12835    protected void onAnimationEnd() {
12836        mPrivateFlags &= ~ANIMATION_STARTED;
12837    }
12838
12839    /**
12840     * Invoked if there is a Transform that involves alpha. Subclass that can
12841     * draw themselves with the specified alpha should return true, and then
12842     * respect that alpha when their onDraw() is called. If this returns false
12843     * then the view may be redirected to draw into an offscreen buffer to
12844     * fulfill the request, which will look fine, but may be slower than if the
12845     * subclass handles it internally. The default implementation returns false.
12846     *
12847     * @param alpha The alpha (0..255) to apply to the view's drawing
12848     * @return true if the view can draw with the specified alpha.
12849     */
12850    protected boolean onSetAlpha(int alpha) {
12851        return false;
12852    }
12853
12854    /**
12855     * This is used by the RootView to perform an optimization when
12856     * the view hierarchy contains one or several SurfaceView.
12857     * SurfaceView is always considered transparent, but its children are not,
12858     * therefore all View objects remove themselves from the global transparent
12859     * region (passed as a parameter to this function).
12860     *
12861     * @param region The transparent region for this ViewAncestor (window).
12862     *
12863     * @return Returns true if the effective visibility of the view at this
12864     * point is opaque, regardless of the transparent region; returns false
12865     * if it is possible for underlying windows to be seen behind the view.
12866     *
12867     * {@hide}
12868     */
12869    public boolean gatherTransparentRegion(Region region) {
12870        final AttachInfo attachInfo = mAttachInfo;
12871        if (region != null && attachInfo != null) {
12872            final int pflags = mPrivateFlags;
12873            if ((pflags & SKIP_DRAW) == 0) {
12874                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
12875                // remove it from the transparent region.
12876                final int[] location = attachInfo.mTransparentLocation;
12877                getLocationInWindow(location);
12878                region.op(location[0], location[1], location[0] + mRight - mLeft,
12879                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
12880            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
12881                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
12882                // exists, so we remove the background drawable's non-transparent
12883                // parts from this transparent region.
12884                applyDrawableToTransparentRegion(mBGDrawable, region);
12885            }
12886        }
12887        return true;
12888    }
12889
12890    /**
12891     * Play a sound effect for this view.
12892     *
12893     * <p>The framework will play sound effects for some built in actions, such as
12894     * clicking, but you may wish to play these effects in your widget,
12895     * for instance, for internal navigation.
12896     *
12897     * <p>The sound effect will only be played if sound effects are enabled by the user, and
12898     * {@link #isSoundEffectsEnabled()} is true.
12899     *
12900     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
12901     */
12902    public void playSoundEffect(int soundConstant) {
12903        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
12904            return;
12905        }
12906        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
12907    }
12908
12909    /**
12910     * BZZZTT!!1!
12911     *
12912     * <p>Provide haptic feedback to the user for this view.
12913     *
12914     * <p>The framework will provide haptic feedback for some built in actions,
12915     * such as long presses, but you may wish to provide feedback for your
12916     * own widget.
12917     *
12918     * <p>The feedback will only be performed if
12919     * {@link #isHapticFeedbackEnabled()} is true.
12920     *
12921     * @param feedbackConstant One of the constants defined in
12922     * {@link HapticFeedbackConstants}
12923     */
12924    public boolean performHapticFeedback(int feedbackConstant) {
12925        return performHapticFeedback(feedbackConstant, 0);
12926    }
12927
12928    /**
12929     * BZZZTT!!1!
12930     *
12931     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
12932     *
12933     * @param feedbackConstant One of the constants defined in
12934     * {@link HapticFeedbackConstants}
12935     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
12936     */
12937    public boolean performHapticFeedback(int feedbackConstant, int flags) {
12938        if (mAttachInfo == null) {
12939            return false;
12940        }
12941        //noinspection SimplifiableIfStatement
12942        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
12943                && !isHapticFeedbackEnabled()) {
12944            return false;
12945        }
12946        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
12947                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
12948    }
12949
12950    /**
12951     * Request that the visibility of the status bar be changed.
12952     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12953     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12954     */
12955    public void setSystemUiVisibility(int visibility) {
12956        if (visibility != mSystemUiVisibility) {
12957            mSystemUiVisibility = visibility;
12958            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12959                mParent.recomputeViewAttributes(this);
12960            }
12961        }
12962    }
12963
12964    /**
12965     * Returns the status bar visibility that this view has requested.
12966     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12967     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12968     */
12969    public int getSystemUiVisibility() {
12970        return mSystemUiVisibility;
12971    }
12972
12973    /**
12974     * Set a listener to receive callbacks when the visibility of the system bar changes.
12975     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
12976     */
12977    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
12978        mOnSystemUiVisibilityChangeListener = l;
12979        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12980            mParent.recomputeViewAttributes(this);
12981        }
12982    }
12983
12984    /**
12985     */
12986    public void dispatchSystemUiVisibilityChanged(int visibility) {
12987        if (mOnSystemUiVisibilityChangeListener != null) {
12988            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
12989                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
12990        }
12991    }
12992
12993    /**
12994     * Creates an image that the system displays during the drag and drop
12995     * operation. This is called a &quot;drag shadow&quot;. The default implementation
12996     * for a DragShadowBuilder based on a View returns an image that has exactly the same
12997     * appearance as the given View. The default also positions the center of the drag shadow
12998     * directly under the touch point. If no View is provided (the constructor with no parameters
12999     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13000     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13001     * default is an invisible drag shadow.
13002     * <p>
13003     * You are not required to use the View you provide to the constructor as the basis of the
13004     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13005     * anything you want as the drag shadow.
13006     * </p>
13007     * <p>
13008     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13009     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13010     *  size and position of the drag shadow. It uses this data to construct a
13011     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13012     *  so that your application can draw the shadow image in the Canvas.
13013     * </p>
13014     */
13015    public static class DragShadowBuilder {
13016        private final WeakReference<View> mView;
13017
13018        /**
13019         * Constructs a shadow image builder based on a View. By default, the resulting drag
13020         * shadow will have the same appearance and dimensions as the View, with the touch point
13021         * over the center of the View.
13022         * @param view A View. Any View in scope can be used.
13023         */
13024        public DragShadowBuilder(View view) {
13025            mView = new WeakReference<View>(view);
13026        }
13027
13028        /**
13029         * Construct a shadow builder object with no associated View.  This
13030         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13031         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13032         * to supply the drag shadow's dimensions and appearance without
13033         * reference to any View object. If they are not overridden, then the result is an
13034         * invisible drag shadow.
13035         */
13036        public DragShadowBuilder() {
13037            mView = new WeakReference<View>(null);
13038        }
13039
13040        /**
13041         * Returns the View object that had been passed to the
13042         * {@link #View.DragShadowBuilder(View)}
13043         * constructor.  If that View parameter was {@code null} or if the
13044         * {@link #View.DragShadowBuilder()}
13045         * constructor was used to instantiate the builder object, this method will return
13046         * null.
13047         *
13048         * @return The View object associate with this builder object.
13049         */
13050        @SuppressWarnings({"JavadocReference"})
13051        final public View getView() {
13052            return mView.get();
13053        }
13054
13055        /**
13056         * Provides the metrics for the shadow image. These include the dimensions of
13057         * the shadow image, and the point within that shadow that should
13058         * be centered under the touch location while dragging.
13059         * <p>
13060         * The default implementation sets the dimensions of the shadow to be the
13061         * same as the dimensions of the View itself and centers the shadow under
13062         * the touch point.
13063         * </p>
13064         *
13065         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13066         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13067         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13068         * image.
13069         *
13070         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13071         * shadow image that should be underneath the touch point during the drag and drop
13072         * operation. Your application must set {@link android.graphics.Point#x} to the
13073         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13074         */
13075        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13076            final View view = mView.get();
13077            if (view != null) {
13078                shadowSize.set(view.getWidth(), view.getHeight());
13079                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13080            } else {
13081                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13082            }
13083        }
13084
13085        /**
13086         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13087         * based on the dimensions it received from the
13088         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13089         *
13090         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13091         */
13092        public void onDrawShadow(Canvas canvas) {
13093            final View view = mView.get();
13094            if (view != null) {
13095                view.draw(canvas);
13096            } else {
13097                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13098            }
13099        }
13100    }
13101
13102    /**
13103     * Starts a drag and drop operation. When your application calls this method, it passes a
13104     * {@link android.view.View.DragShadowBuilder} object to the system. The
13105     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13106     * to get metrics for the drag shadow, and then calls the object's
13107     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13108     * <p>
13109     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13110     *  drag events to all the View objects in your application that are currently visible. It does
13111     *  this either by calling the View object's drag listener (an implementation of
13112     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13113     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13114     *  Both are passed a {@link android.view.DragEvent} object that has a
13115     *  {@link android.view.DragEvent#getAction()} value of
13116     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13117     * </p>
13118     * <p>
13119     * Your application can invoke startDrag() on any attached View object. The View object does not
13120     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13121     * be related to the View the user selected for dragging.
13122     * </p>
13123     * @param data A {@link android.content.ClipData} object pointing to the data to be
13124     * transferred by the drag and drop operation.
13125     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13126     * drag shadow.
13127     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13128     * drop operation. This Object is put into every DragEvent object sent by the system during the
13129     * current drag.
13130     * <p>
13131     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13132     * to the target Views. For example, it can contain flags that differentiate between a
13133     * a copy operation and a move operation.
13134     * </p>
13135     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13136     * so the parameter should be set to 0.
13137     * @return {@code true} if the method completes successfully, or
13138     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13139     * do a drag, and so no drag operation is in progress.
13140     */
13141    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13142            Object myLocalState, int flags) {
13143        if (ViewDebug.DEBUG_DRAG) {
13144            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13145        }
13146        boolean okay = false;
13147
13148        Point shadowSize = new Point();
13149        Point shadowTouchPoint = new Point();
13150        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13151
13152        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13153                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13154            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13155        }
13156
13157        if (ViewDebug.DEBUG_DRAG) {
13158            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13159                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13160        }
13161        Surface surface = new Surface();
13162        try {
13163            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13164                    flags, shadowSize.x, shadowSize.y, surface);
13165            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13166                    + " surface=" + surface);
13167            if (token != null) {
13168                Canvas canvas = surface.lockCanvas(null);
13169                try {
13170                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13171                    shadowBuilder.onDrawShadow(canvas);
13172                } finally {
13173                    surface.unlockCanvasAndPost(canvas);
13174                }
13175
13176                final ViewRootImpl root = getViewRootImpl();
13177
13178                // Cache the local state object for delivery with DragEvents
13179                root.setLocalDragState(myLocalState);
13180
13181                // repurpose 'shadowSize' for the last touch point
13182                root.getLastTouchPoint(shadowSize);
13183
13184                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13185                        shadowSize.x, shadowSize.y,
13186                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13187                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13188
13189                // Off and running!  Release our local surface instance; the drag
13190                // shadow surface is now managed by the system process.
13191                surface.release();
13192            }
13193        } catch (Exception e) {
13194            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13195            surface.destroy();
13196        }
13197
13198        return okay;
13199    }
13200
13201    /**
13202     * Handles drag events sent by the system following a call to
13203     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13204     *<p>
13205     * When the system calls this method, it passes a
13206     * {@link android.view.DragEvent} object. A call to
13207     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13208     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13209     * operation.
13210     * @param event The {@link android.view.DragEvent} sent by the system.
13211     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13212     * in DragEvent, indicating the type of drag event represented by this object.
13213     * @return {@code true} if the method was successful, otherwise {@code false}.
13214     * <p>
13215     *  The method should return {@code true} in response to an action type of
13216     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13217     *  operation.
13218     * </p>
13219     * <p>
13220     *  The method should also return {@code true} in response to an action type of
13221     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13222     *  {@code false} if it didn't.
13223     * </p>
13224     */
13225    public boolean onDragEvent(DragEvent event) {
13226        return false;
13227    }
13228
13229    /**
13230     * Detects if this View is enabled and has a drag event listener.
13231     * If both are true, then it calls the drag event listener with the
13232     * {@link android.view.DragEvent} it received. If the drag event listener returns
13233     * {@code true}, then dispatchDragEvent() returns {@code true}.
13234     * <p>
13235     * For all other cases, the method calls the
13236     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
13237     * method and returns its result.
13238     * </p>
13239     * <p>
13240     * This ensures that a drag event is always consumed, even if the View does not have a drag
13241     * event listener. However, if the View has a listener and the listener returns true, then
13242     * onDragEvent() is not called.
13243     * </p>
13244     */
13245    public boolean dispatchDragEvent(DragEvent event) {
13246        //noinspection SimplifiableIfStatement
13247        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
13248                && mOnDragListener.onDrag(this, event)) {
13249            return true;
13250        }
13251        return onDragEvent(event);
13252    }
13253
13254    boolean canAcceptDrag() {
13255        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13256    }
13257
13258    /**
13259     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13260     * it is ever exposed at all.
13261     * @hide
13262     */
13263    public void onCloseSystemDialogs(String reason) {
13264    }
13265
13266    /**
13267     * Given a Drawable whose bounds have been set to draw into this view,
13268     * update a Region being computed for
13269     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13270     * that any non-transparent parts of the Drawable are removed from the
13271     * given transparent region.
13272     *
13273     * @param dr The Drawable whose transparency is to be applied to the region.
13274     * @param region A Region holding the current transparency information,
13275     * where any parts of the region that are set are considered to be
13276     * transparent.  On return, this region will be modified to have the
13277     * transparency information reduced by the corresponding parts of the
13278     * Drawable that are not transparent.
13279     * {@hide}
13280     */
13281    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13282        if (DBG) {
13283            Log.i("View", "Getting transparent region for: " + this);
13284        }
13285        final Region r = dr.getTransparentRegion();
13286        final Rect db = dr.getBounds();
13287        final AttachInfo attachInfo = mAttachInfo;
13288        if (r != null && attachInfo != null) {
13289            final int w = getRight()-getLeft();
13290            final int h = getBottom()-getTop();
13291            if (db.left > 0) {
13292                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13293                r.op(0, 0, db.left, h, Region.Op.UNION);
13294            }
13295            if (db.right < w) {
13296                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13297                r.op(db.right, 0, w, h, Region.Op.UNION);
13298            }
13299            if (db.top > 0) {
13300                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13301                r.op(0, 0, w, db.top, Region.Op.UNION);
13302            }
13303            if (db.bottom < h) {
13304                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13305                r.op(0, db.bottom, w, h, Region.Op.UNION);
13306            }
13307            final int[] location = attachInfo.mTransparentLocation;
13308            getLocationInWindow(location);
13309            r.translate(location[0], location[1]);
13310            region.op(r, Region.Op.INTERSECT);
13311        } else {
13312            region.op(db, Region.Op.DIFFERENCE);
13313        }
13314    }
13315
13316    private void checkForLongClick(int delayOffset) {
13317        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13318            mHasPerformedLongPress = false;
13319
13320            if (mPendingCheckForLongPress == null) {
13321                mPendingCheckForLongPress = new CheckForLongPress();
13322            }
13323            mPendingCheckForLongPress.rememberWindowAttachCount();
13324            postDelayed(mPendingCheckForLongPress,
13325                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13326        }
13327    }
13328
13329    /**
13330     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13331     * LayoutInflater} class, which provides a full range of options for view inflation.
13332     *
13333     * @param context The Context object for your activity or application.
13334     * @param resource The resource ID to inflate
13335     * @param root A view group that will be the parent.  Used to properly inflate the
13336     * layout_* parameters.
13337     * @see LayoutInflater
13338     */
13339    public static View inflate(Context context, int resource, ViewGroup root) {
13340        LayoutInflater factory = LayoutInflater.from(context);
13341        return factory.inflate(resource, root);
13342    }
13343
13344    /**
13345     * Scroll the view with standard behavior for scrolling beyond the normal
13346     * content boundaries. Views that call this method should override
13347     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13348     * results of an over-scroll operation.
13349     *
13350     * Views can use this method to handle any touch or fling-based scrolling.
13351     *
13352     * @param deltaX Change in X in pixels
13353     * @param deltaY Change in Y in pixels
13354     * @param scrollX Current X scroll value in pixels before applying deltaX
13355     * @param scrollY Current Y scroll value in pixels before applying deltaY
13356     * @param scrollRangeX Maximum content scroll range along the X axis
13357     * @param scrollRangeY Maximum content scroll range along the Y axis
13358     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13359     *          along the X axis.
13360     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13361     *          along the Y axis.
13362     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13363     * @return true if scrolling was clamped to an over-scroll boundary along either
13364     *          axis, false otherwise.
13365     */
13366    @SuppressWarnings({"UnusedParameters"})
13367    protected boolean overScrollBy(int deltaX, int deltaY,
13368            int scrollX, int scrollY,
13369            int scrollRangeX, int scrollRangeY,
13370            int maxOverScrollX, int maxOverScrollY,
13371            boolean isTouchEvent) {
13372        final int overScrollMode = mOverScrollMode;
13373        final boolean canScrollHorizontal =
13374                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13375        final boolean canScrollVertical =
13376                computeVerticalScrollRange() > computeVerticalScrollExtent();
13377        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13378                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13379        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13380                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13381
13382        int newScrollX = scrollX + deltaX;
13383        if (!overScrollHorizontal) {
13384            maxOverScrollX = 0;
13385        }
13386
13387        int newScrollY = scrollY + deltaY;
13388        if (!overScrollVertical) {
13389            maxOverScrollY = 0;
13390        }
13391
13392        // Clamp values if at the limits and record
13393        final int left = -maxOverScrollX;
13394        final int right = maxOverScrollX + scrollRangeX;
13395        final int top = -maxOverScrollY;
13396        final int bottom = maxOverScrollY + scrollRangeY;
13397
13398        boolean clampedX = false;
13399        if (newScrollX > right) {
13400            newScrollX = right;
13401            clampedX = true;
13402        } else if (newScrollX < left) {
13403            newScrollX = left;
13404            clampedX = true;
13405        }
13406
13407        boolean clampedY = false;
13408        if (newScrollY > bottom) {
13409            newScrollY = bottom;
13410            clampedY = true;
13411        } else if (newScrollY < top) {
13412            newScrollY = top;
13413            clampedY = true;
13414        }
13415
13416        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13417
13418        return clampedX || clampedY;
13419    }
13420
13421    /**
13422     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13423     * respond to the results of an over-scroll operation.
13424     *
13425     * @param scrollX New X scroll value in pixels
13426     * @param scrollY New Y scroll value in pixels
13427     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13428     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13429     */
13430    protected void onOverScrolled(int scrollX, int scrollY,
13431            boolean clampedX, boolean clampedY) {
13432        // Intentionally empty.
13433    }
13434
13435    /**
13436     * Returns the over-scroll mode for this view. The result will be
13437     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13438     * (allow over-scrolling only if the view content is larger than the container),
13439     * or {@link #OVER_SCROLL_NEVER}.
13440     *
13441     * @return This view's over-scroll mode.
13442     */
13443    public int getOverScrollMode() {
13444        return mOverScrollMode;
13445    }
13446
13447    /**
13448     * Set the over-scroll mode for this view. Valid over-scroll modes are
13449     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13450     * (allow over-scrolling only if the view content is larger than the container),
13451     * or {@link #OVER_SCROLL_NEVER}.
13452     *
13453     * Setting the over-scroll mode of a view will have an effect only if the
13454     * view is capable of scrolling.
13455     *
13456     * @param overScrollMode The new over-scroll mode for this view.
13457     */
13458    public void setOverScrollMode(int overScrollMode) {
13459        if (overScrollMode != OVER_SCROLL_ALWAYS &&
13460                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
13461                overScrollMode != OVER_SCROLL_NEVER) {
13462            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
13463        }
13464        mOverScrollMode = overScrollMode;
13465    }
13466
13467    /**
13468     * Gets a scale factor that determines the distance the view should scroll
13469     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
13470     * @return The vertical scroll scale factor.
13471     * @hide
13472     */
13473    protected float getVerticalScrollFactor() {
13474        if (mVerticalScrollFactor == 0) {
13475            TypedValue outValue = new TypedValue();
13476            if (!mContext.getTheme().resolveAttribute(
13477                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
13478                throw new IllegalStateException(
13479                        "Expected theme to define listPreferredItemHeight.");
13480            }
13481            mVerticalScrollFactor = outValue.getDimension(
13482                    mContext.getResources().getDisplayMetrics());
13483        }
13484        return mVerticalScrollFactor;
13485    }
13486
13487    /**
13488     * Gets a scale factor that determines the distance the view should scroll
13489     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
13490     * @return The horizontal scroll scale factor.
13491     * @hide
13492     */
13493    protected float getHorizontalScrollFactor() {
13494        // TODO: Should use something else.
13495        return getVerticalScrollFactor();
13496    }
13497
13498    /**
13499     * Return the value specifying the text direction or policy that was set with
13500     * {@link #setTextDirection(int)}.
13501     *
13502     * @return the defined text direction. It can be one of:
13503     *
13504     * {@link #TEXT_DIRECTION_INHERIT},
13505     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13506     * {@link #TEXT_DIRECTION_ANY_RTL},
13507     * {@link #TEXT_DIRECTION_LTR},
13508     * {@link #TEXT_DIRECTION_RTL},
13509     *
13510     * @hide
13511     */
13512    public int getTextDirection() {
13513        return mTextDirection;
13514    }
13515
13516    /**
13517     * Set the text direction.
13518     *
13519     * @param textDirection the direction to set. Should be one of:
13520     *
13521     * {@link #TEXT_DIRECTION_INHERIT},
13522     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13523     * {@link #TEXT_DIRECTION_ANY_RTL},
13524     * {@link #TEXT_DIRECTION_LTR},
13525     * {@link #TEXT_DIRECTION_RTL},
13526     *
13527     * @hide
13528     */
13529    public void setTextDirection(int textDirection) {
13530        if (textDirection != mTextDirection) {
13531            mTextDirection = textDirection;
13532            resetResolvedTextDirection();
13533            requestLayout();
13534        }
13535    }
13536
13537    /**
13538     * Return the resolved text direction.
13539     *
13540     * @return the resolved text direction. Return one of:
13541     *
13542     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13543     * {@link #TEXT_DIRECTION_ANY_RTL},
13544     * {@link #TEXT_DIRECTION_LTR},
13545     * {@link #TEXT_DIRECTION_RTL},
13546     *
13547     * @hide
13548     */
13549    public int getResolvedTextDirection() {
13550        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
13551            resolveTextDirection();
13552        }
13553        return mResolvedTextDirection;
13554    }
13555
13556    /**
13557     * Resolve the text direction.
13558     *
13559     * @hide
13560     */
13561    protected void resolveTextDirection() {
13562        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
13563            mResolvedTextDirection = mTextDirection;
13564            return;
13565        }
13566        if (mParent != null && mParent instanceof ViewGroup) {
13567            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
13568            return;
13569        }
13570        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
13571    }
13572
13573    /**
13574     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
13575     *
13576     * @hide
13577     */
13578    protected void resetResolvedTextDirection() {
13579        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
13580    }
13581
13582    //
13583    // Properties
13584    //
13585    /**
13586     * A Property wrapper around the <code>alpha</code> functionality handled by the
13587     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
13588     */
13589    public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
13590        @Override
13591        public void setValue(View object, float value) {
13592            object.setAlpha(value);
13593        }
13594
13595        @Override
13596        public Float get(View object) {
13597            return object.getAlpha();
13598        }
13599    };
13600
13601    /**
13602     * A Property wrapper around the <code>translationX</code> functionality handled by the
13603     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
13604     */
13605    public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
13606        @Override
13607        public void setValue(View object, float value) {
13608            object.setTranslationX(value);
13609        }
13610
13611                @Override
13612        public Float get(View object) {
13613            return object.getTranslationX();
13614        }
13615    };
13616
13617    /**
13618     * A Property wrapper around the <code>translationY</code> functionality handled by the
13619     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
13620     */
13621    public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
13622        @Override
13623        public void setValue(View object, float value) {
13624            object.setTranslationY(value);
13625        }
13626
13627        @Override
13628        public Float get(View object) {
13629            return object.getTranslationY();
13630        }
13631    };
13632
13633    /**
13634     * A Property wrapper around the <code>x</code> functionality handled by the
13635     * {@link View#setX(float)} and {@link View#getX()} methods.
13636     */
13637    public static Property<View, Float> X = new FloatProperty<View>("x") {
13638        @Override
13639        public void setValue(View object, float value) {
13640            object.setX(value);
13641        }
13642
13643        @Override
13644        public Float get(View object) {
13645            return object.getX();
13646        }
13647    };
13648
13649    /**
13650     * A Property wrapper around the <code>y</code> functionality handled by the
13651     * {@link View#setY(float)} and {@link View#getY()} methods.
13652     */
13653    public static Property<View, Float> Y = new FloatProperty<View>("y") {
13654        @Override
13655        public void setValue(View object, float value) {
13656            object.setY(value);
13657        }
13658
13659        @Override
13660        public Float get(View object) {
13661            return object.getY();
13662        }
13663    };
13664
13665    /**
13666     * A Property wrapper around the <code>rotation</code> functionality handled by the
13667     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
13668     */
13669    public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
13670        @Override
13671        public void setValue(View object, float value) {
13672            object.setRotation(value);
13673        }
13674
13675        @Override
13676        public Float get(View object) {
13677            return object.getRotation();
13678        }
13679    };
13680
13681    /**
13682     * A Property wrapper around the <code>rotationX</code> functionality handled by the
13683     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
13684     */
13685    public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
13686        @Override
13687        public void setValue(View object, float value) {
13688            object.setRotationX(value);
13689        }
13690
13691        @Override
13692        public Float get(View object) {
13693            return object.getRotationX();
13694        }
13695    };
13696
13697    /**
13698     * A Property wrapper around the <code>rotationY</code> functionality handled by the
13699     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
13700     */
13701    public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
13702        @Override
13703        public void setValue(View object, float value) {
13704            object.setRotationY(value);
13705        }
13706
13707        @Override
13708        public Float get(View object) {
13709            return object.getRotationY();
13710        }
13711    };
13712
13713    /**
13714     * A Property wrapper around the <code>scaleX</code> functionality handled by the
13715     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
13716     */
13717    public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
13718        @Override
13719        public void setValue(View object, float value) {
13720            object.setScaleX(value);
13721        }
13722
13723        @Override
13724        public Float get(View object) {
13725            return object.getScaleX();
13726        }
13727    };
13728
13729    /**
13730     * A Property wrapper around the <code>scaleY</code> functionality handled by the
13731     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
13732     */
13733    public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
13734        @Override
13735        public void setValue(View object, float value) {
13736            object.setScaleY(value);
13737        }
13738
13739        @Override
13740        public Float get(View object) {
13741            return object.getScaleY();
13742        }
13743    };
13744
13745    /**
13746     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
13747     * Each MeasureSpec represents a requirement for either the width or the height.
13748     * A MeasureSpec is comprised of a size and a mode. There are three possible
13749     * modes:
13750     * <dl>
13751     * <dt>UNSPECIFIED</dt>
13752     * <dd>
13753     * The parent has not imposed any constraint on the child. It can be whatever size
13754     * it wants.
13755     * </dd>
13756     *
13757     * <dt>EXACTLY</dt>
13758     * <dd>
13759     * The parent has determined an exact size for the child. The child is going to be
13760     * given those bounds regardless of how big it wants to be.
13761     * </dd>
13762     *
13763     * <dt>AT_MOST</dt>
13764     * <dd>
13765     * The child can be as large as it wants up to the specified size.
13766     * </dd>
13767     * </dl>
13768     *
13769     * MeasureSpecs are implemented as ints to reduce object allocation. This class
13770     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
13771     */
13772    public static class MeasureSpec {
13773        private static final int MODE_SHIFT = 30;
13774        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
13775
13776        /**
13777         * Measure specification mode: The parent has not imposed any constraint
13778         * on the child. It can be whatever size it wants.
13779         */
13780        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
13781
13782        /**
13783         * Measure specification mode: The parent has determined an exact size
13784         * for the child. The child is going to be given those bounds regardless
13785         * of how big it wants to be.
13786         */
13787        public static final int EXACTLY     = 1 << MODE_SHIFT;
13788
13789        /**
13790         * Measure specification mode: The child can be as large as it wants up
13791         * to the specified size.
13792         */
13793        public static final int AT_MOST     = 2 << MODE_SHIFT;
13794
13795        /**
13796         * Creates a measure specification based on the supplied size and mode.
13797         *
13798         * The mode must always be one of the following:
13799         * <ul>
13800         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
13801         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
13802         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
13803         * </ul>
13804         *
13805         * @param size the size of the measure specification
13806         * @param mode the mode of the measure specification
13807         * @return the measure specification based on size and mode
13808         */
13809        public static int makeMeasureSpec(int size, int mode) {
13810            return size + mode;
13811        }
13812
13813        /**
13814         * Extracts the mode from the supplied measure specification.
13815         *
13816         * @param measureSpec the measure specification to extract the mode from
13817         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
13818         *         {@link android.view.View.MeasureSpec#AT_MOST} or
13819         *         {@link android.view.View.MeasureSpec#EXACTLY}
13820         */
13821        public static int getMode(int measureSpec) {
13822            return (measureSpec & MODE_MASK);
13823        }
13824
13825        /**
13826         * Extracts the size from the supplied measure specification.
13827         *
13828         * @param measureSpec the measure specification to extract the size from
13829         * @return the size in pixels defined in the supplied measure specification
13830         */
13831        public static int getSize(int measureSpec) {
13832            return (measureSpec & ~MODE_MASK);
13833        }
13834
13835        /**
13836         * Returns a String representation of the specified measure
13837         * specification.
13838         *
13839         * @param measureSpec the measure specification to convert to a String
13840         * @return a String with the following format: "MeasureSpec: MODE SIZE"
13841         */
13842        public static String toString(int measureSpec) {
13843            int mode = getMode(measureSpec);
13844            int size = getSize(measureSpec);
13845
13846            StringBuilder sb = new StringBuilder("MeasureSpec: ");
13847
13848            if (mode == UNSPECIFIED)
13849                sb.append("UNSPECIFIED ");
13850            else if (mode == EXACTLY)
13851                sb.append("EXACTLY ");
13852            else if (mode == AT_MOST)
13853                sb.append("AT_MOST ");
13854            else
13855                sb.append(mode).append(" ");
13856
13857            sb.append(size);
13858            return sb.toString();
13859        }
13860    }
13861
13862    class CheckForLongPress implements Runnable {
13863
13864        private int mOriginalWindowAttachCount;
13865
13866        public void run() {
13867            if (isPressed() && (mParent != null)
13868                    && mOriginalWindowAttachCount == mWindowAttachCount) {
13869                if (performLongClick()) {
13870                    mHasPerformedLongPress = true;
13871                }
13872            }
13873        }
13874
13875        public void rememberWindowAttachCount() {
13876            mOriginalWindowAttachCount = mWindowAttachCount;
13877        }
13878    }
13879
13880    private final class CheckForTap implements Runnable {
13881        public void run() {
13882            mPrivateFlags &= ~PREPRESSED;
13883            mPrivateFlags |= PRESSED;
13884            refreshDrawableState();
13885            checkForLongClick(ViewConfiguration.getTapTimeout());
13886        }
13887    }
13888
13889    private final class PerformClick implements Runnable {
13890        public void run() {
13891            performClick();
13892        }
13893    }
13894
13895    /** @hide */
13896    public void hackTurnOffWindowResizeAnim(boolean off) {
13897        mAttachInfo.mTurnOffWindowResizeAnim = off;
13898    }
13899
13900    /**
13901     * This method returns a ViewPropertyAnimator object, which can be used to animate
13902     * specific properties on this View.
13903     *
13904     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
13905     */
13906    public ViewPropertyAnimator animate() {
13907        if (mAnimator == null) {
13908            mAnimator = new ViewPropertyAnimator(this);
13909        }
13910        return mAnimator;
13911    }
13912
13913    /**
13914     * Interface definition for a callback to be invoked when a key event is
13915     * dispatched to this view. The callback will be invoked before the key
13916     * event is given to the view.
13917     */
13918    public interface OnKeyListener {
13919        /**
13920         * Called when a key is dispatched to a view. This allows listeners to
13921         * get a chance to respond before the target view.
13922         *
13923         * @param v The view the key has been dispatched to.
13924         * @param keyCode The code for the physical key that was pressed
13925         * @param event The KeyEvent object containing full information about
13926         *        the event.
13927         * @return True if the listener has consumed the event, false otherwise.
13928         */
13929        boolean onKey(View v, int keyCode, KeyEvent event);
13930    }
13931
13932    /**
13933     * Interface definition for a callback to be invoked when a touch event is
13934     * dispatched to this view. The callback will be invoked before the touch
13935     * event is given to the view.
13936     */
13937    public interface OnTouchListener {
13938        /**
13939         * Called when a touch event is dispatched to a view. This allows listeners to
13940         * get a chance to respond before the target view.
13941         *
13942         * @param v The view the touch event has been dispatched to.
13943         * @param event The MotionEvent object containing full information about
13944         *        the event.
13945         * @return True if the listener has consumed the event, false otherwise.
13946         */
13947        boolean onTouch(View v, MotionEvent event);
13948    }
13949
13950    /**
13951     * Interface definition for a callback to be invoked when a hover event is
13952     * dispatched to this view. The callback will be invoked before the hover
13953     * event is given to the view.
13954     */
13955    public interface OnHoverListener {
13956        /**
13957         * Called when a hover event is dispatched to a view. This allows listeners to
13958         * get a chance to respond before the target view.
13959         *
13960         * @param v The view the hover event has been dispatched to.
13961         * @param event The MotionEvent object containing full information about
13962         *        the event.
13963         * @return True if the listener has consumed the event, false otherwise.
13964         */
13965        boolean onHover(View v, MotionEvent event);
13966    }
13967
13968    /**
13969     * Interface definition for a callback to be invoked when a generic motion event is
13970     * dispatched to this view. The callback will be invoked before the generic motion
13971     * event is given to the view.
13972     */
13973    public interface OnGenericMotionListener {
13974        /**
13975         * Called when a generic motion event is dispatched to a view. This allows listeners to
13976         * get a chance to respond before the target view.
13977         *
13978         * @param v The view the generic motion event has been dispatched to.
13979         * @param event The MotionEvent object containing full information about
13980         *        the event.
13981         * @return True if the listener has consumed the event, false otherwise.
13982         */
13983        boolean onGenericMotion(View v, MotionEvent event);
13984    }
13985
13986    /**
13987     * Interface definition for a callback to be invoked when a view has been clicked and held.
13988     */
13989    public interface OnLongClickListener {
13990        /**
13991         * Called when a view has been clicked and held.
13992         *
13993         * @param v The view that was clicked and held.
13994         *
13995         * @return true if the callback consumed the long click, false otherwise.
13996         */
13997        boolean onLongClick(View v);
13998    }
13999
14000    /**
14001     * Interface definition for a callback to be invoked when a drag is being dispatched
14002     * to this view.  The callback will be invoked before the hosting view's own
14003     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14004     * onDrag(event) behavior, it should return 'false' from this callback.
14005     */
14006    public interface OnDragListener {
14007        /**
14008         * Called when a drag event is dispatched to a view. This allows listeners
14009         * to get a chance to override base View behavior.
14010         *
14011         * @param v The View that received the drag event.
14012         * @param event The {@link android.view.DragEvent} object for the drag event.
14013         * @return {@code true} if the drag event was handled successfully, or {@code false}
14014         * if the drag event was not handled. Note that {@code false} will trigger the View
14015         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14016         */
14017        boolean onDrag(View v, DragEvent event);
14018    }
14019
14020    /**
14021     * Interface definition for a callback to be invoked when the focus state of
14022     * a view changed.
14023     */
14024    public interface OnFocusChangeListener {
14025        /**
14026         * Called when the focus state of a view has changed.
14027         *
14028         * @param v The view whose state has changed.
14029         * @param hasFocus The new focus state of v.
14030         */
14031        void onFocusChange(View v, boolean hasFocus);
14032    }
14033
14034    /**
14035     * Interface definition for a callback to be invoked when a view is clicked.
14036     */
14037    public interface OnClickListener {
14038        /**
14039         * Called when a view has been clicked.
14040         *
14041         * @param v The view that was clicked.
14042         */
14043        void onClick(View v);
14044    }
14045
14046    /**
14047     * Interface definition for a callback to be invoked when the context menu
14048     * for this view is being built.
14049     */
14050    public interface OnCreateContextMenuListener {
14051        /**
14052         * Called when the context menu for this view is being built. It is not
14053         * safe to hold onto the menu after this method returns.
14054         *
14055         * @param menu The context menu that is being built
14056         * @param v The view for which the context menu is being built
14057         * @param menuInfo Extra information about the item for which the
14058         *            context menu should be shown. This information will vary
14059         *            depending on the class of v.
14060         */
14061        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14062    }
14063
14064    /**
14065     * Interface definition for a callback to be invoked when the status bar changes
14066     * visibility.
14067     *
14068     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14069     */
14070    public interface OnSystemUiVisibilityChangeListener {
14071        /**
14072         * Called when the status bar changes visibility because of a call to
14073         * {@link View#setSystemUiVisibility(int)}.
14074         *
14075         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14076         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
14077         */
14078        public void onSystemUiVisibilityChange(int visibility);
14079    }
14080
14081    /**
14082     * Interface definition for a callback to be invoked when this view is attached
14083     * or detached from its window.
14084     */
14085    public interface OnAttachStateChangeListener {
14086        /**
14087         * Called when the view is attached to a window.
14088         * @param v The view that was attached
14089         */
14090        public void onViewAttachedToWindow(View v);
14091        /**
14092         * Called when the view is detached from a window.
14093         * @param v The view that was detached
14094         */
14095        public void onViewDetachedFromWindow(View v);
14096    }
14097
14098    private final class UnsetPressedState implements Runnable {
14099        public void run() {
14100            setPressed(false);
14101        }
14102    }
14103
14104    /**
14105     * Base class for derived classes that want to save and restore their own
14106     * state in {@link android.view.View#onSaveInstanceState()}.
14107     */
14108    public static class BaseSavedState extends AbsSavedState {
14109        /**
14110         * Constructor used when reading from a parcel. Reads the state of the superclass.
14111         *
14112         * @param source
14113         */
14114        public BaseSavedState(Parcel source) {
14115            super(source);
14116        }
14117
14118        /**
14119         * Constructor called by derived classes when creating their SavedState objects
14120         *
14121         * @param superState The state of the superclass of this view
14122         */
14123        public BaseSavedState(Parcelable superState) {
14124            super(superState);
14125        }
14126
14127        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14128                new Parcelable.Creator<BaseSavedState>() {
14129            public BaseSavedState createFromParcel(Parcel in) {
14130                return new BaseSavedState(in);
14131            }
14132
14133            public BaseSavedState[] newArray(int size) {
14134                return new BaseSavedState[size];
14135            }
14136        };
14137    }
14138
14139    /**
14140     * A set of information given to a view when it is attached to its parent
14141     * window.
14142     */
14143    static class AttachInfo {
14144        interface Callbacks {
14145            void playSoundEffect(int effectId);
14146            boolean performHapticFeedback(int effectId, boolean always);
14147        }
14148
14149        /**
14150         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
14151         * to a Handler. This class contains the target (View) to invalidate and
14152         * the coordinates of the dirty rectangle.
14153         *
14154         * For performance purposes, this class also implements a pool of up to
14155         * POOL_LIMIT objects that get reused. This reduces memory allocations
14156         * whenever possible.
14157         */
14158        static class InvalidateInfo implements Poolable<InvalidateInfo> {
14159            private static final int POOL_LIMIT = 10;
14160            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
14161                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
14162                        public InvalidateInfo newInstance() {
14163                            return new InvalidateInfo();
14164                        }
14165
14166                        public void onAcquired(InvalidateInfo element) {
14167                        }
14168
14169                        public void onReleased(InvalidateInfo element) {
14170                            element.target = null;
14171                        }
14172                    }, POOL_LIMIT)
14173            );
14174
14175            private InvalidateInfo mNext;
14176            private boolean mIsPooled;
14177
14178            View target;
14179
14180            int left;
14181            int top;
14182            int right;
14183            int bottom;
14184
14185            public void setNextPoolable(InvalidateInfo element) {
14186                mNext = element;
14187            }
14188
14189            public InvalidateInfo getNextPoolable() {
14190                return mNext;
14191            }
14192
14193            static InvalidateInfo acquire() {
14194                return sPool.acquire();
14195            }
14196
14197            void release() {
14198                sPool.release(this);
14199            }
14200
14201            public boolean isPooled() {
14202                return mIsPooled;
14203            }
14204
14205            public void setPooled(boolean isPooled) {
14206                mIsPooled = isPooled;
14207            }
14208        }
14209
14210        final IWindowSession mSession;
14211
14212        final IWindow mWindow;
14213
14214        final IBinder mWindowToken;
14215
14216        final Callbacks mRootCallbacks;
14217
14218        HardwareCanvas mHardwareCanvas;
14219
14220        /**
14221         * The top view of the hierarchy.
14222         */
14223        View mRootView;
14224
14225        IBinder mPanelParentWindowToken;
14226        Surface mSurface;
14227
14228        boolean mHardwareAccelerated;
14229        boolean mHardwareAccelerationRequested;
14230        HardwareRenderer mHardwareRenderer;
14231
14232        /**
14233         * Scale factor used by the compatibility mode
14234         */
14235        float mApplicationScale;
14236
14237        /**
14238         * Indicates whether the application is in compatibility mode
14239         */
14240        boolean mScalingRequired;
14241
14242        /**
14243         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
14244         */
14245        boolean mTurnOffWindowResizeAnim;
14246
14247        /**
14248         * Left position of this view's window
14249         */
14250        int mWindowLeft;
14251
14252        /**
14253         * Top position of this view's window
14254         */
14255        int mWindowTop;
14256
14257        /**
14258         * Indicates whether views need to use 32-bit drawing caches
14259         */
14260        boolean mUse32BitDrawingCache;
14261
14262        /**
14263         * For windows that are full-screen but using insets to layout inside
14264         * of the screen decorations, these are the current insets for the
14265         * content of the window.
14266         */
14267        final Rect mContentInsets = new Rect();
14268
14269        /**
14270         * For windows that are full-screen but using insets to layout inside
14271         * of the screen decorations, these are the current insets for the
14272         * actual visible parts of the window.
14273         */
14274        final Rect mVisibleInsets = new Rect();
14275
14276        /**
14277         * The internal insets given by this window.  This value is
14278         * supplied by the client (through
14279         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14280         * be given to the window manager when changed to be used in laying
14281         * out windows behind it.
14282         */
14283        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14284                = new ViewTreeObserver.InternalInsetsInfo();
14285
14286        /**
14287         * All views in the window's hierarchy that serve as scroll containers,
14288         * used to determine if the window can be resized or must be panned
14289         * to adjust for a soft input area.
14290         */
14291        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14292
14293        final KeyEvent.DispatcherState mKeyDispatchState
14294                = new KeyEvent.DispatcherState();
14295
14296        /**
14297         * Indicates whether the view's window currently has the focus.
14298         */
14299        boolean mHasWindowFocus;
14300
14301        /**
14302         * The current visibility of the window.
14303         */
14304        int mWindowVisibility;
14305
14306        /**
14307         * Indicates the time at which drawing started to occur.
14308         */
14309        long mDrawingTime;
14310
14311        /**
14312         * Indicates whether or not ignoring the DIRTY_MASK flags.
14313         */
14314        boolean mIgnoreDirtyState;
14315
14316        /**
14317         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14318         * to avoid clearing that flag prematurely.
14319         */
14320        boolean mSetIgnoreDirtyState = false;
14321
14322        /**
14323         * Indicates whether the view's window is currently in touch mode.
14324         */
14325        boolean mInTouchMode;
14326
14327        /**
14328         * Indicates that ViewAncestor should trigger a global layout change
14329         * the next time it performs a traversal
14330         */
14331        boolean mRecomputeGlobalAttributes;
14332
14333        /**
14334         * Set during a traveral if any views want to keep the screen on.
14335         */
14336        boolean mKeepScreenOn;
14337
14338        /**
14339         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14340         */
14341        int mSystemUiVisibility;
14342
14343        /**
14344         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14345         * attached.
14346         */
14347        boolean mHasSystemUiListeners;
14348
14349        /**
14350         * Set if the visibility of any views has changed.
14351         */
14352        boolean mViewVisibilityChanged;
14353
14354        /**
14355         * Set to true if a view has been scrolled.
14356         */
14357        boolean mViewScrollChanged;
14358
14359        /**
14360         * Global to the view hierarchy used as a temporary for dealing with
14361         * x/y points in the transparent region computations.
14362         */
14363        final int[] mTransparentLocation = new int[2];
14364
14365        /**
14366         * Global to the view hierarchy used as a temporary for dealing with
14367         * x/y points in the ViewGroup.invalidateChild implementation.
14368         */
14369        final int[] mInvalidateChildLocation = new int[2];
14370
14371
14372        /**
14373         * Global to the view hierarchy used as a temporary for dealing with
14374         * x/y location when view is transformed.
14375         */
14376        final float[] mTmpTransformLocation = new float[2];
14377
14378        /**
14379         * The view tree observer used to dispatch global events like
14380         * layout, pre-draw, touch mode change, etc.
14381         */
14382        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14383
14384        /**
14385         * A Canvas used by the view hierarchy to perform bitmap caching.
14386         */
14387        Canvas mCanvas;
14388
14389        /**
14390         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14391         * handler can be used to pump events in the UI events queue.
14392         */
14393        final Handler mHandler;
14394
14395        /**
14396         * Identifier for messages requesting the view to be invalidated.
14397         * Such messages should be sent to {@link #mHandler}.
14398         */
14399        static final int INVALIDATE_MSG = 0x1;
14400
14401        /**
14402         * Identifier for messages requesting the view to invalidate a region.
14403         * Such messages should be sent to {@link #mHandler}.
14404         */
14405        static final int INVALIDATE_RECT_MSG = 0x2;
14406
14407        /**
14408         * Temporary for use in computing invalidate rectangles while
14409         * calling up the hierarchy.
14410         */
14411        final Rect mTmpInvalRect = new Rect();
14412
14413        /**
14414         * Temporary for use in computing hit areas with transformed views
14415         */
14416        final RectF mTmpTransformRect = new RectF();
14417
14418        /**
14419         * Temporary list for use in collecting focusable descendents of a view.
14420         */
14421        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14422
14423        /**
14424         * The id of the window for accessibility purposes.
14425         */
14426        int mAccessibilityWindowId = View.NO_ID;
14427
14428        /**
14429         * Creates a new set of attachment information with the specified
14430         * events handler and thread.
14431         *
14432         * @param handler the events handler the view must use
14433         */
14434        AttachInfo(IWindowSession session, IWindow window,
14435                Handler handler, Callbacks effectPlayer) {
14436            mSession = session;
14437            mWindow = window;
14438            mWindowToken = window.asBinder();
14439            mHandler = handler;
14440            mRootCallbacks = effectPlayer;
14441        }
14442    }
14443
14444    /**
14445     * <p>ScrollabilityCache holds various fields used by a View when scrolling
14446     * is supported. This avoids keeping too many unused fields in most
14447     * instances of View.</p>
14448     */
14449    private static class ScrollabilityCache implements Runnable {
14450
14451        /**
14452         * Scrollbars are not visible
14453         */
14454        public static final int OFF = 0;
14455
14456        /**
14457         * Scrollbars are visible
14458         */
14459        public static final int ON = 1;
14460
14461        /**
14462         * Scrollbars are fading away
14463         */
14464        public static final int FADING = 2;
14465
14466        public boolean fadeScrollBars;
14467
14468        public int fadingEdgeLength;
14469        public int scrollBarDefaultDelayBeforeFade;
14470        public int scrollBarFadeDuration;
14471
14472        public int scrollBarSize;
14473        public ScrollBarDrawable scrollBar;
14474        public float[] interpolatorValues;
14475        public View host;
14476
14477        public final Paint paint;
14478        public final Matrix matrix;
14479        public Shader shader;
14480
14481        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
14482
14483        private static final float[] OPAQUE = { 255 };
14484        private static final float[] TRANSPARENT = { 0.0f };
14485
14486        /**
14487         * When fading should start. This time moves into the future every time
14488         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
14489         */
14490        public long fadeStartTime;
14491
14492
14493        /**
14494         * The current state of the scrollbars: ON, OFF, or FADING
14495         */
14496        public int state = OFF;
14497
14498        private int mLastColor;
14499
14500        public ScrollabilityCache(ViewConfiguration configuration, View host) {
14501            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
14502            scrollBarSize = configuration.getScaledScrollBarSize();
14503            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
14504            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
14505
14506            paint = new Paint();
14507            matrix = new Matrix();
14508            // use use a height of 1, and then wack the matrix each time we
14509            // actually use it.
14510            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
14511
14512            paint.setShader(shader);
14513            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
14514            this.host = host;
14515        }
14516
14517        public void setFadeColor(int color) {
14518            if (color != 0 && color != mLastColor) {
14519                mLastColor = color;
14520                color |= 0xFF000000;
14521
14522                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
14523                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
14524
14525                paint.setShader(shader);
14526                // Restore the default transfer mode (src_over)
14527                paint.setXfermode(null);
14528            }
14529        }
14530
14531        public void run() {
14532            long now = AnimationUtils.currentAnimationTimeMillis();
14533            if (now >= fadeStartTime) {
14534
14535                // the animation fades the scrollbars out by changing
14536                // the opacity (alpha) from fully opaque to fully
14537                // transparent
14538                int nextFrame = (int) now;
14539                int framesCount = 0;
14540
14541                Interpolator interpolator = scrollBarInterpolator;
14542
14543                // Start opaque
14544                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
14545
14546                // End transparent
14547                nextFrame += scrollBarFadeDuration;
14548                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
14549
14550                state = FADING;
14551
14552                // Kick off the fade animation
14553                host.invalidate(true);
14554            }
14555        }
14556    }
14557
14558    /**
14559     * Resuable callback for sending
14560     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
14561     */
14562    private class SendViewScrolledAccessibilityEvent implements Runnable {
14563        public volatile boolean mIsPending;
14564
14565        public void run() {
14566            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
14567            mIsPending = false;
14568        }
14569    }
14570
14571    /**
14572     * <p>
14573     * This class represents a delegate that can be registered in a {@link View}
14574     * to enhance accessibility support via composition rather via inheritance.
14575     * It is specifically targeted to widget developers that extend basic View
14576     * classes i.e. classes in package android.view, that would like their
14577     * applications to be backwards compatible.
14578     * </p>
14579     * <p>
14580     * A scenario in which a developer would like to use an accessibility delegate
14581     * is overriding a method introduced in a later API version then the minimal API
14582     * version supported by the application. For example, the method
14583     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
14584     * in API version 4 when the accessibility APIs were first introduced. If a
14585     * developer would like his application to run on API version 4 devices (assuming
14586     * all other APIs used by the application are version 4 or lower) and take advantage
14587     * of this method, instead of overriding the method which would break the application's
14588     * backwards compatibility, he can override the corresponding method in this
14589     * delegate and register the delegate in the target View if the API version of
14590     * the system is high enough i.e. the API version is same or higher to the API
14591     * version that introduced
14592     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
14593     * </p>
14594     * <p>
14595     * Here is an example implementation:
14596     * </p>
14597     * <code><pre><p>
14598     * if (Build.VERSION.SDK_INT >= 14) {
14599     *     // If the API version is equal of higher than the version in
14600     *     // which onInitializeAccessibilityNodeInfo was introduced we
14601     *     // register a delegate with a customized implementation.
14602     *     View view = findViewById(R.id.view_id);
14603     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
14604     *         public void onInitializeAccessibilityNodeInfo(View host,
14605     *                 AccessibilityNodeInfo info) {
14606     *             // Let the default implementation populate the info.
14607     *             super.onInitializeAccessibilityNodeInfo(host, info);
14608     *             // Set some other information.
14609     *             info.setEnabled(host.isEnabled());
14610     *         }
14611     *     });
14612     * }
14613     * </code></pre></p>
14614     * <p>
14615     * This delegate contains methods that correspond to the accessibility methods
14616     * in View. If a delegate has been specified the implementation in View hands
14617     * off handling to the corresponding method in this delegate. The default
14618     * implementation the delegate methods behaves exactly as the corresponding
14619     * method in View for the case of no accessibility delegate been set. Hence,
14620     * to customize the behavior of a View method, clients can override only the
14621     * corresponding delegate method without altering the behavior of the rest
14622     * accessibility related methods of the host view.
14623     * </p>
14624     */
14625    public static class AccessibilityDelegate {
14626
14627        /**
14628         * Sends an accessibility event of the given type. If accessibility is not
14629         * enabled this method has no effect.
14630         * <p>
14631         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
14632         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
14633         * been set.
14634         * </p>
14635         *
14636         * @param host The View hosting the delegate.
14637         * @param eventType The type of the event to send.
14638         *
14639         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
14640         */
14641        public void sendAccessibilityEvent(View host, int eventType) {
14642            host.sendAccessibilityEventInternal(eventType);
14643        }
14644
14645        /**
14646         * Sends an accessibility event. This method behaves exactly as
14647         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
14648         * empty {@link AccessibilityEvent} and does not perform a check whether
14649         * accessibility is enabled.
14650         * <p>
14651         * The default implementation behaves as
14652         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14653         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
14654         * the case of no accessibility delegate been set.
14655         * </p>
14656         *
14657         * @param host The View hosting the delegate.
14658         * @param event The event to send.
14659         *
14660         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14661         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14662         */
14663        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
14664            host.sendAccessibilityEventUncheckedInternal(event);
14665        }
14666
14667        /**
14668         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
14669         * to its children for adding their text content to the event.
14670         * <p>
14671         * The default implementation behaves as
14672         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14673         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
14674         * the case of no accessibility delegate been set.
14675         * </p>
14676         *
14677         * @param host The View hosting the delegate.
14678         * @param event The event.
14679         * @return True if the event population was completed.
14680         *
14681         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14682         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14683         */
14684        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14685            return host.dispatchPopulateAccessibilityEventInternal(event);
14686        }
14687
14688        /**
14689         * Gives a chance to the host View to populate the accessibility event with its
14690         * text content.
14691         * <p>
14692         * The default implementation behaves as
14693         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
14694         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
14695         * the case of no accessibility delegate been set.
14696         * </p>
14697         *
14698         * @param host The View hosting the delegate.
14699         * @param event The accessibility event which to populate.
14700         *
14701         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
14702         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
14703         */
14704        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14705            host.onPopulateAccessibilityEventInternal(event);
14706        }
14707
14708        /**
14709         * Initializes an {@link AccessibilityEvent} with information about the
14710         * the host View which is the event source.
14711         * <p>
14712         * The default implementation behaves as
14713         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
14714         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
14715         * the case of no accessibility delegate been set.
14716         * </p>
14717         *
14718         * @param host The View hosting the delegate.
14719         * @param event The event to initialize.
14720         *
14721         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
14722         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
14723         */
14724        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
14725            host.onInitializeAccessibilityEventInternal(event);
14726        }
14727
14728        /**
14729         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
14730         * <p>
14731         * The default implementation behaves as
14732         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14733         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
14734         * the case of no accessibility delegate been set.
14735         * </p>
14736         *
14737         * @param host The View hosting the delegate.
14738         * @param info The instance to initialize.
14739         *
14740         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14741         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14742         */
14743        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
14744            host.onInitializeAccessibilityNodeInfoInternal(info);
14745        }
14746
14747        /**
14748         * Called when a child of the host View has requested sending an
14749         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
14750         * to augment the event.
14751         * <p>
14752         * The default implementation behaves as
14753         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14754         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
14755         * the case of no accessibility delegate been set.
14756         * </p>
14757         *
14758         * @param host The View hosting the delegate.
14759         * @param child The child which requests sending the event.
14760         * @param event The event to be sent.
14761         * @return True if the event should be sent
14762         *
14763         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14764         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14765         */
14766        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
14767                AccessibilityEvent event) {
14768            return host.onRequestSendAccessibilityEventInternal(child, event);
14769        }
14770    }
14771}
14772