View.java revision a953359db5250d0f648c7ca210ef3954bf1f8b66
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 com.android.internal.R;
20import com.android.internal.util.Predicate;
21import com.android.internal.view.menu.MenuBuilder;
22
23import android.content.ClipData;
24import android.content.Context;
25import android.content.res.Configuration;
26import android.content.res.Resources;
27import android.content.res.TypedArray;
28import android.graphics.Bitmap;
29import android.graphics.Camera;
30import android.graphics.Canvas;
31import android.graphics.Interpolator;
32import android.graphics.LinearGradient;
33import android.graphics.Matrix;
34import android.graphics.Paint;
35import android.graphics.PixelFormat;
36import android.graphics.Point;
37import android.graphics.PorterDuff;
38import android.graphics.PorterDuffXfermode;
39import android.graphics.Rect;
40import android.graphics.RectF;
41import android.graphics.Region;
42import android.graphics.Shader;
43import android.graphics.drawable.ColorDrawable;
44import android.graphics.drawable.Drawable;
45import android.os.Handler;
46import android.os.IBinder;
47import android.os.Message;
48import android.os.Parcel;
49import android.os.Parcelable;
50import android.os.RemoteException;
51import android.os.SystemClock;
52import android.os.SystemProperties;
53import android.util.AttributeSet;
54import android.util.Log;
55import android.util.Pool;
56import android.util.Poolable;
57import android.util.PoolableManager;
58import android.util.Pools;
59import android.util.SparseArray;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.View.MeasureSpec;
62import android.view.accessibility.AccessibilityEvent;
63import android.view.accessibility.AccessibilityEventSource;
64import android.view.accessibility.AccessibilityManager;
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 java.lang.ref.WeakReference;
73import java.lang.reflect.InvocationTargetException;
74import java.lang.reflect.Method;
75import java.util.ArrayList;
76import java.util.Arrays;
77import java.util.List;
78import java.util.WeakHashMap;
79
80/**
81 * <p>
82 * This class represents the basic building block for user interface components. A View
83 * occupies a rectangular area on the screen and is responsible for drawing and
84 * event handling. View is the base class for <em>widgets</em>, which are
85 * used to create interactive UI components (buttons, text fields, etc.). The
86 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
87 * are invisible containers that hold other Views (or other ViewGroups) and define
88 * their layout properties.
89 * </p>
90 *
91 * <div class="special">
92 * <p>For an introduction to using this class to develop your
93 * application's user interface, read the Developer Guide documentation on
94 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
95 * include:
96 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
104 * </p>
105 * </div>
106 *
107 * <a name="Using"></a>
108 * <h3>Using Views</h3>
109 * <p>
110 * All of the views in a window are arranged in a single tree. You can add views
111 * either from code or by specifying a tree of views in one or more XML layout
112 * files. There are many specialized subclasses of views that act as controls or
113 * are capable of displaying text, images, or other content.
114 * </p>
115 * <p>
116 * Once you have created a tree of views, there are typically a few types of
117 * common operations you may wish to perform:
118 * <ul>
119 * <li><strong>Set properties:</strong> for example setting the text of a
120 * {@link android.widget.TextView}. The available properties and the methods
121 * that set them will vary among the different subclasses of views. Note that
122 * properties that are known at build time can be set in the XML layout
123 * files.</li>
124 * <li><strong>Set focus:</strong> The framework will handled moving focus in
125 * response to user input. To force focus to a specific view, call
126 * {@link #requestFocus}.</li>
127 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
128 * that will be notified when something interesting happens to the view. For
129 * example, all views will let you set a listener to be notified when the view
130 * gains or loses focus. You can register such a listener using
131 * {@link #setOnFocusChangeListener}. Other view subclasses offer more
132 * specialized listeners. For example, a Button exposes a listener to notify
133 * clients when the button is clicked.</li>
134 * <li><strong>Set visibility:</strong> You can hide or show views using
135 * {@link #setVisibility}.</li>
136 * </ul>
137 * </p>
138 * <p><em>
139 * Note: The Android framework is responsible for measuring, laying out and
140 * drawing views. You should not call methods that perform these actions on
141 * views yourself unless you are actually implementing a
142 * {@link android.view.ViewGroup}.
143 * </em></p>
144 *
145 * <a name="Lifecycle"></a>
146 * <h3>Implementing a Custom View</h3>
147 *
148 * <p>
149 * To implement a custom view, you will usually begin by providing overrides for
150 * some of the standard methods that the framework calls on all views. You do
151 * not need to override all of these methods. In fact, you can start by just
152 * overriding {@link #onDraw(android.graphics.Canvas)}.
153 * <table border="2" width="85%" align="center" cellpadding="5">
154 *     <thead>
155 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
156 *     </thead>
157 *
158 *     <tbody>
159 *     <tr>
160 *         <td rowspan="2">Creation</td>
161 *         <td>Constructors</td>
162 *         <td>There is a form of the constructor that are called when the view
163 *         is created from code and a form that is called when the view is
164 *         inflated from a layout file. The second form should parse and apply
165 *         any attributes defined in the layout file.
166 *         </td>
167 *     </tr>
168 *     <tr>
169 *         <td><code>{@link #onFinishInflate()}</code></td>
170 *         <td>Called after a view and all of its children has been inflated
171 *         from XML.</td>
172 *     </tr>
173 *
174 *     <tr>
175 *         <td rowspan="3">Layout</td>
176 *         <td><code>{@link #onMeasure}</code></td>
177 *         <td>Called to determine the size requirements for this view and all
178 *         of its children.
179 *         </td>
180 *     </tr>
181 *     <tr>
182 *         <td><code>{@link #onLayout}</code></td>
183 *         <td>Called when this view should assign a size and position to all
184 *         of its children.
185 *         </td>
186 *     </tr>
187 *     <tr>
188 *         <td><code>{@link #onSizeChanged}</code></td>
189 *         <td>Called when the size of this view has changed.
190 *         </td>
191 *     </tr>
192 *
193 *     <tr>
194 *         <td>Drawing</td>
195 *         <td><code>{@link #onDraw}</code></td>
196 *         <td>Called when the view should render its content.
197 *         </td>
198 *     </tr>
199 *
200 *     <tr>
201 *         <td rowspan="4">Event processing</td>
202 *         <td><code>{@link #onKeyDown}</code></td>
203 *         <td>Called when a new key event occurs.
204 *         </td>
205 *     </tr>
206 *     <tr>
207 *         <td><code>{@link #onKeyUp}</code></td>
208 *         <td>Called when a key up event occurs.
209 *         </td>
210 *     </tr>
211 *     <tr>
212 *         <td><code>{@link #onTrackballEvent}</code></td>
213 *         <td>Called when a trackball motion event occurs.
214 *         </td>
215 *     </tr>
216 *     <tr>
217 *         <td><code>{@link #onTouchEvent}</code></td>
218 *         <td>Called when a touch screen motion event occurs.
219 *         </td>
220 *     </tr>
221 *
222 *     <tr>
223 *         <td rowspan="2">Focus</td>
224 *         <td><code>{@link #onFocusChanged}</code></td>
225 *         <td>Called when the view gains or loses focus.
226 *         </td>
227 *     </tr>
228 *
229 *     <tr>
230 *         <td><code>{@link #onWindowFocusChanged}</code></td>
231 *         <td>Called when the window containing the view gains or loses focus.
232 *         </td>
233 *     </tr>
234 *
235 *     <tr>
236 *         <td rowspan="3">Attaching</td>
237 *         <td><code>{@link #onAttachedToWindow()}</code></td>
238 *         <td>Called when the view is attached to a window.
239 *         </td>
240 *     </tr>
241 *
242 *     <tr>
243 *         <td><code>{@link #onDetachedFromWindow}</code></td>
244 *         <td>Called when the view is detached from its window.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td><code>{@link #onWindowVisibilityChanged}</code></td>
250 *         <td>Called when the visibility of the window containing the view
251 *         has changed.
252 *         </td>
253 *     </tr>
254 *     </tbody>
255 *
256 * </table>
257 * </p>
258 *
259 * <a name="IDs"></a>
260 * <h3>IDs</h3>
261 * Views may have an integer id associated with them. These ids are typically
262 * assigned in the layout XML files, and are used to find specific views within
263 * the view tree. A common pattern is to:
264 * <ul>
265 * <li>Define a Button in the layout file and assign it a unique ID.
266 * <pre>
267 * &lt;Button
268 *     android:id="@+id/my_button"
269 *     android:layout_width="wrap_content"
270 *     android:layout_height="wrap_content"
271 *     android:text="@string/my_button_text"/&gt;
272 * </pre></li>
273 * <li>From the onCreate method of an Activity, find the Button
274 * <pre class="prettyprint">
275 *      Button myButton = (Button) findViewById(R.id.my_button);
276 * </pre></li>
277 * </ul>
278 * <p>
279 * View IDs need not be unique throughout the tree, but it is good practice to
280 * ensure that they are at least unique within the part of the tree you are
281 * searching.
282 * </p>
283 *
284 * <a name="Position"></a>
285 * <h3>Position</h3>
286 * <p>
287 * The geometry of a view is that of a rectangle. A view has a location,
288 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
289 * two dimensions, expressed as a width and a height. The unit for location
290 * and dimensions is the pixel.
291 * </p>
292 *
293 * <p>
294 * It is possible to retrieve the location of a view by invoking the methods
295 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
296 * coordinate of the rectangle representing the view. The latter returns the
297 * top, or Y, coordinate of the rectangle representing the view. These methods
298 * both return the location of the view relative to its parent. For instance,
299 * when getLeft() returns 20, that means the view is located 20 pixels to the
300 * right of the left edge of its direct parent.
301 * </p>
302 *
303 * <p>
304 * In addition, several convenience methods are offered to avoid unnecessary
305 * computations, namely {@link #getRight()} and {@link #getBottom()}.
306 * These methods return the coordinates of the right and bottom edges of the
307 * rectangle representing the view. For instance, calling {@link #getRight()}
308 * is similar to the following computation: <code>getLeft() + getWidth()</code>
309 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
310 * </p>
311 *
312 * <a name="SizePaddingMargins"></a>
313 * <h3>Size, padding and margins</h3>
314 * <p>
315 * The size of a view is expressed with a width and a height. A view actually
316 * possess two pairs of width and height values.
317 * </p>
318 *
319 * <p>
320 * The first pair is known as <em>measured width</em> and
321 * <em>measured height</em>. These dimensions define how big a view wants to be
322 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
323 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
324 * and {@link #getMeasuredHeight()}.
325 * </p>
326 *
327 * <p>
328 * The second pair is simply known as <em>width</em> and <em>height</em>, or
329 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
330 * dimensions define the actual size of the view on screen, at drawing time and
331 * after layout. These values may, but do not have to, be different from the
332 * measured width and height. The width and height can be obtained by calling
333 * {@link #getWidth()} and {@link #getHeight()}.
334 * </p>
335 *
336 * <p>
337 * To measure its dimensions, a view takes into account its padding. The padding
338 * is expressed in pixels for the left, top, right and bottom parts of the view.
339 * Padding can be used to offset the content of the view by a specific amount of
340 * pixels. For instance, a left padding of 2 will push the view's content by
341 * 2 pixels to the right of the left edge. Padding can be set using the
342 * {@link #setPadding(int, int, int, int)} method and queried by calling
343 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
344 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
345 * </p>
346 *
347 * <p>
348 * Even though a view can define a padding, it does not provide any support for
349 * margins. However, view groups provide such a support. Refer to
350 * {@link android.view.ViewGroup} and
351 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
352 * </p>
353 *
354 * <a name="Layout"></a>
355 * <h3>Layout</h3>
356 * <p>
357 * Layout is a two pass process: a measure pass and a layout pass. The measuring
358 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
359 * of the view tree. Each view pushes dimension specifications down the tree
360 * during the recursion. At the end of the measure pass, every view has stored
361 * its measurements. The second pass happens in
362 * {@link #layout(int,int,int,int)} and is also top-down. During
363 * this pass each parent is responsible for positioning all of its children
364 * using the sizes computed in the measure pass.
365 * </p>
366 *
367 * <p>
368 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
369 * {@link #getMeasuredHeight()} values must be set, along with those for all of
370 * that view's descendants. A view's measured width and measured height values
371 * must respect the constraints imposed by the view's parents. This guarantees
372 * that at the end of the measure pass, all parents accept all of their
373 * children's measurements. A parent view may call measure() more than once on
374 * its children. For example, the parent may measure each child once with
375 * unspecified dimensions to find out how big they want to be, then call
376 * measure() on them again with actual numbers if the sum of all the children's
377 * unconstrained sizes is too big or too small.
378 * </p>
379 *
380 * <p>
381 * The measure pass uses two classes to communicate dimensions. The
382 * {@link MeasureSpec} class is used by views to tell their parents how they
383 * want to be measured and positioned. The base LayoutParams class just
384 * describes how big the view wants to be for both width and height. For each
385 * dimension, it can specify one of:
386 * <ul>
387 * <li> an exact number
388 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
389 * (minus padding)
390 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
391 * enclose its content (plus padding).
392 * </ul>
393 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
394 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
395 * an X and Y value.
396 * </p>
397 *
398 * <p>
399 * MeasureSpecs are used to push requirements down the tree from parent to
400 * child. A MeasureSpec can be in one of three modes:
401 * <ul>
402 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
403 * of a child view. For example, a LinearLayout may call measure() on its child
404 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
405 * tall the child view wants to be given a width of 240 pixels.
406 * <li>EXACTLY: This is used by the parent to impose an exact size on the
407 * child. The child must use this size, and guarantee that all of its
408 * descendants will fit within this size.
409 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
410 * child. The child must gurantee that it and all of its descendants will fit
411 * within this size.
412 * </ul>
413 * </p>
414 *
415 * <p>
416 * To intiate a layout, call {@link #requestLayout}. This method is typically
417 * called by a view on itself when it believes that is can no longer fit within
418 * its current bounds.
419 * </p>
420 *
421 * <a name="Drawing"></a>
422 * <h3>Drawing</h3>
423 * <p>
424 * Drawing is handled by walking the tree and rendering each view that
425 * intersects the the invalid region. Because the tree is traversed in-order,
426 * this means that parents will draw before (i.e., behind) their children, with
427 * siblings drawn in the order they appear in the tree.
428 * If you set a background drawable for a View, then the View will draw it for you
429 * before calling back to its <code>onDraw()</code> method.
430 * </p>
431 *
432 * <p>
433 * Note that the framework will not draw views that are not in the invalid region.
434 * </p>
435 *
436 * <p>
437 * To force a view to draw, call {@link #invalidate()}.
438 * </p>
439 *
440 * <a name="EventHandlingThreading"></a>
441 * <h3>Event Handling and Threading</h3>
442 * <p>
443 * The basic cycle of a view is as follows:
444 * <ol>
445 * <li>An event comes in and is dispatched to the appropriate view. The view
446 * handles the event and notifies any listeners.</li>
447 * <li>If in the course of processing the event, the view's bounds may need
448 * to be changed, the view will call {@link #requestLayout()}.</li>
449 * <li>Similarly, if in the course of processing the event the view's appearance
450 * may need to be changed, the view will call {@link #invalidate()}.</li>
451 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
452 * the framework will take care of measuring, laying out, and drawing the tree
453 * as appropriate.</li>
454 * </ol>
455 * </p>
456 *
457 * <p><em>Note: The entire view tree is single threaded. You must always be on
458 * the UI thread when calling any method on any view.</em>
459 * If you are doing work on other threads and want to update the state of a view
460 * from that thread, you should use a {@link Handler}.
461 * </p>
462 *
463 * <a name="FocusHandling"></a>
464 * <h3>Focus Handling</h3>
465 * <p>
466 * The framework will handle routine focus movement in response to user input.
467 * This includes changing the focus as views are removed or hidden, or as new
468 * views become available. Views indicate their willingness to take focus
469 * through the {@link #isFocusable} method. To change whether a view can take
470 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
471 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
472 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
473 * </p>
474 * <p>
475 * Focus movement is based on an algorithm which finds the nearest neighbor in a
476 * given direction. In rare cases, the default algorithm may not match the
477 * intended behavior of the developer. In these situations, you can provide
478 * explicit overrides by using these XML attributes in the layout file:
479 * <pre>
480 * nextFocusDown
481 * nextFocusLeft
482 * nextFocusRight
483 * nextFocusUp
484 * </pre>
485 * </p>
486 *
487 *
488 * <p>
489 * To get a particular view to take focus, call {@link #requestFocus()}.
490 * </p>
491 *
492 * <a name="TouchMode"></a>
493 * <h3>Touch Mode</h3>
494 * <p>
495 * When a user is navigating a user interface via directional keys such as a D-pad, it is
496 * necessary to give focus to actionable items such as buttons so the user can see
497 * what will take input.  If the device has touch capabilities, however, and the user
498 * begins interacting with the interface by touching it, it is no longer necessary to
499 * always highlight, or give focus to, a particular view.  This motivates a mode
500 * for interaction named 'touch mode'.
501 * </p>
502 * <p>
503 * For a touch capable device, once the user touches the screen, the device
504 * will enter touch mode.  From this point onward, only views for which
505 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
506 * Other views that are touchable, like buttons, will not take focus when touched; they will
507 * only fire the on click listeners.
508 * </p>
509 * <p>
510 * Any time a user hits a directional key, such as a D-pad direction, the view device will
511 * exit touch mode, and find a view to take focus, so that the user may resume interacting
512 * with the user interface without touching the screen again.
513 * </p>
514 * <p>
515 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
516 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
517 * </p>
518 *
519 * <a name="Scrolling"></a>
520 * <h3>Scrolling</h3>
521 * <p>
522 * The framework provides basic support for views that wish to internally
523 * scroll their content. This includes keeping track of the X and Y scroll
524 * offset as well as mechanisms for drawing scrollbars. See
525 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
526 * {@link #awakenScrollBars()} for more details.
527 * </p>
528 *
529 * <a name="Tags"></a>
530 * <h3>Tags</h3>
531 * <p>
532 * Unlike IDs, tags are not used to identify views. Tags are essentially an
533 * extra piece of information that can be associated with a view. They are most
534 * often used as a convenience to store data related to views in the views
535 * themselves rather than by putting them in a separate structure.
536 * </p>
537 *
538 * <a name="Animation"></a>
539 * <h3>Animation</h3>
540 * <p>
541 * You can attach an {@link Animation} object to a view using
542 * {@link #setAnimation(Animation)} or
543 * {@link #startAnimation(Animation)}. The animation can alter the scale,
544 * rotation, translation and alpha of a view over time. If the animation is
545 * attached to a view that has children, the animation will affect the entire
546 * subtree rooted by that node. When an animation is started, the framework will
547 * take care of redrawing the appropriate views until the animation completes.
548 * </p>
549 * <p>
550 * Starting with Android 3.0, the preferred way of animating views is to use the
551 * {@link android.animation} package APIs.
552 * </p>
553 *
554 * <a name="Security"></a>
555 * <h3>Security</h3>
556 * <p>
557 * Sometimes it is essential that an application be able to verify that an action
558 * is being performed with the full knowledge and consent of the user, such as
559 * granting a permission request, making a purchase or clicking on an advertisement.
560 * Unfortunately, a malicious application could try to spoof the user into
561 * performing these actions, unaware, by concealing the intended purpose of the view.
562 * As a remedy, the framework offers a touch filtering mechanism that can be used to
563 * improve the security of views that provide access to sensitive functionality.
564 * </p><p>
565 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured} or set the
566 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
567 * will discard touches that are received whenever the view's window is obscured by
568 * another visible window.  As a result, the view will not receive touches whenever a
569 * toast, dialog or other window appears above the view's window.
570 * </p><p>
571 * For more fine-grained control over security, consider overriding the
572 * {@link #onFilterTouchEventForSecurity} method to implement your own security policy.
573 * See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
574 * </p>
575 *
576 * @attr ref android.R.styleable#View_alpha
577 * @attr ref android.R.styleable#View_background
578 * @attr ref android.R.styleable#View_clickable
579 * @attr ref android.R.styleable#View_contentDescription
580 * @attr ref android.R.styleable#View_drawingCacheQuality
581 * @attr ref android.R.styleable#View_duplicateParentState
582 * @attr ref android.R.styleable#View_id
583 * @attr ref android.R.styleable#View_fadingEdge
584 * @attr ref android.R.styleable#View_fadingEdgeLength
585 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
586 * @attr ref android.R.styleable#View_fitsSystemWindows
587 * @attr ref android.R.styleable#View_isScrollContainer
588 * @attr ref android.R.styleable#View_focusable
589 * @attr ref android.R.styleable#View_focusableInTouchMode
590 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
591 * @attr ref android.R.styleable#View_keepScreenOn
592 * @attr ref android.R.styleable#View_layerType
593 * @attr ref android.R.styleable#View_longClickable
594 * @attr ref android.R.styleable#View_minHeight
595 * @attr ref android.R.styleable#View_minWidth
596 * @attr ref android.R.styleable#View_nextFocusDown
597 * @attr ref android.R.styleable#View_nextFocusLeft
598 * @attr ref android.R.styleable#View_nextFocusRight
599 * @attr ref android.R.styleable#View_nextFocusUp
600 * @attr ref android.R.styleable#View_onClick
601 * @attr ref android.R.styleable#View_padding
602 * @attr ref android.R.styleable#View_paddingBottom
603 * @attr ref android.R.styleable#View_paddingLeft
604 * @attr ref android.R.styleable#View_paddingRight
605 * @attr ref android.R.styleable#View_paddingTop
606 * @attr ref android.R.styleable#View_saveEnabled
607 * @attr ref android.R.styleable#View_rotation
608 * @attr ref android.R.styleable#View_rotationX
609 * @attr ref android.R.styleable#View_rotationY
610 * @attr ref android.R.styleable#View_scaleX
611 * @attr ref android.R.styleable#View_scaleY
612 * @attr ref android.R.styleable#View_scrollX
613 * @attr ref android.R.styleable#View_scrollY
614 * @attr ref android.R.styleable#View_scrollbarSize
615 * @attr ref android.R.styleable#View_scrollbarStyle
616 * @attr ref android.R.styleable#View_scrollbars
617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
618 * @attr ref android.R.styleable#View_scrollbarFadeDuration
619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
621 * @attr ref android.R.styleable#View_scrollbarThumbVertical
622 * @attr ref android.R.styleable#View_scrollbarTrackVertical
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
625 * @attr ref android.R.styleable#View_soundEffectsEnabled
626 * @attr ref android.R.styleable#View_tag
627 * @attr ref android.R.styleable#View_transformPivotX
628 * @attr ref android.R.styleable#View_transformPivotY
629 * @attr ref android.R.styleable#View_translationX
630 * @attr ref android.R.styleable#View_translationY
631 * @attr ref android.R.styleable#View_visibility
632 *
633 * @see android.view.ViewGroup
634 */
635public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
636    private static final boolean DBG = false;
637
638    /**
639     * The logging tag used by this class with android.util.Log.
640     */
641    protected static final String VIEW_LOG_TAG = "View";
642
643    /**
644     * Used to mark a View that has no ID.
645     */
646    public static final int NO_ID = -1;
647
648    /**
649     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
650     * calling setFlags.
651     */
652    private static final int NOT_FOCUSABLE = 0x00000000;
653
654    /**
655     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
656     * setFlags.
657     */
658    private static final int FOCUSABLE = 0x00000001;
659
660    /**
661     * Mask for use with setFlags indicating bits used for focus.
662     */
663    private static final int FOCUSABLE_MASK = 0x00000001;
664
665    /**
666     * This view will adjust its padding to fit sytem windows (e.g. status bar)
667     */
668    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
669
670    /**
671     * This view is visible.  Use with {@link #setVisibility}.
672     */
673    public static final int VISIBLE = 0x00000000;
674
675    /**
676     * This view is invisible, but it still takes up space for layout purposes.
677     * Use with {@link #setVisibility}.
678     */
679    public static final int INVISIBLE = 0x00000004;
680
681    /**
682     * This view is invisible, and it doesn't take any space for layout
683     * purposes. Use with {@link #setVisibility}.
684     */
685    public static final int GONE = 0x00000008;
686
687    /**
688     * Mask for use with setFlags indicating bits used for visibility.
689     * {@hide}
690     */
691    static final int VISIBILITY_MASK = 0x0000000C;
692
693    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
694
695    /**
696     * This view is enabled. Intrepretation varies by subclass.
697     * Use with ENABLED_MASK when calling setFlags.
698     * {@hide}
699     */
700    static final int ENABLED = 0x00000000;
701
702    /**
703     * This view is disabled. Intrepretation varies by subclass.
704     * Use with ENABLED_MASK when calling setFlags.
705     * {@hide}
706     */
707    static final int DISABLED = 0x00000020;
708
709   /**
710    * Mask for use with setFlags indicating bits used for indicating whether
711    * this view is enabled
712    * {@hide}
713    */
714    static final int ENABLED_MASK = 0x00000020;
715
716    /**
717     * This view won't draw. {@link #onDraw} won't be called and further
718     * optimizations
719     * will be performed. It is okay to have this flag set and a background.
720     * Use with DRAW_MASK when calling setFlags.
721     * {@hide}
722     */
723    static final int WILL_NOT_DRAW = 0x00000080;
724
725    /**
726     * Mask for use with setFlags indicating bits used for indicating whether
727     * this view is will draw
728     * {@hide}
729     */
730    static final int DRAW_MASK = 0x00000080;
731
732    /**
733     * <p>This view doesn't show scrollbars.</p>
734     * {@hide}
735     */
736    static final int SCROLLBARS_NONE = 0x00000000;
737
738    /**
739     * <p>This view shows horizontal scrollbars.</p>
740     * {@hide}
741     */
742    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
743
744    /**
745     * <p>This view shows vertical scrollbars.</p>
746     * {@hide}
747     */
748    static final int SCROLLBARS_VERTICAL = 0x00000200;
749
750    /**
751     * <p>Mask for use with setFlags indicating bits used for indicating which
752     * scrollbars are enabled.</p>
753     * {@hide}
754     */
755    static final int SCROLLBARS_MASK = 0x00000300;
756
757    /**
758     * Indicates that the view should filter touches when its window is obscured.
759     * Refer to the class comments for more information about this security feature.
760     * {@hide}
761     */
762    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
763
764    // note flag value 0x00000800 is now available for next flags...
765
766    /**
767     * <p>This view doesn't show fading edges.</p>
768     * {@hide}
769     */
770    static final int FADING_EDGE_NONE = 0x00000000;
771
772    /**
773     * <p>This view shows horizontal fading edges.</p>
774     * {@hide}
775     */
776    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
777
778    /**
779     * <p>This view shows vertical fading edges.</p>
780     * {@hide}
781     */
782    static final int FADING_EDGE_VERTICAL = 0x00002000;
783
784    /**
785     * <p>Mask for use with setFlags indicating bits used for indicating which
786     * fading edges are enabled.</p>
787     * {@hide}
788     */
789    static final int FADING_EDGE_MASK = 0x00003000;
790
791    /**
792     * <p>Indicates this view can be clicked. When clickable, a View reacts
793     * to clicks by notifying the OnClickListener.<p>
794     * {@hide}
795     */
796    static final int CLICKABLE = 0x00004000;
797
798    /**
799     * <p>Indicates this view is caching its drawing into a bitmap.</p>
800     * {@hide}
801     */
802    static final int DRAWING_CACHE_ENABLED = 0x00008000;
803
804    /**
805     * <p>Indicates that no icicle should be saved for this view.<p>
806     * {@hide}
807     */
808    static final int SAVE_DISABLED = 0x000010000;
809
810    /**
811     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
812     * property.</p>
813     * {@hide}
814     */
815    static final int SAVE_DISABLED_MASK = 0x000010000;
816
817    /**
818     * <p>Indicates that no drawing cache should ever be created for this view.<p>
819     * {@hide}
820     */
821    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
822
823    /**
824     * <p>Indicates this view can take / keep focus when int touch mode.</p>
825     * {@hide}
826     */
827    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
828
829    /**
830     * <p>Enables low quality mode for the drawing cache.</p>
831     */
832    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
833
834    /**
835     * <p>Enables high quality mode for the drawing cache.</p>
836     */
837    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
838
839    /**
840     * <p>Enables automatic quality mode for the drawing cache.</p>
841     */
842    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
843
844    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
845            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
846    };
847
848    /**
849     * <p>Mask for use with setFlags indicating bits used for the cache
850     * quality property.</p>
851     * {@hide}
852     */
853    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
854
855    /**
856     * <p>
857     * Indicates this view can be long clicked. When long clickable, a View
858     * reacts to long clicks by notifying the OnLongClickListener or showing a
859     * context menu.
860     * </p>
861     * {@hide}
862     */
863    static final int LONG_CLICKABLE = 0x00200000;
864
865    /**
866     * <p>Indicates that this view gets its drawable states from its direct parent
867     * and ignores its original internal states.</p>
868     *
869     * @hide
870     */
871    static final int DUPLICATE_PARENT_STATE = 0x00400000;
872
873    /**
874     * The scrollbar style to display the scrollbars inside the content area,
875     * without increasing the padding. The scrollbars will be overlaid with
876     * translucency on the view's content.
877     */
878    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
879
880    /**
881     * The scrollbar style to display the scrollbars inside the padded area,
882     * increasing the padding of the view. The scrollbars will not overlap the
883     * content area of the view.
884     */
885    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
886
887    /**
888     * The scrollbar style to display the scrollbars at the edge of the view,
889     * without increasing the padding. The scrollbars will be overlaid with
890     * translucency.
891     */
892    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
893
894    /**
895     * The scrollbar style to display the scrollbars at the edge of the view,
896     * increasing the padding of the view. The scrollbars will only overlap the
897     * background, if any.
898     */
899    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
900
901    /**
902     * Mask to check if the scrollbar style is overlay or inset.
903     * {@hide}
904     */
905    static final int SCROLLBARS_INSET_MASK = 0x01000000;
906
907    /**
908     * Mask to check if the scrollbar style is inside or outside.
909     * {@hide}
910     */
911    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
912
913    /**
914     * Mask for scrollbar style.
915     * {@hide}
916     */
917    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
918
919    /**
920     * View flag indicating that the screen should remain on while the
921     * window containing this view is visible to the user.  This effectively
922     * takes care of automatically setting the WindowManager's
923     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
924     */
925    public static final int KEEP_SCREEN_ON = 0x04000000;
926
927    /**
928     * View flag indicating whether this view should have sound effects enabled
929     * for events such as clicking and touching.
930     */
931    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
932
933    /**
934     * View flag indicating whether this view should have haptic feedback
935     * enabled for events such as long presses.
936     */
937    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
938
939    /**
940     * <p>Indicates that the view hierarchy should stop saving state when
941     * it reaches this view.  If state saving is initiated immediately at
942     * the view, it will be allowed.
943     * {@hide}
944     */
945    static final int PARENT_SAVE_DISABLED = 0x20000000;
946
947    /**
948     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
949     * {@hide}
950     */
951    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
952
953    /**
954     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
955     * should add all focusable Views regardless if they are focusable in touch mode.
956     */
957    public static final int FOCUSABLES_ALL = 0x00000000;
958
959    /**
960     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
961     * should add only Views focusable in touch mode.
962     */
963    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
964
965    /**
966     * Use with {@link #focusSearch}. Move focus to the previous selectable
967     * item.
968     */
969    public static final int FOCUS_BACKWARD = 0x00000001;
970
971    /**
972     * Use with {@link #focusSearch}. Move focus to the next selectable
973     * item.
974     */
975    public static final int FOCUS_FORWARD = 0x00000002;
976
977    /**
978     * Use with {@link #focusSearch}. Move focus to the left.
979     */
980    public static final int FOCUS_LEFT = 0x00000011;
981
982    /**
983     * Use with {@link #focusSearch}. Move focus up.
984     */
985    public static final int FOCUS_UP = 0x00000021;
986
987    /**
988     * Use with {@link #focusSearch}. Move focus to the right.
989     */
990    public static final int FOCUS_RIGHT = 0x00000042;
991
992    /**
993     * Use with {@link #focusSearch}. Move focus down.
994     */
995    public static final int FOCUS_DOWN = 0x00000082;
996
997    /**
998     * Bits of {@link #getMeasuredWidthAndState()} and
999     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1000     */
1001    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1002
1003    /**
1004     * Bits of {@link #getMeasuredWidthAndState()} and
1005     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1006     */
1007    public static final int MEASURED_STATE_MASK = 0xff000000;
1008
1009    /**
1010     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1011     * for functions that combine both width and height into a single int,
1012     * such as {@link #getMeasuredState()} and the childState argument of
1013     * {@link #resolveSizeAndState(int, int, int)}.
1014     */
1015    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1016
1017    /**
1018     * Bit of {@link #getMeasuredWidthAndState()} and
1019     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1020     * is smaller that the space the view would like to have.
1021     */
1022    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1023
1024    /**
1025     * Base View state sets
1026     */
1027    // Singles
1028    /**
1029     * Indicates the view has no states set. States are used with
1030     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1031     * view depending on its state.
1032     *
1033     * @see android.graphics.drawable.Drawable
1034     * @see #getDrawableState()
1035     */
1036    protected static final int[] EMPTY_STATE_SET;
1037    /**
1038     * Indicates the view is enabled. States are used with
1039     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1040     * view depending on its state.
1041     *
1042     * @see android.graphics.drawable.Drawable
1043     * @see #getDrawableState()
1044     */
1045    protected static final int[] ENABLED_STATE_SET;
1046    /**
1047     * Indicates the view is focused. States are used with
1048     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1049     * view depending on its state.
1050     *
1051     * @see android.graphics.drawable.Drawable
1052     * @see #getDrawableState()
1053     */
1054    protected static final int[] FOCUSED_STATE_SET;
1055    /**
1056     * Indicates the view is selected. States are used with
1057     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1058     * view depending on its state.
1059     *
1060     * @see android.graphics.drawable.Drawable
1061     * @see #getDrawableState()
1062     */
1063    protected static final int[] SELECTED_STATE_SET;
1064    /**
1065     * Indicates the view is pressed. States are used with
1066     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1067     * view depending on its state.
1068     *
1069     * @see android.graphics.drawable.Drawable
1070     * @see #getDrawableState()
1071     * @hide
1072     */
1073    protected static final int[] PRESSED_STATE_SET;
1074    /**
1075     * Indicates the view's window has focus. States are used with
1076     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1077     * view depending on its state.
1078     *
1079     * @see android.graphics.drawable.Drawable
1080     * @see #getDrawableState()
1081     */
1082    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1083    // Doubles
1084    /**
1085     * Indicates the view is enabled and has the focus.
1086     *
1087     * @see #ENABLED_STATE_SET
1088     * @see #FOCUSED_STATE_SET
1089     */
1090    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1091    /**
1092     * Indicates the view is enabled and selected.
1093     *
1094     * @see #ENABLED_STATE_SET
1095     * @see #SELECTED_STATE_SET
1096     */
1097    protected static final int[] ENABLED_SELECTED_STATE_SET;
1098    /**
1099     * Indicates the view is enabled and that its window has focus.
1100     *
1101     * @see #ENABLED_STATE_SET
1102     * @see #WINDOW_FOCUSED_STATE_SET
1103     */
1104    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1105    /**
1106     * Indicates the view is focused and selected.
1107     *
1108     * @see #FOCUSED_STATE_SET
1109     * @see #SELECTED_STATE_SET
1110     */
1111    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1112    /**
1113     * Indicates the view has the focus and that its window has the focus.
1114     *
1115     * @see #FOCUSED_STATE_SET
1116     * @see #WINDOW_FOCUSED_STATE_SET
1117     */
1118    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1119    /**
1120     * Indicates the view is selected and that its window has the focus.
1121     *
1122     * @see #SELECTED_STATE_SET
1123     * @see #WINDOW_FOCUSED_STATE_SET
1124     */
1125    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1126    // Triples
1127    /**
1128     * Indicates the view is enabled, focused and selected.
1129     *
1130     * @see #ENABLED_STATE_SET
1131     * @see #FOCUSED_STATE_SET
1132     * @see #SELECTED_STATE_SET
1133     */
1134    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1135    /**
1136     * Indicates the view is enabled, focused and its window has the focus.
1137     *
1138     * @see #ENABLED_STATE_SET
1139     * @see #FOCUSED_STATE_SET
1140     * @see #WINDOW_FOCUSED_STATE_SET
1141     */
1142    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1143    /**
1144     * Indicates the view is enabled, selected and its window has the focus.
1145     *
1146     * @see #ENABLED_STATE_SET
1147     * @see #SELECTED_STATE_SET
1148     * @see #WINDOW_FOCUSED_STATE_SET
1149     */
1150    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1151    /**
1152     * Indicates the view is focused, selected and its window has the focus.
1153     *
1154     * @see #FOCUSED_STATE_SET
1155     * @see #SELECTED_STATE_SET
1156     * @see #WINDOW_FOCUSED_STATE_SET
1157     */
1158    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1159    /**
1160     * Indicates the view is enabled, focused, selected and its window
1161     * has the focus.
1162     *
1163     * @see #ENABLED_STATE_SET
1164     * @see #FOCUSED_STATE_SET
1165     * @see #SELECTED_STATE_SET
1166     * @see #WINDOW_FOCUSED_STATE_SET
1167     */
1168    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1169    /**
1170     * Indicates the view is pressed and its window has the focus.
1171     *
1172     * @see #PRESSED_STATE_SET
1173     * @see #WINDOW_FOCUSED_STATE_SET
1174     */
1175    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1176    /**
1177     * Indicates the view is pressed and selected.
1178     *
1179     * @see #PRESSED_STATE_SET
1180     * @see #SELECTED_STATE_SET
1181     */
1182    protected static final int[] PRESSED_SELECTED_STATE_SET;
1183    /**
1184     * Indicates the view is pressed, selected and its window has the focus.
1185     *
1186     * @see #PRESSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     * @see #WINDOW_FOCUSED_STATE_SET
1189     */
1190    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1191    /**
1192     * Indicates the view is pressed and focused.
1193     *
1194     * @see #PRESSED_STATE_SET
1195     * @see #FOCUSED_STATE_SET
1196     */
1197    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is pressed, focused and its window has the focus.
1200     *
1201     * @see #PRESSED_STATE_SET
1202     * @see #FOCUSED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is pressed, focused and selected.
1208     *
1209     * @see #PRESSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #FOCUSED_STATE_SET
1212     */
1213    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1214    /**
1215     * Indicates the view is pressed, focused, selected and its window has the focus.
1216     *
1217     * @see #PRESSED_STATE_SET
1218     * @see #FOCUSED_STATE_SET
1219     * @see #SELECTED_STATE_SET
1220     * @see #WINDOW_FOCUSED_STATE_SET
1221     */
1222    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed and enabled.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #ENABLED_STATE_SET
1228     */
1229    protected static final int[] PRESSED_ENABLED_STATE_SET;
1230    /**
1231     * Indicates the view is pressed, enabled and its window has the focus.
1232     *
1233     * @see #PRESSED_STATE_SET
1234     * @see #ENABLED_STATE_SET
1235     * @see #WINDOW_FOCUSED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, enabled and selected.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #ENABLED_STATE_SET
1243     * @see #SELECTED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed, enabled, selected and its window has the
1248     * focus.
1249     *
1250     * @see #PRESSED_STATE_SET
1251     * @see #ENABLED_STATE_SET
1252     * @see #SELECTED_STATE_SET
1253     * @see #WINDOW_FOCUSED_STATE_SET
1254     */
1255    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1256    /**
1257     * Indicates the view is pressed, enabled and focused.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #ENABLED_STATE_SET
1261     * @see #FOCUSED_STATE_SET
1262     */
1263    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1264    /**
1265     * Indicates the view is pressed, enabled, focused and its window has the
1266     * focus.
1267     *
1268     * @see #PRESSED_STATE_SET
1269     * @see #ENABLED_STATE_SET
1270     * @see #FOCUSED_STATE_SET
1271     * @see #WINDOW_FOCUSED_STATE_SET
1272     */
1273    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1274    /**
1275     * Indicates the view is pressed, enabled, focused and selected.
1276     *
1277     * @see #PRESSED_STATE_SET
1278     * @see #ENABLED_STATE_SET
1279     * @see #SELECTED_STATE_SET
1280     * @see #FOCUSED_STATE_SET
1281     */
1282    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1283    /**
1284     * Indicates the view is pressed, enabled, focused, selected and its window
1285     * has the focus.
1286     *
1287     * @see #PRESSED_STATE_SET
1288     * @see #ENABLED_STATE_SET
1289     * @see #SELECTED_STATE_SET
1290     * @see #FOCUSED_STATE_SET
1291     * @see #WINDOW_FOCUSED_STATE_SET
1292     */
1293    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1294
1295    /**
1296     * The order here is very important to {@link #getDrawableState()}
1297     */
1298    private static final int[][] VIEW_STATE_SETS;
1299
1300    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1301    static final int VIEW_STATE_SELECTED = 1 << 1;
1302    static final int VIEW_STATE_FOCUSED = 1 << 2;
1303    static final int VIEW_STATE_ENABLED = 1 << 3;
1304    static final int VIEW_STATE_PRESSED = 1 << 4;
1305    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1306    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1307
1308    static final int[] VIEW_STATE_IDS = new int[] {
1309        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1310        R.attr.state_selected,          VIEW_STATE_SELECTED,
1311        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1312        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1313        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1314        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1315        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1316    };
1317
1318    static {
1319        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1320            throw new IllegalStateException(
1321                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1322        }
1323        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1324        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1325            int viewState = R.styleable.ViewDrawableStates[i];
1326            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1327                if (VIEW_STATE_IDS[j] == viewState) {
1328                    orderedIds[i * 2] = viewState;
1329                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1330                }
1331            }
1332        }
1333        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1334        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1335        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1336            int numBits = Integer.bitCount(i);
1337            int[] set = new int[numBits];
1338            int pos = 0;
1339            for (int j = 0; j < orderedIds.length; j += 2) {
1340                if ((i & orderedIds[j+1]) != 0) {
1341                    set[pos++] = orderedIds[j];
1342                }
1343            }
1344            VIEW_STATE_SETS[i] = set;
1345        }
1346
1347        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1348        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1349        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1350        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1351                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1352        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1353        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1354                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1355        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1356                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1357        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1358                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1359                | VIEW_STATE_FOCUSED];
1360        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1361        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1362                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1363        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1364                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1365        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1366                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1367                | VIEW_STATE_ENABLED];
1368        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1369                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1370        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1371                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1372                | VIEW_STATE_ENABLED];
1373        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1374                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1375                | VIEW_STATE_ENABLED];
1376        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1377                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1378                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1379
1380        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1381        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1382                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1383        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1384                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1385        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1386                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1387                | VIEW_STATE_PRESSED];
1388        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1389                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1390        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1391                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1392                | VIEW_STATE_PRESSED];
1393        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1394                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1395                | VIEW_STATE_PRESSED];
1396        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1397                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1398                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1399        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1400                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1401        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1402                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1403                | VIEW_STATE_PRESSED];
1404        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1405                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1406                | VIEW_STATE_PRESSED];
1407        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1409                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1410        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1412                | VIEW_STATE_PRESSED];
1413        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1415                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1416        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1418                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1419        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1421                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1422                | VIEW_STATE_PRESSED];
1423    }
1424
1425    /**
1426     * Used by views that contain lists of items. This state indicates that
1427     * the view is showing the last item.
1428     * @hide
1429     */
1430    protected static final int[] LAST_STATE_SET = {R.attr.state_last};
1431    /**
1432     * Used by views that contain lists of items. This state indicates that
1433     * the view is showing the first item.
1434     * @hide
1435     */
1436    protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
1437    /**
1438     * Used by views that contain lists of items. This state indicates that
1439     * the view is showing the middle item.
1440     * @hide
1441     */
1442    protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
1443    /**
1444     * Used by views that contain lists of items. This state indicates that
1445     * the view is showing only one item.
1446     * @hide
1447     */
1448    protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
1449    /**
1450     * Used by views that contain lists of items. This state indicates that
1451     * the view is pressed and showing the last item.
1452     * @hide
1453     */
1454    protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
1455    /**
1456     * Used by views that contain lists of items. This state indicates that
1457     * the view is pressed and showing the first item.
1458     * @hide
1459     */
1460    protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
1461    /**
1462     * Used by views that contain lists of items. This state indicates that
1463     * the view is pressed and showing the middle item.
1464     * @hide
1465     */
1466    protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
1467    /**
1468     * Used by views that contain lists of items. This state indicates that
1469     * the view is pressed and showing only one item.
1470     * @hide
1471     */
1472    protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
1473
1474    /**
1475     * Temporary Rect currently for use in setBackground().  This will probably
1476     * be extended in the future to hold our own class with more than just
1477     * a Rect. :)
1478     */
1479    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1480
1481    /**
1482     * Map used to store views' tags.
1483     */
1484    private static WeakHashMap<View, SparseArray<Object>> sTags;
1485
1486    /**
1487     * Lock used to access sTags.
1488     */
1489    private static final Object sTagsLock = new Object();
1490
1491    /**
1492     * The animation currently associated with this view.
1493     * @hide
1494     */
1495    protected Animation mCurrentAnimation = null;
1496
1497    /**
1498     * Width as measured during measure pass.
1499     * {@hide}
1500     */
1501    @ViewDebug.ExportedProperty(category = "measurement")
1502    /*package*/ int mMeasuredWidth;
1503
1504    /**
1505     * Height as measured during measure pass.
1506     * {@hide}
1507     */
1508    @ViewDebug.ExportedProperty(category = "measurement")
1509    /*package*/ int mMeasuredHeight;
1510
1511    /**
1512     * The view's identifier.
1513     * {@hide}
1514     *
1515     * @see #setId(int)
1516     * @see #getId()
1517     */
1518    @ViewDebug.ExportedProperty(resolveId = true)
1519    int mID = NO_ID;
1520
1521    /**
1522     * The view's tag.
1523     * {@hide}
1524     *
1525     * @see #setTag(Object)
1526     * @see #getTag()
1527     */
1528    protected Object mTag;
1529
1530    // for mPrivateFlags:
1531    /** {@hide} */
1532    static final int WANTS_FOCUS                    = 0x00000001;
1533    /** {@hide} */
1534    static final int FOCUSED                        = 0x00000002;
1535    /** {@hide} */
1536    static final int SELECTED                       = 0x00000004;
1537    /** {@hide} */
1538    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1539    /** {@hide} */
1540    static final int HAS_BOUNDS                     = 0x00000010;
1541    /** {@hide} */
1542    static final int DRAWN                          = 0x00000020;
1543    /**
1544     * When this flag is set, this view is running an animation on behalf of its
1545     * children and should therefore not cancel invalidate requests, even if they
1546     * lie outside of this view's bounds.
1547     *
1548     * {@hide}
1549     */
1550    static final int DRAW_ANIMATION                 = 0x00000040;
1551    /** {@hide} */
1552    static final int SKIP_DRAW                      = 0x00000080;
1553    /** {@hide} */
1554    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1555    /** {@hide} */
1556    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1557    /** {@hide} */
1558    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1559    /** {@hide} */
1560    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1561    /** {@hide} */
1562    static final int FORCE_LAYOUT                   = 0x00001000;
1563    /** {@hide} */
1564    static final int LAYOUT_REQUIRED                = 0x00002000;
1565
1566    private static final int PRESSED                = 0x00004000;
1567
1568    /** {@hide} */
1569    static final int DRAWING_CACHE_VALID            = 0x00008000;
1570    /**
1571     * Flag used to indicate that this view should be drawn once more (and only once
1572     * more) after its animation has completed.
1573     * {@hide}
1574     */
1575    static final int ANIMATION_STARTED              = 0x00010000;
1576
1577    private static final int SAVE_STATE_CALLED      = 0x00020000;
1578
1579    /**
1580     * Indicates that the View returned true when onSetAlpha() was called and that
1581     * the alpha must be restored.
1582     * {@hide}
1583     */
1584    static final int ALPHA_SET                      = 0x00040000;
1585
1586    /**
1587     * Set by {@link #setScrollContainer(boolean)}.
1588     */
1589    static final int SCROLL_CONTAINER               = 0x00080000;
1590
1591    /**
1592     * Set by {@link #setScrollContainer(boolean)}.
1593     */
1594    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1595
1596    /**
1597     * View flag indicating whether this view was invalidated (fully or partially.)
1598     *
1599     * @hide
1600     */
1601    static final int DIRTY                          = 0x00200000;
1602
1603    /**
1604     * View flag indicating whether this view was invalidated by an opaque
1605     * invalidate request.
1606     *
1607     * @hide
1608     */
1609    static final int DIRTY_OPAQUE                   = 0x00400000;
1610
1611    /**
1612     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1613     *
1614     * @hide
1615     */
1616    static final int DIRTY_MASK                     = 0x00600000;
1617
1618    /**
1619     * Indicates whether the background is opaque.
1620     *
1621     * @hide
1622     */
1623    static final int OPAQUE_BACKGROUND              = 0x00800000;
1624
1625    /**
1626     * Indicates whether the scrollbars are opaque.
1627     *
1628     * @hide
1629     */
1630    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1631
1632    /**
1633     * Indicates whether the view is opaque.
1634     *
1635     * @hide
1636     */
1637    static final int OPAQUE_MASK                    = 0x01800000;
1638
1639    /**
1640     * Indicates a prepressed state;
1641     * the short time between ACTION_DOWN and recognizing
1642     * a 'real' press. Prepressed is used to recognize quick taps
1643     * even when they are shorter than ViewConfiguration.getTapTimeout().
1644     *
1645     * @hide
1646     */
1647    private static final int PREPRESSED             = 0x02000000;
1648
1649    /**
1650     * Indicates whether the view is temporarily detached.
1651     *
1652     * @hide
1653     */
1654    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1655
1656    /**
1657     * Indicates that we should awaken scroll bars once attached
1658     *
1659     * @hide
1660     */
1661    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1662
1663    /**
1664     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1665     * for transform operations
1666     *
1667     * @hide
1668     */
1669    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1670
1671    /** {@hide} */
1672    static final int ACTIVATED                    = 0x40000000;
1673
1674    /**
1675     * Always allow a user to over-scroll this view, provided it is a
1676     * view that can scroll.
1677     *
1678     * @see #getOverScrollMode()
1679     * @see #setOverScrollMode(int)
1680     */
1681    public static final int OVER_SCROLL_ALWAYS = 0;
1682
1683    /**
1684     * Allow a user to over-scroll this view only if the content is large
1685     * enough to meaningfully scroll, provided it is a view that can scroll.
1686     *
1687     * @see #getOverScrollMode()
1688     * @see #setOverScrollMode(int)
1689     */
1690    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1691
1692    /**
1693     * Never allow a user to over-scroll this view.
1694     *
1695     * @see #getOverScrollMode()
1696     * @see #setOverScrollMode(int)
1697     */
1698    public static final int OVER_SCROLL_NEVER = 2;
1699
1700    /**
1701     * Controls the over-scroll mode for this view.
1702     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1703     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1704     * and {@link #OVER_SCROLL_NEVER}.
1705     */
1706    private int mOverScrollMode;
1707
1708    /**
1709     * The parent this view is attached to.
1710     * {@hide}
1711     *
1712     * @see #getParent()
1713     */
1714    protected ViewParent mParent;
1715
1716    /**
1717     * {@hide}
1718     */
1719    AttachInfo mAttachInfo;
1720
1721    /**
1722     * {@hide}
1723     */
1724    @ViewDebug.ExportedProperty(flagMapping = {
1725        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1726                name = "FORCE_LAYOUT"),
1727        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1728                name = "LAYOUT_REQUIRED"),
1729        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1730            name = "DRAWING_CACHE_INVALID", outputIf = false),
1731        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1732        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1733        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1734        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1735    })
1736    int mPrivateFlags;
1737
1738    /**
1739     * Count of how many windows this view has been attached to.
1740     */
1741    int mWindowAttachCount;
1742
1743    /**
1744     * The layout parameters associated with this view and used by the parent
1745     * {@link android.view.ViewGroup} to determine how this view should be
1746     * laid out.
1747     * {@hide}
1748     */
1749    protected ViewGroup.LayoutParams mLayoutParams;
1750
1751    /**
1752     * The view flags hold various views states.
1753     * {@hide}
1754     */
1755    @ViewDebug.ExportedProperty
1756    int mViewFlags;
1757
1758    /**
1759     * The transform matrix for the View. This transform is calculated internally
1760     * based on the rotation, scaleX, and scaleY properties. The identity matrix
1761     * is used by default. Do *not* use this variable directly; instead call
1762     * getMatrix(), which will automatically recalculate the matrix if necessary
1763     * to get the correct matrix based on the latest rotation and scale properties.
1764     */
1765    private final Matrix mMatrix = new Matrix();
1766
1767    /**
1768     * The transform matrix for the View. This transform is calculated internally
1769     * based on the rotation, scaleX, and scaleY properties. The identity matrix
1770     * is used by default. Do *not* use this variable directly; instead call
1771     * getInverseMatrix(), which will automatically recalculate the matrix if necessary
1772     * to get the correct matrix based on the latest rotation and scale properties.
1773     */
1774    private Matrix mInverseMatrix;
1775
1776    /**
1777     * An internal variable that tracks whether we need to recalculate the
1778     * transform matrix, based on whether the rotation or scaleX/Y properties
1779     * have changed since the matrix was last calculated.
1780     */
1781    private boolean mMatrixDirty = false;
1782
1783    /**
1784     * An internal variable that tracks whether we need to recalculate the
1785     * transform matrix, based on whether the rotation or scaleX/Y properties
1786     * have changed since the matrix was last calculated.
1787     */
1788    private boolean mInverseMatrixDirty = true;
1789
1790    /**
1791     * A variable that tracks whether we need to recalculate the
1792     * transform matrix, based on whether the rotation or scaleX/Y properties
1793     * have changed since the matrix was last calculated. This variable
1794     * is only valid after a call to updateMatrix() or to a function that
1795     * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
1796     */
1797    private boolean mMatrixIsIdentity = true;
1798
1799    /**
1800     * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1801     */
1802    private Camera mCamera = null;
1803
1804    /**
1805     * This matrix is used when computing the matrix for 3D rotations.
1806     */
1807    private Matrix matrix3D = null;
1808
1809    /**
1810     * These prev values are used to recalculate a centered pivot point when necessary. The
1811     * pivot point is only used in matrix operations (when rotation, scale, or translation are
1812     * set), so thes values are only used then as well.
1813     */
1814    private int mPrevWidth = -1;
1815    private int mPrevHeight = -1;
1816
1817    /**
1818     * Convenience value to check for float values that are close enough to zero to be considered
1819     * zero.
1820     */
1821    private static final float NONZERO_EPSILON = .001f;
1822
1823    /**
1824     * The degrees rotation around the vertical axis through the pivot point.
1825     */
1826    @ViewDebug.ExportedProperty
1827    private float mRotationY = 0f;
1828
1829    /**
1830     * The degrees rotation around the horizontal axis through the pivot point.
1831     */
1832    @ViewDebug.ExportedProperty
1833    private float mRotationX = 0f;
1834
1835    /**
1836     * The degrees rotation around the pivot point.
1837     */
1838    @ViewDebug.ExportedProperty
1839    private float mRotation = 0f;
1840
1841    /**
1842     * The amount of translation of the object away from its left property (post-layout).
1843     */
1844    @ViewDebug.ExportedProperty
1845    private float mTranslationX = 0f;
1846
1847    /**
1848     * The amount of translation of the object away from its top property (post-layout).
1849     */
1850    @ViewDebug.ExportedProperty
1851    private float mTranslationY = 0f;
1852
1853    /**
1854     * The amount of scale in the x direction around the pivot point. A
1855     * value of 1 means no scaling is applied.
1856     */
1857    @ViewDebug.ExportedProperty
1858    private float mScaleX = 1f;
1859
1860    /**
1861     * The amount of scale in the y direction around the pivot point. A
1862     * value of 1 means no scaling is applied.
1863     */
1864    @ViewDebug.ExportedProperty
1865    private float mScaleY = 1f;
1866
1867    /**
1868     * The amount of scale in the x direction around the pivot point. A
1869     * value of 1 means no scaling is applied.
1870     */
1871    @ViewDebug.ExportedProperty
1872    private float mPivotX = 0f;
1873
1874    /**
1875     * The amount of scale in the y direction around the pivot point. A
1876     * value of 1 means no scaling is applied.
1877     */
1878    @ViewDebug.ExportedProperty
1879    private float mPivotY = 0f;
1880
1881    /**
1882     * The opacity of the View. This is a value from 0 to 1, where 0 means
1883     * completely transparent and 1 means completely opaque.
1884     */
1885    @ViewDebug.ExportedProperty
1886    private float mAlpha = 1f;
1887
1888    /**
1889     * The distance in pixels from the left edge of this view's parent
1890     * to the left edge of this view.
1891     * {@hide}
1892     */
1893    @ViewDebug.ExportedProperty(category = "layout")
1894    protected int mLeft;
1895    /**
1896     * The distance in pixels from the left edge of this view's parent
1897     * to the right edge of this view.
1898     * {@hide}
1899     */
1900    @ViewDebug.ExportedProperty(category = "layout")
1901    protected int mRight;
1902    /**
1903     * The distance in pixels from the top edge of this view's parent
1904     * to the top edge of this view.
1905     * {@hide}
1906     */
1907    @ViewDebug.ExportedProperty(category = "layout")
1908    protected int mTop;
1909    /**
1910     * The distance in pixels from the top edge of this view's parent
1911     * to the bottom edge of this view.
1912     * {@hide}
1913     */
1914    @ViewDebug.ExportedProperty(category = "layout")
1915    protected int mBottom;
1916
1917    /**
1918     * The offset, in pixels, by which the content of this view is scrolled
1919     * horizontally.
1920     * {@hide}
1921     */
1922    @ViewDebug.ExportedProperty(category = "scrolling")
1923    protected int mScrollX;
1924    /**
1925     * The offset, in pixels, by which the content of this view is scrolled
1926     * vertically.
1927     * {@hide}
1928     */
1929    @ViewDebug.ExportedProperty(category = "scrolling")
1930    protected int mScrollY;
1931
1932    /**
1933     * The left padding in pixels, that is the distance in pixels between the
1934     * left edge of this view and the left edge of its content.
1935     * {@hide}
1936     */
1937    @ViewDebug.ExportedProperty(category = "padding")
1938    protected int mPaddingLeft;
1939    /**
1940     * The right padding in pixels, that is the distance in pixels between the
1941     * right edge of this view and the right edge of its content.
1942     * {@hide}
1943     */
1944    @ViewDebug.ExportedProperty(category = "padding")
1945    protected int mPaddingRight;
1946    /**
1947     * The top padding in pixels, that is the distance in pixels between the
1948     * top edge of this view and the top edge of its content.
1949     * {@hide}
1950     */
1951    @ViewDebug.ExportedProperty(category = "padding")
1952    protected int mPaddingTop;
1953    /**
1954     * The bottom padding in pixels, that is the distance in pixels between the
1955     * bottom edge of this view and the bottom edge of its content.
1956     * {@hide}
1957     */
1958    @ViewDebug.ExportedProperty(category = "padding")
1959    protected int mPaddingBottom;
1960
1961    /**
1962     * Briefly describes the view and is primarily used for accessibility support.
1963     */
1964    private CharSequence mContentDescription;
1965
1966    /**
1967     * Cache the paddingRight set by the user to append to the scrollbar's size.
1968     */
1969    @ViewDebug.ExportedProperty(category = "padding")
1970    int mUserPaddingRight;
1971
1972    /**
1973     * Cache the paddingBottom set by the user to append to the scrollbar's size.
1974     */
1975    @ViewDebug.ExportedProperty(category = "padding")
1976    int mUserPaddingBottom;
1977
1978    /**
1979     * Cache the paddingLeft set by the user to append to the scrollbar's size.
1980     */
1981    @ViewDebug.ExportedProperty(category = "padding")
1982    int mUserPaddingLeft;
1983
1984    /**
1985     * @hide
1986     */
1987    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
1988    /**
1989     * @hide
1990     */
1991    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
1992
1993    private Resources mResources = null;
1994
1995    private Drawable mBGDrawable;
1996
1997    private int mBackgroundResource;
1998    private boolean mBackgroundSizeChanged;
1999
2000    /**
2001     * Listener used to dispatch focus change events.
2002     * This field should be made private, so it is hidden from the SDK.
2003     * {@hide}
2004     */
2005    protected OnFocusChangeListener mOnFocusChangeListener;
2006
2007    /**
2008     * Listeners for layout change events.
2009     */
2010    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2011
2012    /**
2013     * Listener used to dispatch click events.
2014     * This field should be made private, so it is hidden from the SDK.
2015     * {@hide}
2016     */
2017    protected OnClickListener mOnClickListener;
2018
2019    /**
2020     * Listener used to dispatch long click events.
2021     * This field should be made private, so it is hidden from the SDK.
2022     * {@hide}
2023     */
2024    protected OnLongClickListener mOnLongClickListener;
2025
2026    /**
2027     * Listener used to build the context menu.
2028     * This field should be made private, so it is hidden from the SDK.
2029     * {@hide}
2030     */
2031    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2032
2033    private OnKeyListener mOnKeyListener;
2034
2035    private OnTouchListener mOnTouchListener;
2036
2037    private OnDragListener mOnDragListener;
2038
2039    /**
2040     * The application environment this view lives in.
2041     * This field should be made private, so it is hidden from the SDK.
2042     * {@hide}
2043     */
2044    protected Context mContext;
2045
2046    private ScrollabilityCache mScrollCache;
2047
2048    private int[] mDrawableState = null;
2049
2050    private Bitmap mDrawingCache;
2051    private Bitmap mUnscaledDrawingCache;
2052    private DisplayList mDisplayList;
2053    private HardwareLayer mHardwareLayer;
2054
2055    /**
2056     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2057     * the user may specify which view to go to next.
2058     */
2059    private int mNextFocusLeftId = View.NO_ID;
2060
2061    /**
2062     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2063     * the user may specify which view to go to next.
2064     */
2065    private int mNextFocusRightId = View.NO_ID;
2066
2067    /**
2068     * When this view has focus and the next focus is {@link #FOCUS_UP},
2069     * the user may specify which view to go to next.
2070     */
2071    private int mNextFocusUpId = View.NO_ID;
2072
2073    /**
2074     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2075     * the user may specify which view to go to next.
2076     */
2077    private int mNextFocusDownId = View.NO_ID;
2078
2079    /**
2080     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2081     * the user may specify which view to go to next.
2082     */
2083    int mNextFocusForwardId = View.NO_ID;
2084
2085    private CheckForLongPress mPendingCheckForLongPress;
2086    private CheckForTap mPendingCheckForTap = null;
2087    private PerformClick mPerformClick;
2088
2089    private UnsetPressedState mUnsetPressedState;
2090
2091    /**
2092     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2093     * up event while a long press is invoked as soon as the long press duration is reached, so
2094     * a long press could be performed before the tap is checked, in which case the tap's action
2095     * should not be invoked.
2096     */
2097    private boolean mHasPerformedLongPress;
2098
2099    /**
2100     * The minimum height of the view. We'll try our best to have the height
2101     * of this view to at least this amount.
2102     */
2103    @ViewDebug.ExportedProperty(category = "measurement")
2104    private int mMinHeight;
2105
2106    /**
2107     * The minimum width of the view. We'll try our best to have the width
2108     * of this view to at least this amount.
2109     */
2110    @ViewDebug.ExportedProperty(category = "measurement")
2111    private int mMinWidth;
2112
2113    /**
2114     * The delegate to handle touch events that are physically in this view
2115     * but should be handled by another view.
2116     */
2117    private TouchDelegate mTouchDelegate = null;
2118
2119    /**
2120     * Solid color to use as a background when creating the drawing cache. Enables
2121     * the cache to use 16 bit bitmaps instead of 32 bit.
2122     */
2123    private int mDrawingCacheBackgroundColor = 0;
2124
2125    /**
2126     * Special tree observer used when mAttachInfo is null.
2127     */
2128    private ViewTreeObserver mFloatingTreeObserver;
2129
2130    /**
2131     * Cache the touch slop from the context that created the view.
2132     */
2133    private int mTouchSlop;
2134
2135    /**
2136     * Cache drag/drop state
2137     *
2138     */
2139    boolean mCanAcceptDrop;
2140
2141    /**
2142     * Flag indicating that a drag can cross window boundaries
2143     * @hide
2144     */
2145    public static final int DRAG_FLAG_GLOBAL = 1;
2146
2147    /**
2148     * Position of the vertical scroll bar.
2149     */
2150    private int mVerticalScrollbarPosition;
2151
2152    /**
2153     * Position the scroll bar at the default position as determined by the system.
2154     */
2155    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2156
2157    /**
2158     * Position the scroll bar along the left edge.
2159     */
2160    public static final int SCROLLBAR_POSITION_LEFT = 1;
2161
2162    /**
2163     * Position the scroll bar along the right edge.
2164     */
2165    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2166
2167    /**
2168     * Indicates that the view does not have a layer.
2169     *
2170     * @see #getLayerType()
2171     * @see #setLayerType(int, android.graphics.Paint)
2172     * @see #LAYER_TYPE_SOFTWARE
2173     * @see #LAYER_TYPE_HARDWARE
2174     */
2175    public static final int LAYER_TYPE_NONE = 0;
2176
2177    /**
2178     * <p>Indicates that the view has a software layer. A software layer is backed
2179     * by a bitmap and causes the view to be rendered using Android's software
2180     * rendering pipeline, even if hardware acceleration is enabled.</p>
2181     *
2182     * <p>Software layers have various usages:</p>
2183     * <p>When the application is not using hardware acceleration, a software layer
2184     * is useful to apply a specific color filter and/or blending mode and/or
2185     * translucency to a view and all its children.</p>
2186     * <p>When the application is using hardware acceleration, a software layer
2187     * is useful to render drawing primitives not supported by the hardware
2188     * accelerated pipeline. It can also be used to cache a complex view tree
2189     * into a texture and reduce the complexity of drawing operations. For instance,
2190     * when animating a complex view tree with a translation, a software layer can
2191     * be used to render the view tree only once.</p>
2192     * <p>Software layers should be avoided when the affected view tree updates
2193     * often. Every update will require to re-render the software layer, which can
2194     * potentially be slow (particularly when hardware acceleration is turned on
2195     * since the layer will have to be uploaded into a hardware texture after every
2196     * update.)</p>
2197     *
2198     * @see #getLayerType()
2199     * @see #setLayerType(int, android.graphics.Paint)
2200     * @see #LAYER_TYPE_NONE
2201     * @see #LAYER_TYPE_HARDWARE
2202     */
2203    public static final int LAYER_TYPE_SOFTWARE = 1;
2204
2205    /**
2206     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2207     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2208     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2209     * rendering pipeline, but only if hardware acceleration is turned on for the
2210     * view hierarchy. When hardware acceleration is turned off, hardware layers
2211     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2212     *
2213     * <p>A hardware layer is useful to apply a specific color filter and/or
2214     * blending mode and/or translucency to a view and all its children.</p>
2215     * <p>A hardware layer can be used to cache a complex view tree into a
2216     * texture and reduce the complexity of drawing operations. For instance,
2217     * when animating a complex view tree with a translation, a hardware layer can
2218     * be used to render the view tree only once.</p>
2219     * <p>A hardware layer can also be used to increase the rendering quality when
2220     * rotation transformations are applied on a view. It can also be used to
2221     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2222     *
2223     * @see #getLayerType()
2224     * @see #setLayerType(int, android.graphics.Paint)
2225     * @see #LAYER_TYPE_NONE
2226     * @see #LAYER_TYPE_SOFTWARE
2227     */
2228    public static final int LAYER_TYPE_HARDWARE = 2;
2229
2230    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2231            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2232            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2233            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2234    })
2235    int mLayerType = LAYER_TYPE_NONE;
2236    Paint mLayerPaint;
2237
2238    /**
2239     * Simple constructor to use when creating a view from code.
2240     *
2241     * @param context The Context the view is running in, through which it can
2242     *        access the current theme, resources, etc.
2243     */
2244    public View(Context context) {
2245        mContext = context;
2246        mResources = context != null ? context.getResources() : null;
2247        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
2248        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2249        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2250    }
2251
2252    /**
2253     * Constructor that is called when inflating a view from XML. This is called
2254     * when a view is being constructed from an XML file, supplying attributes
2255     * that were specified in the XML file. This version uses a default style of
2256     * 0, so the only attribute values applied are those in the Context's Theme
2257     * and the given AttributeSet.
2258     *
2259     * <p>
2260     * The method onFinishInflate() will be called after all children have been
2261     * added.
2262     *
2263     * @param context The Context the view is running in, through which it can
2264     *        access the current theme, resources, etc.
2265     * @param attrs The attributes of the XML tag that is inflating the view.
2266     * @see #View(Context, AttributeSet, int)
2267     */
2268    public View(Context context, AttributeSet attrs) {
2269        this(context, attrs, 0);
2270    }
2271
2272    /**
2273     * Perform inflation from XML and apply a class-specific base style. This
2274     * constructor of View allows subclasses to use their own base style when
2275     * they are inflating. For example, a Button class's constructor would call
2276     * this version of the super class constructor and supply
2277     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2278     * the theme's button style to modify all of the base view attributes (in
2279     * particular its background) as well as the Button class's attributes.
2280     *
2281     * @param context The Context the view is running in, through which it can
2282     *        access the current theme, resources, etc.
2283     * @param attrs The attributes of the XML tag that is inflating the view.
2284     * @param defStyle The default style to apply to this view. If 0, no style
2285     *        will be applied (beyond what is included in the theme). This may
2286     *        either be an attribute resource, whose value will be retrieved
2287     *        from the current theme, or an explicit style resource.
2288     * @see #View(Context, AttributeSet)
2289     */
2290    public View(Context context, AttributeSet attrs, int defStyle) {
2291        this(context);
2292
2293        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2294                defStyle, 0);
2295
2296        Drawable background = null;
2297
2298        int leftPadding = -1;
2299        int topPadding = -1;
2300        int rightPadding = -1;
2301        int bottomPadding = -1;
2302
2303        int padding = -1;
2304
2305        int viewFlagValues = 0;
2306        int viewFlagMasks = 0;
2307
2308        boolean setScrollContainer = false;
2309
2310        int x = 0;
2311        int y = 0;
2312
2313        float tx = 0;
2314        float ty = 0;
2315        float rotation = 0;
2316        float rotationX = 0;
2317        float rotationY = 0;
2318        float sx = 1f;
2319        float sy = 1f;
2320        boolean transformSet = false;
2321
2322        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2323
2324        int overScrollMode = mOverScrollMode;
2325        final int N = a.getIndexCount();
2326        for (int i = 0; i < N; i++) {
2327            int attr = a.getIndex(i);
2328            switch (attr) {
2329                case com.android.internal.R.styleable.View_background:
2330                    background = a.getDrawable(attr);
2331                    break;
2332                case com.android.internal.R.styleable.View_padding:
2333                    padding = a.getDimensionPixelSize(attr, -1);
2334                    break;
2335                 case com.android.internal.R.styleable.View_paddingLeft:
2336                    leftPadding = a.getDimensionPixelSize(attr, -1);
2337                    break;
2338                case com.android.internal.R.styleable.View_paddingTop:
2339                    topPadding = a.getDimensionPixelSize(attr, -1);
2340                    break;
2341                case com.android.internal.R.styleable.View_paddingRight:
2342                    rightPadding = a.getDimensionPixelSize(attr, -1);
2343                    break;
2344                case com.android.internal.R.styleable.View_paddingBottom:
2345                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2346                    break;
2347                case com.android.internal.R.styleable.View_scrollX:
2348                    x = a.getDimensionPixelOffset(attr, 0);
2349                    break;
2350                case com.android.internal.R.styleable.View_scrollY:
2351                    y = a.getDimensionPixelOffset(attr, 0);
2352                    break;
2353                case com.android.internal.R.styleable.View_alpha:
2354                    setAlpha(a.getFloat(attr, 1f));
2355                    break;
2356                case com.android.internal.R.styleable.View_transformPivotX:
2357                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2358                    break;
2359                case com.android.internal.R.styleable.View_transformPivotY:
2360                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2361                    break;
2362                case com.android.internal.R.styleable.View_translationX:
2363                    tx = a.getDimensionPixelOffset(attr, 0);
2364                    transformSet = true;
2365                    break;
2366                case com.android.internal.R.styleable.View_translationY:
2367                    ty = a.getDimensionPixelOffset(attr, 0);
2368                    transformSet = true;
2369                    break;
2370                case com.android.internal.R.styleable.View_rotation:
2371                    rotation = a.getFloat(attr, 0);
2372                    transformSet = true;
2373                    break;
2374                case com.android.internal.R.styleable.View_rotationX:
2375                    rotationX = a.getFloat(attr, 0);
2376                    transformSet = true;
2377                    break;
2378                case com.android.internal.R.styleable.View_rotationY:
2379                    rotationY = a.getFloat(attr, 0);
2380                    transformSet = true;
2381                    break;
2382                case com.android.internal.R.styleable.View_scaleX:
2383                    sx = a.getFloat(attr, 1f);
2384                    transformSet = true;
2385                    break;
2386                case com.android.internal.R.styleable.View_scaleY:
2387                    sy = a.getFloat(attr, 1f);
2388                    transformSet = true;
2389                    break;
2390                case com.android.internal.R.styleable.View_id:
2391                    mID = a.getResourceId(attr, NO_ID);
2392                    break;
2393                case com.android.internal.R.styleable.View_tag:
2394                    mTag = a.getText(attr);
2395                    break;
2396                case com.android.internal.R.styleable.View_fitsSystemWindows:
2397                    if (a.getBoolean(attr, false)) {
2398                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2399                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2400                    }
2401                    break;
2402                case com.android.internal.R.styleable.View_focusable:
2403                    if (a.getBoolean(attr, false)) {
2404                        viewFlagValues |= FOCUSABLE;
2405                        viewFlagMasks |= FOCUSABLE_MASK;
2406                    }
2407                    break;
2408                case com.android.internal.R.styleable.View_focusableInTouchMode:
2409                    if (a.getBoolean(attr, false)) {
2410                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2411                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2412                    }
2413                    break;
2414                case com.android.internal.R.styleable.View_clickable:
2415                    if (a.getBoolean(attr, false)) {
2416                        viewFlagValues |= CLICKABLE;
2417                        viewFlagMasks |= CLICKABLE;
2418                    }
2419                    break;
2420                case com.android.internal.R.styleable.View_longClickable:
2421                    if (a.getBoolean(attr, false)) {
2422                        viewFlagValues |= LONG_CLICKABLE;
2423                        viewFlagMasks |= LONG_CLICKABLE;
2424                    }
2425                    break;
2426                case com.android.internal.R.styleable.View_saveEnabled:
2427                    if (!a.getBoolean(attr, true)) {
2428                        viewFlagValues |= SAVE_DISABLED;
2429                        viewFlagMasks |= SAVE_DISABLED_MASK;
2430                    }
2431                    break;
2432                case com.android.internal.R.styleable.View_duplicateParentState:
2433                    if (a.getBoolean(attr, false)) {
2434                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2435                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2436                    }
2437                    break;
2438                case com.android.internal.R.styleable.View_visibility:
2439                    final int visibility = a.getInt(attr, 0);
2440                    if (visibility != 0) {
2441                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2442                        viewFlagMasks |= VISIBILITY_MASK;
2443                    }
2444                    break;
2445                case com.android.internal.R.styleable.View_drawingCacheQuality:
2446                    final int cacheQuality = a.getInt(attr, 0);
2447                    if (cacheQuality != 0) {
2448                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2449                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2450                    }
2451                    break;
2452                case com.android.internal.R.styleable.View_contentDescription:
2453                    mContentDescription = a.getString(attr);
2454                    break;
2455                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2456                    if (!a.getBoolean(attr, true)) {
2457                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2458                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2459                    }
2460                    break;
2461                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2462                    if (!a.getBoolean(attr, true)) {
2463                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2464                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2465                    }
2466                    break;
2467                case R.styleable.View_scrollbars:
2468                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2469                    if (scrollbars != SCROLLBARS_NONE) {
2470                        viewFlagValues |= scrollbars;
2471                        viewFlagMasks |= SCROLLBARS_MASK;
2472                        initializeScrollbars(a);
2473                    }
2474                    break;
2475                case R.styleable.View_fadingEdge:
2476                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2477                    if (fadingEdge != FADING_EDGE_NONE) {
2478                        viewFlagValues |= fadingEdge;
2479                        viewFlagMasks |= FADING_EDGE_MASK;
2480                        initializeFadingEdge(a);
2481                    }
2482                    break;
2483                case R.styleable.View_scrollbarStyle:
2484                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2485                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2486                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2487                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2488                    }
2489                    break;
2490                case R.styleable.View_isScrollContainer:
2491                    setScrollContainer = true;
2492                    if (a.getBoolean(attr, false)) {
2493                        setScrollContainer(true);
2494                    }
2495                    break;
2496                case com.android.internal.R.styleable.View_keepScreenOn:
2497                    if (a.getBoolean(attr, false)) {
2498                        viewFlagValues |= KEEP_SCREEN_ON;
2499                        viewFlagMasks |= KEEP_SCREEN_ON;
2500                    }
2501                    break;
2502                case R.styleable.View_filterTouchesWhenObscured:
2503                    if (a.getBoolean(attr, false)) {
2504                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2505                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2506                    }
2507                    break;
2508                case R.styleable.View_nextFocusLeft:
2509                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2510                    break;
2511                case R.styleable.View_nextFocusRight:
2512                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2513                    break;
2514                case R.styleable.View_nextFocusUp:
2515                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2516                    break;
2517                case R.styleable.View_nextFocusDown:
2518                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2519                    break;
2520                case R.styleable.View_nextFocusForward:
2521                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2522                    break;
2523                case R.styleable.View_minWidth:
2524                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2525                    break;
2526                case R.styleable.View_minHeight:
2527                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2528                    break;
2529                case R.styleable.View_onClick:
2530                    if (context.isRestricted()) {
2531                        throw new IllegalStateException("The android:onClick attribute cannot "
2532                                + "be used within a restricted context");
2533                    }
2534
2535                    final String handlerName = a.getString(attr);
2536                    if (handlerName != null) {
2537                        setOnClickListener(new OnClickListener() {
2538                            private Method mHandler;
2539
2540                            public void onClick(View v) {
2541                                if (mHandler == null) {
2542                                    try {
2543                                        mHandler = getContext().getClass().getMethod(handlerName,
2544                                                View.class);
2545                                    } catch (NoSuchMethodException e) {
2546                                        int id = getId();
2547                                        String idText = id == NO_ID ? "" : " with id '"
2548                                                + getContext().getResources().getResourceEntryName(
2549                                                    id) + "'";
2550                                        throw new IllegalStateException("Could not find a method " +
2551                                                handlerName + "(View) in the activity "
2552                                                + getContext().getClass() + " for onClick handler"
2553                                                + " on view " + View.this.getClass() + idText, e);
2554                                    }
2555                                }
2556
2557                                try {
2558                                    mHandler.invoke(getContext(), View.this);
2559                                } catch (IllegalAccessException e) {
2560                                    throw new IllegalStateException("Could not execute non "
2561                                            + "public method of the activity", e);
2562                                } catch (InvocationTargetException e) {
2563                                    throw new IllegalStateException("Could not execute "
2564                                            + "method of the activity", e);
2565                                }
2566                            }
2567                        });
2568                    }
2569                    break;
2570                case R.styleable.View_overScrollMode:
2571                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2572                    break;
2573                case R.styleable.View_verticalScrollbarPosition:
2574                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2575                    break;
2576                case R.styleable.View_layerType:
2577                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2578                    break;
2579            }
2580        }
2581
2582        setOverScrollMode(overScrollMode);
2583
2584        if (background != null) {
2585            setBackgroundDrawable(background);
2586        }
2587
2588        if (padding >= 0) {
2589            leftPadding = padding;
2590            topPadding = padding;
2591            rightPadding = padding;
2592            bottomPadding = padding;
2593        }
2594
2595        // If the user specified the padding (either with android:padding or
2596        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2597        // use the default padding or the padding from the background drawable
2598        // (stored at this point in mPadding*)
2599        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2600                topPadding >= 0 ? topPadding : mPaddingTop,
2601                rightPadding >= 0 ? rightPadding : mPaddingRight,
2602                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2603
2604        if (viewFlagMasks != 0) {
2605            setFlags(viewFlagValues, viewFlagMasks);
2606        }
2607
2608        // Needs to be called after mViewFlags is set
2609        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2610            recomputePadding();
2611        }
2612
2613        if (x != 0 || y != 0) {
2614            scrollTo(x, y);
2615        }
2616
2617        if (transformSet) {
2618            setTranslationX(tx);
2619            setTranslationY(ty);
2620            setRotation(rotation);
2621            setRotationX(rotationX);
2622            setRotationY(rotationY);
2623            setScaleX(sx);
2624            setScaleY(sy);
2625        }
2626
2627        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2628            setScrollContainer(true);
2629        }
2630
2631        computeOpaqueFlags();
2632
2633        a.recycle();
2634    }
2635
2636    /**
2637     * Non-public constructor for use in testing
2638     */
2639    View() {
2640    }
2641
2642    /**
2643     * <p>
2644     * Initializes the fading edges from a given set of styled attributes. This
2645     * method should be called by subclasses that need fading edges and when an
2646     * instance of these subclasses is created programmatically rather than
2647     * being inflated from XML. This method is automatically called when the XML
2648     * is inflated.
2649     * </p>
2650     *
2651     * @param a the styled attributes set to initialize the fading edges from
2652     */
2653    protected void initializeFadingEdge(TypedArray a) {
2654        initScrollCache();
2655
2656        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2657                R.styleable.View_fadingEdgeLength,
2658                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2659    }
2660
2661    /**
2662     * Returns the size of the vertical faded edges used to indicate that more
2663     * content in this view is visible.
2664     *
2665     * @return The size in pixels of the vertical faded edge or 0 if vertical
2666     *         faded edges are not enabled for this view.
2667     * @attr ref android.R.styleable#View_fadingEdgeLength
2668     */
2669    public int getVerticalFadingEdgeLength() {
2670        if (isVerticalFadingEdgeEnabled()) {
2671            ScrollabilityCache cache = mScrollCache;
2672            if (cache != null) {
2673                return cache.fadingEdgeLength;
2674            }
2675        }
2676        return 0;
2677    }
2678
2679    /**
2680     * Set the size of the faded edge used to indicate that more content in this
2681     * view is available.  Will not change whether the fading edge is enabled; use
2682     * {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
2683     * to enable the fading edge for the vertical or horizontal fading edges.
2684     *
2685     * @param length The size in pixels of the faded edge used to indicate that more
2686     *        content in this view is visible.
2687     */
2688    public void setFadingEdgeLength(int length) {
2689        initScrollCache();
2690        mScrollCache.fadingEdgeLength = length;
2691    }
2692
2693    /**
2694     * Returns the size of the horizontal faded edges used to indicate that more
2695     * content in this view is visible.
2696     *
2697     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2698     *         faded edges are not enabled for this view.
2699     * @attr ref android.R.styleable#View_fadingEdgeLength
2700     */
2701    public int getHorizontalFadingEdgeLength() {
2702        if (isHorizontalFadingEdgeEnabled()) {
2703            ScrollabilityCache cache = mScrollCache;
2704            if (cache != null) {
2705                return cache.fadingEdgeLength;
2706            }
2707        }
2708        return 0;
2709    }
2710
2711    /**
2712     * Returns the width of the vertical scrollbar.
2713     *
2714     * @return The width in pixels of the vertical scrollbar or 0 if there
2715     *         is no vertical scrollbar.
2716     */
2717    public int getVerticalScrollbarWidth() {
2718        ScrollabilityCache cache = mScrollCache;
2719        if (cache != null) {
2720            ScrollBarDrawable scrollBar = cache.scrollBar;
2721            if (scrollBar != null) {
2722                int size = scrollBar.getSize(true);
2723                if (size <= 0) {
2724                    size = cache.scrollBarSize;
2725                }
2726                return size;
2727            }
2728            return 0;
2729        }
2730        return 0;
2731    }
2732
2733    /**
2734     * Returns the height of the horizontal scrollbar.
2735     *
2736     * @return The height in pixels of the horizontal scrollbar or 0 if
2737     *         there is no horizontal scrollbar.
2738     */
2739    protected int getHorizontalScrollbarHeight() {
2740        ScrollabilityCache cache = mScrollCache;
2741        if (cache != null) {
2742            ScrollBarDrawable scrollBar = cache.scrollBar;
2743            if (scrollBar != null) {
2744                int size = scrollBar.getSize(false);
2745                if (size <= 0) {
2746                    size = cache.scrollBarSize;
2747                }
2748                return size;
2749            }
2750            return 0;
2751        }
2752        return 0;
2753    }
2754
2755    /**
2756     * <p>
2757     * Initializes the scrollbars from a given set of styled attributes. This
2758     * method should be called by subclasses that need scrollbars and when an
2759     * instance of these subclasses is created programmatically rather than
2760     * being inflated from XML. This method is automatically called when the XML
2761     * is inflated.
2762     * </p>
2763     *
2764     * @param a the styled attributes set to initialize the scrollbars from
2765     */
2766    protected void initializeScrollbars(TypedArray a) {
2767        initScrollCache();
2768
2769        final ScrollabilityCache scrollabilityCache = mScrollCache;
2770
2771        if (scrollabilityCache.scrollBar == null) {
2772            scrollabilityCache.scrollBar = new ScrollBarDrawable();
2773        }
2774
2775        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
2776
2777        if (!fadeScrollbars) {
2778            scrollabilityCache.state = ScrollabilityCache.ON;
2779        }
2780        scrollabilityCache.fadeScrollBars = fadeScrollbars;
2781
2782
2783        scrollabilityCache.scrollBarFadeDuration = a.getInt(
2784                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
2785                        .getScrollBarFadeDuration());
2786        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
2787                R.styleable.View_scrollbarDefaultDelayBeforeFade,
2788                ViewConfiguration.getScrollDefaultDelay());
2789
2790
2791        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
2792                com.android.internal.R.styleable.View_scrollbarSize,
2793                ViewConfiguration.get(mContext).getScaledScrollBarSize());
2794
2795        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
2796        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
2797
2798        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
2799        if (thumb != null) {
2800            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
2801        }
2802
2803        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
2804                false);
2805        if (alwaysDraw) {
2806            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
2807        }
2808
2809        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
2810        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
2811
2812        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
2813        if (thumb != null) {
2814            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
2815        }
2816
2817        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
2818                false);
2819        if (alwaysDraw) {
2820            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
2821        }
2822
2823        // Re-apply user/background padding so that scrollbar(s) get added
2824        recomputePadding();
2825    }
2826
2827    /**
2828     * <p>
2829     * Initalizes the scrollability cache if necessary.
2830     * </p>
2831     */
2832    private void initScrollCache() {
2833        if (mScrollCache == null) {
2834            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
2835        }
2836    }
2837
2838    /**
2839     * Set the position of the vertical scroll bar. Should be one of
2840     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
2841     * {@link #SCROLLBAR_POSITION_RIGHT}.
2842     *
2843     * @param position Where the vertical scroll bar should be positioned.
2844     */
2845    public void setVerticalScrollbarPosition(int position) {
2846        if (mVerticalScrollbarPosition != position) {
2847            mVerticalScrollbarPosition = position;
2848            computeOpaqueFlags();
2849            recomputePadding();
2850        }
2851    }
2852
2853    /**
2854     * @return The position where the vertical scroll bar will show, if applicable.
2855     * @see #setVerticalScrollbarPosition(int)
2856     */
2857    public int getVerticalScrollbarPosition() {
2858        return mVerticalScrollbarPosition;
2859    }
2860
2861    /**
2862     * Register a callback to be invoked when focus of this view changed.
2863     *
2864     * @param l The callback that will run.
2865     */
2866    public void setOnFocusChangeListener(OnFocusChangeListener l) {
2867        mOnFocusChangeListener = l;
2868    }
2869
2870    /**
2871     * Add a listener that will be called when the bounds of the view change due to
2872     * layout processing.
2873     *
2874     * @param listener The listener that will be called when layout bounds change.
2875     */
2876    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
2877        if (mOnLayoutChangeListeners == null) {
2878            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
2879        }
2880        mOnLayoutChangeListeners.add(listener);
2881    }
2882
2883    /**
2884     * Remove a listener for layout changes.
2885     *
2886     * @param listener The listener for layout bounds change.
2887     */
2888    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
2889        if (mOnLayoutChangeListeners == null) {
2890            return;
2891        }
2892        mOnLayoutChangeListeners.remove(listener);
2893    }
2894
2895    /**
2896     * Gets the current list of listeners for layout changes.
2897     */
2898    public List<OnLayoutChangeListener> getOnLayoutChangeListeners() {
2899        return mOnLayoutChangeListeners;
2900    }
2901
2902    /**
2903     * Returns the focus-change callback registered for this view.
2904     *
2905     * @return The callback, or null if one is not registered.
2906     */
2907    public OnFocusChangeListener getOnFocusChangeListener() {
2908        return mOnFocusChangeListener;
2909    }
2910
2911    /**
2912     * Register a callback to be invoked when this view is clicked. If this view is not
2913     * clickable, it becomes clickable.
2914     *
2915     * @param l The callback that will run
2916     *
2917     * @see #setClickable(boolean)
2918     */
2919    public void setOnClickListener(OnClickListener l) {
2920        if (!isClickable()) {
2921            setClickable(true);
2922        }
2923        mOnClickListener = l;
2924    }
2925
2926    /**
2927     * Register a callback to be invoked when this view is clicked and held. If this view is not
2928     * long clickable, it becomes long clickable.
2929     *
2930     * @param l The callback that will run
2931     *
2932     * @see #setLongClickable(boolean)
2933     */
2934    public void setOnLongClickListener(OnLongClickListener l) {
2935        if (!isLongClickable()) {
2936            setLongClickable(true);
2937        }
2938        mOnLongClickListener = l;
2939    }
2940
2941    /**
2942     * Register a callback to be invoked when the context menu for this view is
2943     * being built. If this view is not long clickable, it becomes long clickable.
2944     *
2945     * @param l The callback that will run
2946     *
2947     */
2948    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
2949        if (!isLongClickable()) {
2950            setLongClickable(true);
2951        }
2952        mOnCreateContextMenuListener = l;
2953    }
2954
2955    /**
2956     * Call this view's OnClickListener, if it is defined.
2957     *
2958     * @return True there was an assigned OnClickListener that was called, false
2959     *         otherwise is returned.
2960     */
2961    public boolean performClick() {
2962        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
2963
2964        if (mOnClickListener != null) {
2965            playSoundEffect(SoundEffectConstants.CLICK);
2966            mOnClickListener.onClick(this);
2967            return true;
2968        }
2969
2970        return false;
2971    }
2972
2973    /**
2974     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
2975     * OnLongClickListener did not consume the event.
2976     *
2977     * @return True if one of the above receivers consumed the event, false otherwise.
2978     */
2979    public boolean performLongClick() {
2980        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
2981
2982        boolean handled = false;
2983        if (mOnLongClickListener != null) {
2984            handled = mOnLongClickListener.onLongClick(View.this);
2985        }
2986        if (!handled) {
2987            handled = showContextMenu();
2988        }
2989        if (handled) {
2990            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
2991        }
2992        return handled;
2993    }
2994
2995    /**
2996     * Bring up the context menu for this view.
2997     *
2998     * @return Whether a context menu was displayed.
2999     */
3000    public boolean showContextMenu() {
3001        return getParent().showContextMenuForChild(this);
3002    }
3003
3004    /**
3005     * Start an action mode.
3006     *
3007     * @param callback Callback that will control the lifecycle of the action mode
3008     * @return The new action mode if it is started, null otherwise
3009     *
3010     * @see ActionMode
3011     */
3012    public ActionMode startActionMode(ActionMode.Callback callback) {
3013        return getParent().startActionModeForChild(this, callback);
3014    }
3015
3016    /**
3017     * Register a callback to be invoked when a key is pressed in this view.
3018     * @param l the key listener to attach to this view
3019     */
3020    public void setOnKeyListener(OnKeyListener l) {
3021        mOnKeyListener = l;
3022    }
3023
3024    /**
3025     * Register a callback to be invoked when a touch event is sent to this view.
3026     * @param l the touch listener to attach to this view
3027     */
3028    public void setOnTouchListener(OnTouchListener l) {
3029        mOnTouchListener = l;
3030    }
3031
3032    /**
3033     * Register a callback to be invoked when a drag event is sent to this view.
3034     * @param l The drag listener to attach to this view
3035     */
3036    public void setOnDragListener(OnDragListener l) {
3037        mOnDragListener = l;
3038    }
3039
3040    /**
3041     * Give this view focus. This will cause {@link #onFocusChanged} to be called.
3042     *
3043     * Note: this does not check whether this {@link View} should get focus, it just
3044     * gives it focus no matter what.  It should only be called internally by framework
3045     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3046     *
3047     * @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
3048     *        View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
3049     *        focus moved when requestFocus() is called. It may not always
3050     *        apply, in which case use the default View.FOCUS_DOWN.
3051     * @param previouslyFocusedRect The rectangle of the view that had focus
3052     *        prior in this View's coordinate system.
3053     */
3054    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3055        if (DBG) {
3056            System.out.println(this + " requestFocus()");
3057        }
3058
3059        if ((mPrivateFlags & FOCUSED) == 0) {
3060            mPrivateFlags |= FOCUSED;
3061
3062            if (mParent != null) {
3063                mParent.requestChildFocus(this, this);
3064            }
3065
3066            onFocusChanged(true, direction, previouslyFocusedRect);
3067            refreshDrawableState();
3068        }
3069    }
3070
3071    /**
3072     * Request that a rectangle of this view be visible on the screen,
3073     * scrolling if necessary just enough.
3074     *
3075     * <p>A View should call this if it maintains some notion of which part
3076     * of its content is interesting.  For example, a text editing view
3077     * should call this when its cursor moves.
3078     *
3079     * @param rectangle The rectangle.
3080     * @return Whether any parent scrolled.
3081     */
3082    public boolean requestRectangleOnScreen(Rect rectangle) {
3083        return requestRectangleOnScreen(rectangle, false);
3084    }
3085
3086    /**
3087     * Request that a rectangle of this view be visible on the screen,
3088     * scrolling if necessary just enough.
3089     *
3090     * <p>A View should call this if it maintains some notion of which part
3091     * of its content is interesting.  For example, a text editing view
3092     * should call this when its cursor moves.
3093     *
3094     * <p>When <code>immediate</code> is set to true, scrolling will not be
3095     * animated.
3096     *
3097     * @param rectangle The rectangle.
3098     * @param immediate True to forbid animated scrolling, false otherwise
3099     * @return Whether any parent scrolled.
3100     */
3101    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3102        View child = this;
3103        ViewParent parent = mParent;
3104        boolean scrolled = false;
3105        while (parent != null) {
3106            scrolled |= parent.requestChildRectangleOnScreen(child,
3107                    rectangle, immediate);
3108
3109            // offset rect so next call has the rectangle in the
3110            // coordinate system of its direct child.
3111            rectangle.offset(child.getLeft(), child.getTop());
3112            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3113
3114            if (!(parent instanceof View)) {
3115                break;
3116            }
3117
3118            child = (View) parent;
3119            parent = child.getParent();
3120        }
3121        return scrolled;
3122    }
3123
3124    /**
3125     * Called when this view wants to give up focus. This will cause
3126     * {@link #onFocusChanged} to be called.
3127     */
3128    public void clearFocus() {
3129        if (DBG) {
3130            System.out.println(this + " clearFocus()");
3131        }
3132
3133        if ((mPrivateFlags & FOCUSED) != 0) {
3134            mPrivateFlags &= ~FOCUSED;
3135
3136            if (mParent != null) {
3137                mParent.clearChildFocus(this);
3138            }
3139
3140            onFocusChanged(false, 0, null);
3141            refreshDrawableState();
3142        }
3143    }
3144
3145    /**
3146     * Called to clear the focus of a view that is about to be removed.
3147     * Doesn't call clearChildFocus, which prevents this view from taking
3148     * focus again before it has been removed from the parent
3149     */
3150    void clearFocusForRemoval() {
3151        if ((mPrivateFlags & FOCUSED) != 0) {
3152            mPrivateFlags &= ~FOCUSED;
3153
3154            onFocusChanged(false, 0, null);
3155            refreshDrawableState();
3156        }
3157    }
3158
3159    /**
3160     * Called internally by the view system when a new view is getting focus.
3161     * This is what clears the old focus.
3162     */
3163    void unFocus() {
3164        if (DBG) {
3165            System.out.println(this + " unFocus()");
3166        }
3167
3168        if ((mPrivateFlags & FOCUSED) != 0) {
3169            mPrivateFlags &= ~FOCUSED;
3170
3171            onFocusChanged(false, 0, null);
3172            refreshDrawableState();
3173        }
3174    }
3175
3176    /**
3177     * Returns true if this view has focus iteself, or is the ancestor of the
3178     * view that has focus.
3179     *
3180     * @return True if this view has or contains focus, false otherwise.
3181     */
3182    @ViewDebug.ExportedProperty(category = "focus")
3183    public boolean hasFocus() {
3184        return (mPrivateFlags & FOCUSED) != 0;
3185    }
3186
3187    /**
3188     * Returns true if this view is focusable or if it contains a reachable View
3189     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3190     * is a View whose parents do not block descendants focus.
3191     *
3192     * Only {@link #VISIBLE} views are considered focusable.
3193     *
3194     * @return True if the view is focusable or if the view contains a focusable
3195     *         View, false otherwise.
3196     *
3197     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3198     */
3199    public boolean hasFocusable() {
3200        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3201    }
3202
3203    /**
3204     * Called by the view system when the focus state of this view changes.
3205     * When the focus change event is caused by directional navigation, direction
3206     * and previouslyFocusedRect provide insight into where the focus is coming from.
3207     * When overriding, be sure to call up through to the super class so that
3208     * the standard focus handling will occur.
3209     *
3210     * @param gainFocus True if the View has focus; false otherwise.
3211     * @param direction The direction focus has moved when requestFocus()
3212     *                  is called to give this view focus. Values are
3213     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3214     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3215     *                  It may not always apply, in which case use the default.
3216     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3217     *        system, of the previously focused view.  If applicable, this will be
3218     *        passed in as finer grained information about where the focus is coming
3219     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3220     */
3221    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3222        if (gainFocus) {
3223            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3224        }
3225
3226        InputMethodManager imm = InputMethodManager.peekInstance();
3227        if (!gainFocus) {
3228            if (isPressed()) {
3229                setPressed(false);
3230            }
3231            if (imm != null && mAttachInfo != null
3232                    && mAttachInfo.mHasWindowFocus) {
3233                imm.focusOut(this);
3234            }
3235            onFocusLost();
3236        } else if (imm != null && mAttachInfo != null
3237                && mAttachInfo.mHasWindowFocus) {
3238            imm.focusIn(this);
3239        }
3240
3241        invalidate();
3242        if (mOnFocusChangeListener != null) {
3243            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3244        }
3245
3246        if (mAttachInfo != null) {
3247            mAttachInfo.mKeyDispatchState.reset(this);
3248        }
3249    }
3250
3251    /**
3252     * {@inheritDoc}
3253     */
3254    public void sendAccessibilityEvent(int eventType) {
3255        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3256            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3257        }
3258    }
3259
3260    /**
3261     * {@inheritDoc}
3262     */
3263    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3264        if (!isShown()) {
3265            return;
3266        }
3267        event.setClassName(getClass().getName());
3268        event.setPackageName(getContext().getPackageName());
3269        event.setEnabled(isEnabled());
3270        event.setContentDescription(mContentDescription);
3271
3272        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3273            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3274            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3275            event.setItemCount(focusablesTempList.size());
3276            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3277            focusablesTempList.clear();
3278        }
3279
3280        dispatchPopulateAccessibilityEvent(event);
3281
3282        AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
3283    }
3284
3285    /**
3286     * Dispatches an {@link AccessibilityEvent} to the {@link View} children
3287     * to be populated.
3288     *
3289     * @param event The event.
3290     *
3291     * @return True if the event population was completed.
3292     */
3293    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3294        return false;
3295    }
3296
3297    /**
3298     * Gets the {@link View} description. It briefly describes the view and is
3299     * primarily used for accessibility support. Set this property to enable
3300     * better accessibility support for your application. This is especially
3301     * true for views that do not have textual representation (For example,
3302     * ImageButton).
3303     *
3304     * @return The content descriptiopn.
3305     *
3306     * @attr ref android.R.styleable#View_contentDescription
3307     */
3308    public CharSequence getContentDescription() {
3309        return mContentDescription;
3310    }
3311
3312    /**
3313     * Sets the {@link View} description. It briefly describes the view and is
3314     * primarily used for accessibility support. Set this property to enable
3315     * better accessibility support for your application. This is especially
3316     * true for views that do not have textual representation (For example,
3317     * ImageButton).
3318     *
3319     * @param contentDescription The content description.
3320     *
3321     * @attr ref android.R.styleable#View_contentDescription
3322     */
3323    public void setContentDescription(CharSequence contentDescription) {
3324        mContentDescription = contentDescription;
3325    }
3326
3327    /**
3328     * Invoked whenever this view loses focus, either by losing window focus or by losing
3329     * focus within its window. This method can be used to clear any state tied to the
3330     * focus. For instance, if a button is held pressed with the trackball and the window
3331     * loses focus, this method can be used to cancel the press.
3332     *
3333     * Subclasses of View overriding this method should always call super.onFocusLost().
3334     *
3335     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
3336     * @see #onWindowFocusChanged(boolean)
3337     *
3338     * @hide pending API council approval
3339     */
3340    protected void onFocusLost() {
3341        resetPressedState();
3342    }
3343
3344    private void resetPressedState() {
3345        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3346            return;
3347        }
3348
3349        if (isPressed()) {
3350            setPressed(false);
3351
3352            if (!mHasPerformedLongPress) {
3353                removeLongPressCallback();
3354            }
3355        }
3356    }
3357
3358    /**
3359     * Returns true if this view has focus
3360     *
3361     * @return True if this view has focus, false otherwise.
3362     */
3363    @ViewDebug.ExportedProperty(category = "focus")
3364    public boolean isFocused() {
3365        return (mPrivateFlags & FOCUSED) != 0;
3366    }
3367
3368    /**
3369     * Find the view in the hierarchy rooted at this view that currently has
3370     * focus.
3371     *
3372     * @return The view that currently has focus, or null if no focused view can
3373     *         be found.
3374     */
3375    public View findFocus() {
3376        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3377    }
3378
3379    /**
3380     * Change whether this view is one of the set of scrollable containers in
3381     * its window.  This will be used to determine whether the window can
3382     * resize or must pan when a soft input area is open -- scrollable
3383     * containers allow the window to use resize mode since the container
3384     * will appropriately shrink.
3385     */
3386    public void setScrollContainer(boolean isScrollContainer) {
3387        if (isScrollContainer) {
3388            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3389                mAttachInfo.mScrollContainers.add(this);
3390                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3391            }
3392            mPrivateFlags |= SCROLL_CONTAINER;
3393        } else {
3394            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3395                mAttachInfo.mScrollContainers.remove(this);
3396            }
3397            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3398        }
3399    }
3400
3401    /**
3402     * Returns the quality of the drawing cache.
3403     *
3404     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3405     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3406     *
3407     * @see #setDrawingCacheQuality(int)
3408     * @see #setDrawingCacheEnabled(boolean)
3409     * @see #isDrawingCacheEnabled()
3410     *
3411     * @attr ref android.R.styleable#View_drawingCacheQuality
3412     */
3413    public int getDrawingCacheQuality() {
3414        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3415    }
3416
3417    /**
3418     * Set the drawing cache quality of this view. This value is used only when the
3419     * drawing cache is enabled
3420     *
3421     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3422     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3423     *
3424     * @see #getDrawingCacheQuality()
3425     * @see #setDrawingCacheEnabled(boolean)
3426     * @see #isDrawingCacheEnabled()
3427     *
3428     * @attr ref android.R.styleable#View_drawingCacheQuality
3429     */
3430    public void setDrawingCacheQuality(int quality) {
3431        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3432    }
3433
3434    /**
3435     * Returns whether the screen should remain on, corresponding to the current
3436     * value of {@link #KEEP_SCREEN_ON}.
3437     *
3438     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3439     *
3440     * @see #setKeepScreenOn(boolean)
3441     *
3442     * @attr ref android.R.styleable#View_keepScreenOn
3443     */
3444    public boolean getKeepScreenOn() {
3445        return (mViewFlags & KEEP_SCREEN_ON) != 0;
3446    }
3447
3448    /**
3449     * Controls whether the screen should remain on, modifying the
3450     * value of {@link #KEEP_SCREEN_ON}.
3451     *
3452     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3453     *
3454     * @see #getKeepScreenOn()
3455     *
3456     * @attr ref android.R.styleable#View_keepScreenOn
3457     */
3458    public void setKeepScreenOn(boolean keepScreenOn) {
3459        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3460    }
3461
3462    /**
3463     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3464     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3465     *
3466     * @attr ref android.R.styleable#View_nextFocusLeft
3467     */
3468    public int getNextFocusLeftId() {
3469        return mNextFocusLeftId;
3470    }
3471
3472    /**
3473     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3474     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3475     * decide automatically.
3476     *
3477     * @attr ref android.R.styleable#View_nextFocusLeft
3478     */
3479    public void setNextFocusLeftId(int nextFocusLeftId) {
3480        mNextFocusLeftId = nextFocusLeftId;
3481    }
3482
3483    /**
3484     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3485     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3486     *
3487     * @attr ref android.R.styleable#View_nextFocusRight
3488     */
3489    public int getNextFocusRightId() {
3490        return mNextFocusRightId;
3491    }
3492
3493    /**
3494     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3495     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3496     * decide automatically.
3497     *
3498     * @attr ref android.R.styleable#View_nextFocusRight
3499     */
3500    public void setNextFocusRightId(int nextFocusRightId) {
3501        mNextFocusRightId = nextFocusRightId;
3502    }
3503
3504    /**
3505     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3506     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3507     *
3508     * @attr ref android.R.styleable#View_nextFocusUp
3509     */
3510    public int getNextFocusUpId() {
3511        return mNextFocusUpId;
3512    }
3513
3514    /**
3515     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3516     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
3517     * decide automatically.
3518     *
3519     * @attr ref android.R.styleable#View_nextFocusUp
3520     */
3521    public void setNextFocusUpId(int nextFocusUpId) {
3522        mNextFocusUpId = nextFocusUpId;
3523    }
3524
3525    /**
3526     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3527     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3528     *
3529     * @attr ref android.R.styleable#View_nextFocusDown
3530     */
3531    public int getNextFocusDownId() {
3532        return mNextFocusDownId;
3533    }
3534
3535    /**
3536     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
3537     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
3538     * decide automatically.
3539     *
3540     * @attr ref android.R.styleable#View_nextFocusDown
3541     */
3542    public void setNextFocusDownId(int nextFocusDownId) {
3543        mNextFocusDownId = nextFocusDownId;
3544    }
3545
3546    /**
3547     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3548     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3549     *
3550     * @attr ref android.R.styleable#View_nextFocusForward
3551     */
3552    public int getNextFocusForwardId() {
3553        return mNextFocusForwardId;
3554    }
3555
3556    /**
3557     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
3558     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
3559     * decide automatically.
3560     *
3561     * @attr ref android.R.styleable#View_nextFocusForward
3562     */
3563    public void setNextFocusForwardId(int nextFocusForwardId) {
3564        mNextFocusForwardId = nextFocusForwardId;
3565    }
3566
3567    /**
3568     * Returns the visibility of this view and all of its ancestors
3569     *
3570     * @return True if this view and all of its ancestors are {@link #VISIBLE}
3571     */
3572    public boolean isShown() {
3573        View current = this;
3574        //noinspection ConstantConditions
3575        do {
3576            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
3577                return false;
3578            }
3579            ViewParent parent = current.mParent;
3580            if (parent == null) {
3581                return false; // We are not attached to the view root
3582            }
3583            if (!(parent instanceof View)) {
3584                return true;
3585            }
3586            current = (View) parent;
3587        } while (current != null);
3588
3589        return false;
3590    }
3591
3592    /**
3593     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
3594     * is set
3595     *
3596     * @param insets Insets for system windows
3597     *
3598     * @return True if this view applied the insets, false otherwise
3599     */
3600    protected boolean fitSystemWindows(Rect insets) {
3601        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
3602            mPaddingLeft = insets.left;
3603            mPaddingTop = insets.top;
3604            mPaddingRight = insets.right;
3605            mPaddingBottom = insets.bottom;
3606            requestLayout();
3607            return true;
3608        }
3609        return false;
3610    }
3611
3612    /**
3613     * Determine if this view has the FITS_SYSTEM_WINDOWS flag set.
3614     * @return True if window has FITS_SYSTEM_WINDOWS set
3615     *
3616     * @hide
3617     */
3618    public boolean isFitsSystemWindowsFlagSet() {
3619        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
3620    }
3621
3622    /**
3623     * Returns the visibility status for this view.
3624     *
3625     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3626     * @attr ref android.R.styleable#View_visibility
3627     */
3628    @ViewDebug.ExportedProperty(mapping = {
3629        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
3630        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
3631        @ViewDebug.IntToString(from = GONE,      to = "GONE")
3632    })
3633    public int getVisibility() {
3634        return mViewFlags & VISIBILITY_MASK;
3635    }
3636
3637    /**
3638     * Set the enabled state of this view.
3639     *
3640     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
3641     * @attr ref android.R.styleable#View_visibility
3642     */
3643    @RemotableViewMethod
3644    public void setVisibility(int visibility) {
3645        setFlags(visibility, VISIBILITY_MASK);
3646        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
3647    }
3648
3649    /**
3650     * Returns the enabled status for this view. The interpretation of the
3651     * enabled state varies by subclass.
3652     *
3653     * @return True if this view is enabled, false otherwise.
3654     */
3655    @ViewDebug.ExportedProperty
3656    public boolean isEnabled() {
3657        return (mViewFlags & ENABLED_MASK) == ENABLED;
3658    }
3659
3660    /**
3661     * Set the enabled state of this view. The interpretation of the enabled
3662     * state varies by subclass.
3663     *
3664     * @param enabled True if this view is enabled, false otherwise.
3665     */
3666    @RemotableViewMethod
3667    public void setEnabled(boolean enabled) {
3668        if (enabled == isEnabled()) return;
3669
3670        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
3671
3672        /*
3673         * The View most likely has to change its appearance, so refresh
3674         * the drawable state.
3675         */
3676        refreshDrawableState();
3677
3678        // Invalidate too, since the default behavior for views is to be
3679        // be drawn at 50% alpha rather than to change the drawable.
3680        invalidate();
3681    }
3682
3683    /**
3684     * Set whether this view can receive the focus.
3685     *
3686     * Setting this to false will also ensure that this view is not focusable
3687     * in touch mode.
3688     *
3689     * @param focusable If true, this view can receive the focus.
3690     *
3691     * @see #setFocusableInTouchMode(boolean)
3692     * @attr ref android.R.styleable#View_focusable
3693     */
3694    public void setFocusable(boolean focusable) {
3695        if (!focusable) {
3696            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
3697        }
3698        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
3699    }
3700
3701    /**
3702     * Set whether this view can receive focus while in touch mode.
3703     *
3704     * Setting this to true will also ensure that this view is focusable.
3705     *
3706     * @param focusableInTouchMode If true, this view can receive the focus while
3707     *   in touch mode.
3708     *
3709     * @see #setFocusable(boolean)
3710     * @attr ref android.R.styleable#View_focusableInTouchMode
3711     */
3712    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
3713        // Focusable in touch mode should always be set before the focusable flag
3714        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
3715        // which, in touch mode, will not successfully request focus on this view
3716        // because the focusable in touch mode flag is not set
3717        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
3718        if (focusableInTouchMode) {
3719            setFlags(FOCUSABLE, FOCUSABLE_MASK);
3720        }
3721    }
3722
3723    /**
3724     * Set whether this view should have sound effects enabled for events such as
3725     * clicking and touching.
3726     *
3727     * <p>You may wish to disable sound effects for a view if you already play sounds,
3728     * for instance, a dial key that plays dtmf tones.
3729     *
3730     * @param soundEffectsEnabled whether sound effects are enabled for this view.
3731     * @see #isSoundEffectsEnabled()
3732     * @see #playSoundEffect(int)
3733     * @attr ref android.R.styleable#View_soundEffectsEnabled
3734     */
3735    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
3736        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
3737    }
3738
3739    /**
3740     * @return whether this view should have sound effects enabled for events such as
3741     *     clicking and touching.
3742     *
3743     * @see #setSoundEffectsEnabled(boolean)
3744     * @see #playSoundEffect(int)
3745     * @attr ref android.R.styleable#View_soundEffectsEnabled
3746     */
3747    @ViewDebug.ExportedProperty
3748    public boolean isSoundEffectsEnabled() {
3749        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
3750    }
3751
3752    /**
3753     * Set whether this view should have haptic feedback for events such as
3754     * long presses.
3755     *
3756     * <p>You may wish to disable haptic feedback if your view already controls
3757     * its own haptic feedback.
3758     *
3759     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
3760     * @see #isHapticFeedbackEnabled()
3761     * @see #performHapticFeedback(int)
3762     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3763     */
3764    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
3765        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
3766    }
3767
3768    /**
3769     * @return whether this view should have haptic feedback enabled for events
3770     * long presses.
3771     *
3772     * @see #setHapticFeedbackEnabled(boolean)
3773     * @see #performHapticFeedback(int)
3774     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
3775     */
3776    @ViewDebug.ExportedProperty
3777    public boolean isHapticFeedbackEnabled() {
3778        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
3779    }
3780
3781    /**
3782     * If this view doesn't do any drawing on its own, set this flag to
3783     * allow further optimizations. By default, this flag is not set on
3784     * View, but could be set on some View subclasses such as ViewGroup.
3785     *
3786     * Typically, if you override {@link #onDraw} you should clear this flag.
3787     *
3788     * @param willNotDraw whether or not this View draw on its own
3789     */
3790    public void setWillNotDraw(boolean willNotDraw) {
3791        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
3792    }
3793
3794    /**
3795     * Returns whether or not this View draws on its own.
3796     *
3797     * @return true if this view has nothing to draw, false otherwise
3798     */
3799    @ViewDebug.ExportedProperty(category = "drawing")
3800    public boolean willNotDraw() {
3801        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
3802    }
3803
3804    /**
3805     * When a View's drawing cache is enabled, drawing is redirected to an
3806     * offscreen bitmap. Some views, like an ImageView, must be able to
3807     * bypass this mechanism if they already draw a single bitmap, to avoid
3808     * unnecessary usage of the memory.
3809     *
3810     * @param willNotCacheDrawing true if this view does not cache its
3811     *        drawing, false otherwise
3812     */
3813    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
3814        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
3815    }
3816
3817    /**
3818     * Returns whether or not this View can cache its drawing or not.
3819     *
3820     * @return true if this view does not cache its drawing, false otherwise
3821     */
3822    @ViewDebug.ExportedProperty(category = "drawing")
3823    public boolean willNotCacheDrawing() {
3824        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
3825    }
3826
3827    /**
3828     * Indicates whether this view reacts to click events or not.
3829     *
3830     * @return true if the view is clickable, false otherwise
3831     *
3832     * @see #setClickable(boolean)
3833     * @attr ref android.R.styleable#View_clickable
3834     */
3835    @ViewDebug.ExportedProperty
3836    public boolean isClickable() {
3837        return (mViewFlags & CLICKABLE) == CLICKABLE;
3838    }
3839
3840    /**
3841     * Enables or disables click events for this view. When a view
3842     * is clickable it will change its state to "pressed" on every click.
3843     * Subclasses should set the view clickable to visually react to
3844     * user's clicks.
3845     *
3846     * @param clickable true to make the view clickable, false otherwise
3847     *
3848     * @see #isClickable()
3849     * @attr ref android.R.styleable#View_clickable
3850     */
3851    public void setClickable(boolean clickable) {
3852        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
3853    }
3854
3855    /**
3856     * Indicates whether this view reacts to long click events or not.
3857     *
3858     * @return true if the view is long clickable, false otherwise
3859     *
3860     * @see #setLongClickable(boolean)
3861     * @attr ref android.R.styleable#View_longClickable
3862     */
3863    public boolean isLongClickable() {
3864        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
3865    }
3866
3867    /**
3868     * Enables or disables long click events for this view. When a view is long
3869     * clickable it reacts to the user holding down the button for a longer
3870     * duration than a tap. This event can either launch the listener or a
3871     * context menu.
3872     *
3873     * @param longClickable true to make the view long clickable, false otherwise
3874     * @see #isLongClickable()
3875     * @attr ref android.R.styleable#View_longClickable
3876     */
3877    public void setLongClickable(boolean longClickable) {
3878        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
3879    }
3880
3881    /**
3882     * Sets the pressed state for this view.
3883     *
3884     * @see #isClickable()
3885     * @see #setClickable(boolean)
3886     *
3887     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
3888     *        the View's internal state from a previously set "pressed" state.
3889     */
3890    public void setPressed(boolean pressed) {
3891        if (pressed) {
3892            mPrivateFlags |= PRESSED;
3893        } else {
3894            mPrivateFlags &= ~PRESSED;
3895        }
3896        refreshDrawableState();
3897        dispatchSetPressed(pressed);
3898    }
3899
3900    /**
3901     * Dispatch setPressed to all of this View's children.
3902     *
3903     * @see #setPressed(boolean)
3904     *
3905     * @param pressed The new pressed state
3906     */
3907    protected void dispatchSetPressed(boolean pressed) {
3908    }
3909
3910    /**
3911     * Indicates whether the view is currently in pressed state. Unless
3912     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
3913     * the pressed state.
3914     *
3915     * @see #setPressed
3916     * @see #isClickable()
3917     * @see #setClickable(boolean)
3918     *
3919     * @return true if the view is currently pressed, false otherwise
3920     */
3921    public boolean isPressed() {
3922        return (mPrivateFlags & PRESSED) == PRESSED;
3923    }
3924
3925    /**
3926     * Indicates whether this view will save its state (that is,
3927     * whether its {@link #onSaveInstanceState} method will be called).
3928     *
3929     * @return Returns true if the view state saving is enabled, else false.
3930     *
3931     * @see #setSaveEnabled(boolean)
3932     * @attr ref android.R.styleable#View_saveEnabled
3933     */
3934    public boolean isSaveEnabled() {
3935        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
3936    }
3937
3938    /**
3939     * Controls whether the saving of this view's state is
3940     * enabled (that is, whether its {@link #onSaveInstanceState} method
3941     * will be called).  Note that even if freezing is enabled, the
3942     * view still must have an id assigned to it (via {@link #setId setId()})
3943     * for its state to be saved.  This flag can only disable the
3944     * saving of this view; any child views may still have their state saved.
3945     *
3946     * @param enabled Set to false to <em>disable</em> state saving, or true
3947     * (the default) to allow it.
3948     *
3949     * @see #isSaveEnabled()
3950     * @see #setId(int)
3951     * @see #onSaveInstanceState()
3952     * @attr ref android.R.styleable#View_saveEnabled
3953     */
3954    public void setSaveEnabled(boolean enabled) {
3955        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
3956    }
3957
3958    /**
3959     * Gets whether the framework should discard touches when the view's
3960     * window is obscured by another visible window.
3961     * Refer to the {@link View} security documentation for more details.
3962     *
3963     * @return True if touch filtering is enabled.
3964     *
3965     * @see #setFilterTouchesWhenObscured(boolean)
3966     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3967     */
3968    @ViewDebug.ExportedProperty
3969    public boolean getFilterTouchesWhenObscured() {
3970        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
3971    }
3972
3973    /**
3974     * Sets whether the framework should discard touches when the view's
3975     * window is obscured by another visible window.
3976     * Refer to the {@link View} security documentation for more details.
3977     *
3978     * @param enabled True if touch filtering should be enabled.
3979     *
3980     * @see #getFilterTouchesWhenObscured
3981     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
3982     */
3983    public void setFilterTouchesWhenObscured(boolean enabled) {
3984        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
3985                FILTER_TOUCHES_WHEN_OBSCURED);
3986    }
3987
3988    /**
3989     * Indicates whether the entire hierarchy under this view will save its
3990     * state when a state saving traversal occurs from its parent.  The default
3991     * is true; if false, these views will not be saved unless
3992     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
3993     *
3994     * @return Returns true if the view state saving from parent is enabled, else false.
3995     *
3996     * @see #setSaveFromParentEnabled(boolean)
3997     */
3998    public boolean isSaveFromParentEnabled() {
3999        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4000    }
4001
4002    /**
4003     * Controls whether the entire hierarchy under this view will save its
4004     * state when a state saving traversal occurs from its parent.  The default
4005     * is true; if false, these views will not be saved unless
4006     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4007     *
4008     * @param enabled Set to false to <em>disable</em> state saving, or true
4009     * (the default) to allow it.
4010     *
4011     * @see #isSaveFromParentEnabled()
4012     * @see #setId(int)
4013     * @see #onSaveInstanceState()
4014     */
4015    public void setSaveFromParentEnabled(boolean enabled) {
4016        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4017    }
4018
4019
4020    /**
4021     * Returns whether this View is able to take focus.
4022     *
4023     * @return True if this view can take focus, or false otherwise.
4024     * @attr ref android.R.styleable#View_focusable
4025     */
4026    @ViewDebug.ExportedProperty(category = "focus")
4027    public final boolean isFocusable() {
4028        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4029    }
4030
4031    /**
4032     * When a view is focusable, it may not want to take focus when in touch mode.
4033     * For example, a button would like focus when the user is navigating via a D-pad
4034     * so that the user can click on it, but once the user starts touching the screen,
4035     * the button shouldn't take focus
4036     * @return Whether the view is focusable in touch mode.
4037     * @attr ref android.R.styleable#View_focusableInTouchMode
4038     */
4039    @ViewDebug.ExportedProperty
4040    public final boolean isFocusableInTouchMode() {
4041        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4042    }
4043
4044    /**
4045     * Find the nearest view in the specified direction that can take focus.
4046     * This does not actually give focus to that view.
4047     *
4048     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4049     *
4050     * @return The nearest focusable in the specified direction, or null if none
4051     *         can be found.
4052     */
4053    public View focusSearch(int direction) {
4054        if (mParent != null) {
4055            return mParent.focusSearch(this, direction);
4056        } else {
4057            return null;
4058        }
4059    }
4060
4061    /**
4062     * This method is the last chance for the focused view and its ancestors to
4063     * respond to an arrow key. This is called when the focused view did not
4064     * consume the key internally, nor could the view system find a new view in
4065     * the requested direction to give focus to.
4066     *
4067     * @param focused The currently focused view.
4068     * @param direction The direction focus wants to move. One of FOCUS_UP,
4069     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4070     * @return True if the this view consumed this unhandled move.
4071     */
4072    public boolean dispatchUnhandledMove(View focused, int direction) {
4073        return false;
4074    }
4075
4076    /**
4077     * If a user manually specified the next view id for a particular direction,
4078     * use the root to look up the view.
4079     * @param root The root view of the hierarchy containing this view.
4080     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4081     * or FOCUS_BACKWARD.
4082     * @return The user specified next view, or null if there is none.
4083     */
4084    View findUserSetNextFocus(View root, int direction) {
4085        switch (direction) {
4086            case FOCUS_LEFT:
4087                if (mNextFocusLeftId == View.NO_ID) return null;
4088                return findViewShouldExist(root, mNextFocusLeftId);
4089            case FOCUS_RIGHT:
4090                if (mNextFocusRightId == View.NO_ID) return null;
4091                return findViewShouldExist(root, mNextFocusRightId);
4092            case FOCUS_UP:
4093                if (mNextFocusUpId == View.NO_ID) return null;
4094                return findViewShouldExist(root, mNextFocusUpId);
4095            case FOCUS_DOWN:
4096                if (mNextFocusDownId == View.NO_ID) return null;
4097                return findViewShouldExist(root, mNextFocusDownId);
4098            case FOCUS_FORWARD:
4099                if (mNextFocusForwardId == View.NO_ID) return null;
4100                return findViewShouldExist(root, mNextFocusForwardId);
4101            case FOCUS_BACKWARD: {
4102                final int id = mID;
4103                return root.findViewByPredicate(new Predicate<View>() {
4104                    @Override
4105                    public boolean apply(View t) {
4106                        return t.mNextFocusForwardId == id;
4107                    }
4108                });
4109            }
4110        }
4111        return null;
4112    }
4113
4114    private static View findViewShouldExist(View root, int childViewId) {
4115        View result = root.findViewById(childViewId);
4116        if (result == null) {
4117            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4118                    + "by user for id " + childViewId);
4119        }
4120        return result;
4121    }
4122
4123    /**
4124     * Find and return all focusable views that are descendants of this view,
4125     * possibly including this view if it is focusable itself.
4126     *
4127     * @param direction The direction of the focus
4128     * @return A list of focusable views
4129     */
4130    public ArrayList<View> getFocusables(int direction) {
4131        ArrayList<View> result = new ArrayList<View>(24);
4132        addFocusables(result, direction);
4133        return result;
4134    }
4135
4136    /**
4137     * Add any focusable views that are descendants of this view (possibly
4138     * including this view if it is focusable itself) to views.  If we are in touch mode,
4139     * only add views that are also focusable in touch mode.
4140     *
4141     * @param views Focusable views found so far
4142     * @param direction The direction of the focus
4143     */
4144    public void addFocusables(ArrayList<View> views, int direction) {
4145        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4146    }
4147
4148    /**
4149     * Adds any focusable views that are descendants of this view (possibly
4150     * including this view if it is focusable itself) to views. This method
4151     * adds all focusable views regardless if we are in touch mode or
4152     * only views focusable in touch mode if we are in touch mode depending on
4153     * the focusable mode paramater.
4154     *
4155     * @param views Focusable views found so far or null if all we are interested is
4156     *        the number of focusables.
4157     * @param direction The direction of the focus.
4158     * @param focusableMode The type of focusables to be added.
4159     *
4160     * @see #FOCUSABLES_ALL
4161     * @see #FOCUSABLES_TOUCH_MODE
4162     */
4163    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4164        if (!isFocusable()) {
4165            return;
4166        }
4167
4168        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4169                isInTouchMode() && !isFocusableInTouchMode()) {
4170            return;
4171        }
4172
4173        if (views != null) {
4174            views.add(this);
4175        }
4176    }
4177
4178    /**
4179     * Find and return all touchable views that are descendants of this view,
4180     * possibly including this view if it is touchable itself.
4181     *
4182     * @return A list of touchable views
4183     */
4184    public ArrayList<View> getTouchables() {
4185        ArrayList<View> result = new ArrayList<View>();
4186        addTouchables(result);
4187        return result;
4188    }
4189
4190    /**
4191     * Add any touchable views that are descendants of this view (possibly
4192     * including this view if it is touchable itself) to views.
4193     *
4194     * @param views Touchable views found so far
4195     */
4196    public void addTouchables(ArrayList<View> views) {
4197        final int viewFlags = mViewFlags;
4198
4199        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4200                && (viewFlags & ENABLED_MASK) == ENABLED) {
4201            views.add(this);
4202        }
4203    }
4204
4205    /**
4206     * Call this to try to give focus to a specific view or to one of its
4207     * descendants.
4208     *
4209     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4210     * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4211     * while the device is in touch mode.
4212     *
4213     * See also {@link #focusSearch}, which is what you call to say that you
4214     * have focus, and you want your parent to look for the next one.
4215     *
4216     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4217     * {@link #FOCUS_DOWN} and <code>null</code>.
4218     *
4219     * @return Whether this view or one of its descendants actually took focus.
4220     */
4221    public final boolean requestFocus() {
4222        return requestFocus(View.FOCUS_DOWN);
4223    }
4224
4225
4226    /**
4227     * Call this to try to give focus to a specific view or to one of its
4228     * descendants and give it a hint about what direction focus is heading.
4229     *
4230     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4231     * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4232     * while the device is in touch mode.
4233     *
4234     * See also {@link #focusSearch}, which is what you call to say that you
4235     * have focus, and you want your parent to look for the next one.
4236     *
4237     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4238     * <code>null</code> set for the previously focused rectangle.
4239     *
4240     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4241     * @return Whether this view or one of its descendants actually took focus.
4242     */
4243    public final boolean requestFocus(int direction) {
4244        return requestFocus(direction, null);
4245    }
4246
4247    /**
4248     * Call this to try to give focus to a specific view or to one of its descendants
4249     * and give it hints about the direction and a specific rectangle that the focus
4250     * is coming from.  The rectangle can help give larger views a finer grained hint
4251     * about where focus is coming from, and therefore, where to show selection, or
4252     * forward focus change internally.
4253     *
4254     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
4255     * or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
4256     * while the device is in touch mode.
4257     *
4258     * A View will not take focus if it is not visible.
4259     *
4260     * A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
4261     * equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4262     *
4263     * See also {@link #focusSearch}, which is what you call to say that you
4264     * have focus, and you want your parent to look for the next one.
4265     *
4266     * You may wish to override this method if your custom {@link View} has an internal
4267     * {@link View} that it wishes to forward the request to.
4268     *
4269     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4270     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4271     *        to give a finer grained hint about where focus is coming from.  May be null
4272     *        if there is no hint.
4273     * @return Whether this view or one of its descendants actually took focus.
4274     */
4275    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4276        // need to be focusable
4277        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4278                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4279            return false;
4280        }
4281
4282        // need to be focusable in touch mode if in touch mode
4283        if (isInTouchMode() &&
4284                (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4285            return false;
4286        }
4287
4288        // need to not have any parents blocking us
4289        if (hasAncestorThatBlocksDescendantFocus()) {
4290            return false;
4291        }
4292
4293        handleFocusGainInternal(direction, previouslyFocusedRect);
4294        return true;
4295    }
4296
4297    /** Gets the ViewRoot, or null if not attached. */
4298    /*package*/ ViewRoot getViewRoot() {
4299        View root = getRootView();
4300        return root != null ? (ViewRoot)root.getParent() : null;
4301    }
4302
4303    /**
4304     * Call this to try to give focus to a specific view or to one of its descendants. This is a
4305     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4306     * touch mode to request focus when they are touched.
4307     *
4308     * @return Whether this view or one of its descendants actually took focus.
4309     *
4310     * @see #isInTouchMode()
4311     *
4312     */
4313    public final boolean requestFocusFromTouch() {
4314        // Leave touch mode if we need to
4315        if (isInTouchMode()) {
4316            ViewRoot viewRoot = getViewRoot();
4317            if (viewRoot != null) {
4318                viewRoot.ensureTouchMode(false);
4319            }
4320        }
4321        return requestFocus(View.FOCUS_DOWN);
4322    }
4323
4324    /**
4325     * @return Whether any ancestor of this view blocks descendant focus.
4326     */
4327    private boolean hasAncestorThatBlocksDescendantFocus() {
4328        ViewParent ancestor = mParent;
4329        while (ancestor instanceof ViewGroup) {
4330            final ViewGroup vgAncestor = (ViewGroup) ancestor;
4331            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4332                return true;
4333            } else {
4334                ancestor = vgAncestor.getParent();
4335            }
4336        }
4337        return false;
4338    }
4339
4340    /**
4341     * @hide
4342     */
4343    public void dispatchStartTemporaryDetach() {
4344        onStartTemporaryDetach();
4345    }
4346
4347    /**
4348     * This is called when a container is going to temporarily detach a child, with
4349     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4350     * It will either be followed by {@link #onFinishTemporaryDetach()} or
4351     * {@link #onDetachedFromWindow()} when the container is done.
4352     */
4353    public void onStartTemporaryDetach() {
4354        removeUnsetPressCallback();
4355        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
4356    }
4357
4358    /**
4359     * @hide
4360     */
4361    public void dispatchFinishTemporaryDetach() {
4362        onFinishTemporaryDetach();
4363    }
4364
4365    /**
4366     * Called after {@link #onStartTemporaryDetach} when the container is done
4367     * changing the view.
4368     */
4369    public void onFinishTemporaryDetach() {
4370    }
4371
4372    /**
4373     * capture information of this view for later analysis: developement only
4374     * check dynamic switch to make sure we only dump view
4375     * when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
4376     */
4377    private static void captureViewInfo(String subTag, View v) {
4378        if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
4379            return;
4380        }
4381        ViewDebug.dumpCapturedView(subTag, v);
4382    }
4383
4384    /**
4385     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4386     * for this view's window.  Returns null if the view is not currently attached
4387     * to the window.  Normally you will not need to use this directly, but
4388     * just use the standard high-level event callbacks like {@link #onKeyDown}.
4389     */
4390    public KeyEvent.DispatcherState getKeyDispatcherState() {
4391        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4392    }
4393
4394    /**
4395     * Dispatch a key event before it is processed by any input method
4396     * associated with the view hierarchy.  This can be used to intercept
4397     * key events in special situations before the IME consumes them; a
4398     * typical example would be handling the BACK key to update the application's
4399     * UI instead of allowing the IME to see it and close itself.
4400     *
4401     * @param event The key event to be dispatched.
4402     * @return True if the event was handled, false otherwise.
4403     */
4404    public boolean dispatchKeyEventPreIme(KeyEvent event) {
4405        return onKeyPreIme(event.getKeyCode(), event);
4406    }
4407
4408    /**
4409     * Dispatch a key event to the next view on the focus path. This path runs
4410     * from the top of the view tree down to the currently focused view. If this
4411     * view has focus, it will dispatch to itself. Otherwise it will dispatch
4412     * the next node down the focus path. This method also fires any key
4413     * listeners.
4414     *
4415     * @param event The key event to be dispatched.
4416     * @return True if the event was handled, false otherwise.
4417     */
4418    public boolean dispatchKeyEvent(KeyEvent event) {
4419        // If any attached key listener a first crack at the event.
4420
4421        //noinspection SimplifiableIfStatement,deprecation
4422        if (android.util.Config.LOGV) {
4423            captureViewInfo("captureViewKeyEvent", this);
4424        }
4425
4426        //noinspection SimplifiableIfStatement
4427        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4428                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4429            return true;
4430        }
4431
4432        return event.dispatch(this, mAttachInfo != null
4433                ? mAttachInfo.mKeyDispatchState : null, this);
4434    }
4435
4436    /**
4437     * Dispatches a key shortcut event.
4438     *
4439     * @param event The key event to be dispatched.
4440     * @return True if the event was handled by the view, false otherwise.
4441     */
4442    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4443        return onKeyShortcut(event.getKeyCode(), event);
4444    }
4445
4446    /**
4447     * Pass the touch screen motion event down to the target view, or this
4448     * view if it is the target.
4449     *
4450     * @param event The motion event to be dispatched.
4451     * @return True if the event was handled by the view, false otherwise.
4452     */
4453    public boolean dispatchTouchEvent(MotionEvent event) {
4454        if (!onFilterTouchEventForSecurity(event)) {
4455            return false;
4456        }
4457
4458        //noinspection SimplifiableIfStatement
4459        if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4460                mOnTouchListener.onTouch(this, event)) {
4461            return true;
4462        }
4463        return onTouchEvent(event);
4464    }
4465
4466    /**
4467     * Filter the touch event to apply security policies.
4468     *
4469     * @param event The motion event to be filtered.
4470     * @return True if the event should be dispatched, false if the event should be dropped.
4471     *
4472     * @see #getFilterTouchesWhenObscured
4473     */
4474    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
4475        //noinspection RedundantIfStatement
4476        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
4477                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
4478            // Window is obscured, drop this touch.
4479            return false;
4480        }
4481        return true;
4482    }
4483
4484    /**
4485     * Pass a trackball motion event down to the focused view.
4486     *
4487     * @param event The motion event to be dispatched.
4488     * @return True if the event was handled by the view, false otherwise.
4489     */
4490    public boolean dispatchTrackballEvent(MotionEvent event) {
4491        //Log.i("view", "view=" + this + ", " + event.toString());
4492        return onTrackballEvent(event);
4493    }
4494
4495    /**
4496     * Pass a generic motion event down to the focused view.
4497     *
4498     * @param event The motion event to be dispatched.
4499     * @return True if the event was handled by the view, false otherwise.
4500     */
4501    public boolean dispatchGenericMotionEvent(MotionEvent event) {
4502        return onGenericMotionEvent(event);
4503    }
4504
4505    /**
4506     * Called when the window containing this view gains or loses window focus.
4507     * ViewGroups should override to route to their children.
4508     *
4509     * @param hasFocus True if the window containing this view now has focus,
4510     *        false otherwise.
4511     */
4512    public void dispatchWindowFocusChanged(boolean hasFocus) {
4513        onWindowFocusChanged(hasFocus);
4514    }
4515
4516    /**
4517     * Called when the window containing this view gains or loses focus.  Note
4518     * that this is separate from view focus: to receive key events, both
4519     * your view and its window must have focus.  If a window is displayed
4520     * on top of yours that takes input focus, then your own window will lose
4521     * focus but the view focus will remain unchanged.
4522     *
4523     * @param hasWindowFocus True if the window containing this view now has
4524     *        focus, false otherwise.
4525     */
4526    public void onWindowFocusChanged(boolean hasWindowFocus) {
4527        InputMethodManager imm = InputMethodManager.peekInstance();
4528        if (!hasWindowFocus) {
4529            if (isPressed()) {
4530                setPressed(false);
4531            }
4532            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4533                imm.focusOut(this);
4534            }
4535            removeLongPressCallback();
4536            removeTapCallback();
4537            onFocusLost();
4538        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
4539            imm.focusIn(this);
4540        }
4541        refreshDrawableState();
4542    }
4543
4544    /**
4545     * Returns true if this view is in a window that currently has window focus.
4546     * Note that this is not the same as the view itself having focus.
4547     *
4548     * @return True if this view is in a window that currently has window focus.
4549     */
4550    public boolean hasWindowFocus() {
4551        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
4552    }
4553
4554    /**
4555     * Dispatch a view visibility change down the view hierarchy.
4556     * ViewGroups should override to route to their children.
4557     * @param changedView The view whose visibility changed. Could be 'this' or
4558     * an ancestor view.
4559     * @param visibility The new visibility of changedView: {@link #VISIBLE},
4560     * {@link #INVISIBLE} or {@link #GONE}.
4561     */
4562    protected void dispatchVisibilityChanged(View changedView, int visibility) {
4563        onVisibilityChanged(changedView, visibility);
4564    }
4565
4566    /**
4567     * Called when the visibility of the view or an ancestor of the view is changed.
4568     * @param changedView The view whose visibility changed. Could be 'this' or
4569     * an ancestor view.
4570     * @param visibility The new visibility of changedView: {@link #VISIBLE},
4571     * {@link #INVISIBLE} or {@link #GONE}.
4572     */
4573    protected void onVisibilityChanged(View changedView, int visibility) {
4574        if (visibility == VISIBLE) {
4575            if (mAttachInfo != null) {
4576                initialAwakenScrollBars();
4577            } else {
4578                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
4579            }
4580        }
4581    }
4582
4583    /**
4584     * Dispatch a hint about whether this view is displayed. For instance, when
4585     * a View moves out of the screen, it might receives a display hint indicating
4586     * the view is not displayed. Applications should not <em>rely</em> on this hint
4587     * as there is no guarantee that they will receive one.
4588     *
4589     * @param hint A hint about whether or not this view is displayed:
4590     * {@link #VISIBLE} or {@link #INVISIBLE}.
4591     */
4592    public void dispatchDisplayHint(int hint) {
4593        onDisplayHint(hint);
4594    }
4595
4596    /**
4597     * Gives this view a hint about whether is displayed or not. For instance, when
4598     * a View moves out of the screen, it might receives a display hint indicating
4599     * the view is not displayed. Applications should not <em>rely</em> on this hint
4600     * as there is no guarantee that they will receive one.
4601     *
4602     * @param hint A hint about whether or not this view is displayed:
4603     * {@link #VISIBLE} or {@link #INVISIBLE}.
4604     */
4605    protected void onDisplayHint(int hint) {
4606    }
4607
4608    /**
4609     * Dispatch a window visibility change down the view hierarchy.
4610     * ViewGroups should override to route to their children.
4611     *
4612     * @param visibility The new visibility of the window.
4613     *
4614     * @see #onWindowVisibilityChanged
4615     */
4616    public void dispatchWindowVisibilityChanged(int visibility) {
4617        onWindowVisibilityChanged(visibility);
4618    }
4619
4620    /**
4621     * Called when the window containing has change its visibility
4622     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
4623     * that this tells you whether or not your window is being made visible
4624     * to the window manager; this does <em>not</em> tell you whether or not
4625     * your window is obscured by other windows on the screen, even if it
4626     * is itself visible.
4627     *
4628     * @param visibility The new visibility of the window.
4629     */
4630    protected void onWindowVisibilityChanged(int visibility) {
4631        if (visibility == VISIBLE) {
4632            initialAwakenScrollBars();
4633        }
4634    }
4635
4636    /**
4637     * Returns the current visibility of the window this view is attached to
4638     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
4639     *
4640     * @return Returns the current visibility of the view's window.
4641     */
4642    public int getWindowVisibility() {
4643        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
4644    }
4645
4646    /**
4647     * Retrieve the overall visible display size in which the window this view is
4648     * attached to has been positioned in.  This takes into account screen
4649     * decorations above the window, for both cases where the window itself
4650     * is being position inside of them or the window is being placed under
4651     * then and covered insets are used for the window to position its content
4652     * inside.  In effect, this tells you the available area where content can
4653     * be placed and remain visible to users.
4654     *
4655     * <p>This function requires an IPC back to the window manager to retrieve
4656     * the requested information, so should not be used in performance critical
4657     * code like drawing.
4658     *
4659     * @param outRect Filled in with the visible display frame.  If the view
4660     * is not attached to a window, this is simply the raw display size.
4661     */
4662    public void getWindowVisibleDisplayFrame(Rect outRect) {
4663        if (mAttachInfo != null) {
4664            try {
4665                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
4666            } catch (RemoteException e) {
4667                return;
4668            }
4669            // XXX This is really broken, and probably all needs to be done
4670            // in the window manager, and we need to know more about whether
4671            // we want the area behind or in front of the IME.
4672            final Rect insets = mAttachInfo.mVisibleInsets;
4673            outRect.left += insets.left;
4674            outRect.top += insets.top;
4675            outRect.right -= insets.right;
4676            outRect.bottom -= insets.bottom;
4677            return;
4678        }
4679        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
4680        outRect.set(0, 0, d.getWidth(), d.getHeight());
4681    }
4682
4683    /**
4684     * Dispatch a notification about a resource configuration change down
4685     * the view hierarchy.
4686     * ViewGroups should override to route to their children.
4687     *
4688     * @param newConfig The new resource configuration.
4689     *
4690     * @see #onConfigurationChanged
4691     */
4692    public void dispatchConfigurationChanged(Configuration newConfig) {
4693        onConfigurationChanged(newConfig);
4694    }
4695
4696    /**
4697     * Called when the current configuration of the resources being used
4698     * by the application have changed.  You can use this to decide when
4699     * to reload resources that can changed based on orientation and other
4700     * configuration characterstics.  You only need to use this if you are
4701     * not relying on the normal {@link android.app.Activity} mechanism of
4702     * recreating the activity instance upon a configuration change.
4703     *
4704     * @param newConfig The new resource configuration.
4705     */
4706    protected void onConfigurationChanged(Configuration newConfig) {
4707    }
4708
4709    /**
4710     * Private function to aggregate all per-view attributes in to the view
4711     * root.
4712     */
4713    void dispatchCollectViewAttributes(int visibility) {
4714        performCollectViewAttributes(visibility);
4715    }
4716
4717    void performCollectViewAttributes(int visibility) {
4718        //noinspection PointlessBitwiseExpression
4719        if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
4720                == (VISIBLE | KEEP_SCREEN_ON)) {
4721            mAttachInfo.mKeepScreenOn = true;
4722        }
4723    }
4724
4725    void needGlobalAttributesUpdate(boolean force) {
4726        AttachInfo ai = mAttachInfo;
4727        if (ai != null) {
4728            if (ai.mKeepScreenOn || force) {
4729                ai.mRecomputeGlobalAttributes = true;
4730            }
4731        }
4732    }
4733
4734    /**
4735     * Returns whether the device is currently in touch mode.  Touch mode is entered
4736     * once the user begins interacting with the device by touch, and affects various
4737     * things like whether focus is always visible to the user.
4738     *
4739     * @return Whether the device is in touch mode.
4740     */
4741    @ViewDebug.ExportedProperty
4742    public boolean isInTouchMode() {
4743        if (mAttachInfo != null) {
4744            return mAttachInfo.mInTouchMode;
4745        } else {
4746            return ViewRoot.isInTouchMode();
4747        }
4748    }
4749
4750    /**
4751     * Returns the context the view is running in, through which it can
4752     * access the current theme, resources, etc.
4753     *
4754     * @return The view's Context.
4755     */
4756    @ViewDebug.CapturedViewProperty
4757    public final Context getContext() {
4758        return mContext;
4759    }
4760
4761    /**
4762     * Handle a key event before it is processed by any input method
4763     * associated with the view hierarchy.  This can be used to intercept
4764     * key events in special situations before the IME consumes them; a
4765     * typical example would be handling the BACK key to update the application's
4766     * UI instead of allowing the IME to see it and close itself.
4767     *
4768     * @param keyCode The value in event.getKeyCode().
4769     * @param event Description of the key event.
4770     * @return If you handled the event, return true. If you want to allow the
4771     *         event to be handled by the next receiver, return false.
4772     */
4773    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
4774        return false;
4775    }
4776
4777    /**
4778     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
4779     * KeyEvent.Callback.onKeyDown()}: perform press of the view
4780     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
4781     * is released, if the view is enabled and clickable.
4782     *
4783     * @param keyCode A key code that represents the button pressed, from
4784     *                {@link android.view.KeyEvent}.
4785     * @param event   The KeyEvent object that defines the button action.
4786     */
4787    public boolean onKeyDown(int keyCode, KeyEvent event) {
4788        boolean result = false;
4789
4790        switch (keyCode) {
4791            case KeyEvent.KEYCODE_DPAD_CENTER:
4792            case KeyEvent.KEYCODE_ENTER: {
4793                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4794                    return true;
4795                }
4796                // Long clickable items don't necessarily have to be clickable
4797                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
4798                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
4799                        (event.getRepeatCount() == 0)) {
4800                    setPressed(true);
4801                    if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
4802                        postCheckForLongClick(0);
4803                    }
4804                    return true;
4805                }
4806                break;
4807            }
4808        }
4809        return result;
4810    }
4811
4812    /**
4813     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
4814     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
4815     * the event).
4816     */
4817    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
4818        return false;
4819    }
4820
4821    /**
4822     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
4823     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
4824     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
4825     * {@link KeyEvent#KEYCODE_ENTER} is released.
4826     *
4827     * @param keyCode A key code that represents the button pressed, from
4828     *                {@link android.view.KeyEvent}.
4829     * @param event   The KeyEvent object that defines the button action.
4830     */
4831    public boolean onKeyUp(int keyCode, KeyEvent event) {
4832        boolean result = false;
4833
4834        switch (keyCode) {
4835            case KeyEvent.KEYCODE_DPAD_CENTER:
4836            case KeyEvent.KEYCODE_ENTER: {
4837                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4838                    return true;
4839                }
4840                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
4841                    setPressed(false);
4842
4843                    if (!mHasPerformedLongPress) {
4844                        // This is a tap, so remove the longpress check
4845                        removeLongPressCallback();
4846
4847                        result = performClick();
4848                    }
4849                }
4850                break;
4851            }
4852        }
4853        return result;
4854    }
4855
4856    /**
4857     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
4858     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
4859     * the event).
4860     *
4861     * @param keyCode     A key code that represents the button pressed, from
4862     *                    {@link android.view.KeyEvent}.
4863     * @param repeatCount The number of times the action was made.
4864     * @param event       The KeyEvent object that defines the button action.
4865     */
4866    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4867        return false;
4868    }
4869
4870    /**
4871     * Called on the focused view when a key shortcut event is not handled.
4872     * Override this method to implement local key shortcuts for the View.
4873     * Key shortcuts can also be implemented by setting the
4874     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
4875     *
4876     * @param keyCode The value in event.getKeyCode().
4877     * @param event Description of the key event.
4878     * @return If you handled the event, return true. If you want to allow the
4879     *         event to be handled by the next receiver, return false.
4880     */
4881    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
4882        return false;
4883    }
4884
4885    /**
4886     * Check whether the called view is a text editor, in which case it
4887     * would make sense to automatically display a soft input window for
4888     * it.  Subclasses should override this if they implement
4889     * {@link #onCreateInputConnection(EditorInfo)} to return true if
4890     * a call on that method would return a non-null InputConnection, and
4891     * they are really a first-class editor that the user would normally
4892     * start typing on when the go into a window containing your view.
4893     *
4894     * <p>The default implementation always returns false.  This does
4895     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
4896     * will not be called or the user can not otherwise perform edits on your
4897     * view; it is just a hint to the system that this is not the primary
4898     * purpose of this view.
4899     *
4900     * @return Returns true if this view is a text editor, else false.
4901     */
4902    public boolean onCheckIsTextEditor() {
4903        return false;
4904    }
4905
4906    /**
4907     * Create a new InputConnection for an InputMethod to interact
4908     * with the view.  The default implementation returns null, since it doesn't
4909     * support input methods.  You can override this to implement such support.
4910     * This is only needed for views that take focus and text input.
4911     *
4912     * <p>When implementing this, you probably also want to implement
4913     * {@link #onCheckIsTextEditor()} to indicate you will return a
4914     * non-null InputConnection.
4915     *
4916     * @param outAttrs Fill in with attribute information about the connection.
4917     */
4918    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4919        return null;
4920    }
4921
4922    /**
4923     * Called by the {@link android.view.inputmethod.InputMethodManager}
4924     * when a view who is not the current
4925     * input connection target is trying to make a call on the manager.  The
4926     * default implementation returns false; you can override this to return
4927     * true for certain views if you are performing InputConnection proxying
4928     * to them.
4929     * @param view The View that is making the InputMethodManager call.
4930     * @return Return true to allow the call, false to reject.
4931     */
4932    public boolean checkInputConnectionProxy(View view) {
4933        return false;
4934    }
4935
4936    /**
4937     * Show the context menu for this view. It is not safe to hold on to the
4938     * menu after returning from this method.
4939     *
4940     * You should normally not overload this method. Overload
4941     * {@link #onCreateContextMenu(ContextMenu)} or define an
4942     * {@link OnCreateContextMenuListener} to add items to the context menu.
4943     *
4944     * @param menu The context menu to populate
4945     */
4946    public void createContextMenu(ContextMenu menu) {
4947        ContextMenuInfo menuInfo = getContextMenuInfo();
4948
4949        // Sets the current menu info so all items added to menu will have
4950        // my extra info set.
4951        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
4952
4953        onCreateContextMenu(menu);
4954        if (mOnCreateContextMenuListener != null) {
4955            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
4956        }
4957
4958        // Clear the extra information so subsequent items that aren't mine don't
4959        // have my extra info.
4960        ((MenuBuilder)menu).setCurrentMenuInfo(null);
4961
4962        if (mParent != null) {
4963            mParent.createContextMenu(menu);
4964        }
4965    }
4966
4967    /**
4968     * Views should implement this if they have extra information to associate
4969     * with the context menu. The return result is supplied as a parameter to
4970     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
4971     * callback.
4972     *
4973     * @return Extra information about the item for which the context menu
4974     *         should be shown. This information will vary across different
4975     *         subclasses of View.
4976     */
4977    protected ContextMenuInfo getContextMenuInfo() {
4978        return null;
4979    }
4980
4981    /**
4982     * Views should implement this if the view itself is going to add items to
4983     * the context menu.
4984     *
4985     * @param menu the context menu to populate
4986     */
4987    protected void onCreateContextMenu(ContextMenu menu) {
4988    }
4989
4990    /**
4991     * Implement this method to handle trackball motion events.  The
4992     * <em>relative</em> movement of the trackball since the last event
4993     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
4994     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
4995     * that a movement of 1 corresponds to the user pressing one DPAD key (so
4996     * they will often be fractional values, representing the more fine-grained
4997     * movement information available from a trackball).
4998     *
4999     * @param event The motion event.
5000     * @return True if the event was handled, false otherwise.
5001     */
5002    public boolean onTrackballEvent(MotionEvent event) {
5003        return false;
5004    }
5005
5006    /**
5007     * Implement this method to handle generic motion events.
5008     * <p>
5009     * Generic motion events are dispatched to the focused view to describe
5010     * the motions of input devices such as joysticks.  The
5011     * {@link MotionEvent#getSource() source} of the motion event specifies
5012     * the class of input that was received.  Implementations of this method
5013     * must examine the bits in the source before processing the event.
5014     * The following code example shows how this is done.
5015     * </p>
5016     * <code>
5017     * public boolean onGenericMotionEvent(MotionEvent event) {
5018     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
5019     *         float x = event.getX();
5020     *         float y = event.getY();
5021     *         // process the joystick motion
5022     *         return true;
5023     *     }
5024     *     return super.onGenericMotionEvent(event);
5025     * }
5026     * </code>
5027     *
5028     * @param event The generic motion event being processed.
5029     *
5030     * @return Return true if you have consumed the event, false if you haven't.
5031     * The default implementation always returns false.
5032     */
5033    public boolean onGenericMotionEvent(MotionEvent event) {
5034        return false;
5035    }
5036
5037    /**
5038     * Implement this method to handle touch screen motion events.
5039     *
5040     * @param event The motion event.
5041     * @return True if the event was handled, false otherwise.
5042     */
5043    public boolean onTouchEvent(MotionEvent event) {
5044        final int viewFlags = mViewFlags;
5045
5046        if ((viewFlags & ENABLED_MASK) == DISABLED) {
5047            // A disabled view that is clickable still consumes the touch
5048            // events, it just doesn't respond to them.
5049            return (((viewFlags & CLICKABLE) == CLICKABLE ||
5050                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5051        }
5052
5053        if (mTouchDelegate != null) {
5054            if (mTouchDelegate.onTouchEvent(event)) {
5055                return true;
5056            }
5057        }
5058
5059        if (((viewFlags & CLICKABLE) == CLICKABLE ||
5060                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5061            switch (event.getAction()) {
5062                case MotionEvent.ACTION_UP:
5063                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5064                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
5065                        // take focus if we don't have it already and we should in
5066                        // touch mode.
5067                        boolean focusTaken = false;
5068                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5069                            focusTaken = requestFocus();
5070                        }
5071
5072                        if (!mHasPerformedLongPress) {
5073                            // This is a tap, so remove the longpress check
5074                            removeLongPressCallback();
5075
5076                            // Only perform take click actions if we were in the pressed state
5077                            if (!focusTaken) {
5078                                // Use a Runnable and post this rather than calling
5079                                // performClick directly. This lets other visual state
5080                                // of the view update before click actions start.
5081                                if (mPerformClick == null) {
5082                                    mPerformClick = new PerformClick();
5083                                }
5084                                if (!post(mPerformClick)) {
5085                                    performClick();
5086                                }
5087                            }
5088                        }
5089
5090                        if (mUnsetPressedState == null) {
5091                            mUnsetPressedState = new UnsetPressedState();
5092                        }
5093
5094                        if (prepressed) {
5095                            mPrivateFlags |= PRESSED;
5096                            refreshDrawableState();
5097                            postDelayed(mUnsetPressedState,
5098                                    ViewConfiguration.getPressedStateDuration());
5099                        } else if (!post(mUnsetPressedState)) {
5100                            // If the post failed, unpress right now
5101                            mUnsetPressedState.run();
5102                        }
5103                        removeTapCallback();
5104                    }
5105                    break;
5106
5107                case MotionEvent.ACTION_DOWN:
5108                    if (mPendingCheckForTap == null) {
5109                        mPendingCheckForTap = new CheckForTap();
5110                    }
5111                    mPrivateFlags |= PREPRESSED;
5112                    mHasPerformedLongPress = false;
5113                    postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
5114                    break;
5115
5116                case MotionEvent.ACTION_CANCEL:
5117                    mPrivateFlags &= ~PRESSED;
5118                    refreshDrawableState();
5119                    removeTapCallback();
5120                    break;
5121
5122                case MotionEvent.ACTION_MOVE:
5123                    final int x = (int) event.getX();
5124                    final int y = (int) event.getY();
5125
5126                    // Be lenient about moving outside of buttons
5127                    if (!pointInView(x, y, mTouchSlop)) {
5128                        // Outside button
5129                        removeTapCallback();
5130                        if ((mPrivateFlags & PRESSED) != 0) {
5131                            // Remove any future long press/tap checks
5132                            removeLongPressCallback();
5133
5134                            // Need to switch from pressed to not pressed
5135                            mPrivateFlags &= ~PRESSED;
5136                            refreshDrawableState();
5137                        }
5138                    }
5139                    break;
5140            }
5141            return true;
5142        }
5143
5144        return false;
5145    }
5146
5147    /**
5148     * Remove the longpress detection timer.
5149     */
5150    private void removeLongPressCallback() {
5151        if (mPendingCheckForLongPress != null) {
5152          removeCallbacks(mPendingCheckForLongPress);
5153        }
5154    }
5155
5156    /**
5157     * Remove the prepress detection timer.
5158     */
5159    private void removeUnsetPressCallback() {
5160        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5161            setPressed(false);
5162            removeCallbacks(mUnsetPressedState);
5163        }
5164    }
5165
5166    /**
5167     * Remove the tap detection timer.
5168     */
5169    private void removeTapCallback() {
5170        if (mPendingCheckForTap != null) {
5171            mPrivateFlags &= ~PREPRESSED;
5172            removeCallbacks(mPendingCheckForTap);
5173        }
5174    }
5175
5176    /**
5177     * Cancels a pending long press.  Your subclass can use this if you
5178     * want the context menu to come up if the user presses and holds
5179     * at the same place, but you don't want it to come up if they press
5180     * and then move around enough to cause scrolling.
5181     */
5182    public void cancelLongPress() {
5183        removeLongPressCallback();
5184
5185        /*
5186         * The prepressed state handled by the tap callback is a display
5187         * construct, but the tap callback will post a long press callback
5188         * less its own timeout. Remove it here.
5189         */
5190        removeTapCallback();
5191    }
5192
5193    /**
5194     * Sets the TouchDelegate for this View.
5195     */
5196    public void setTouchDelegate(TouchDelegate delegate) {
5197        mTouchDelegate = delegate;
5198    }
5199
5200    /**
5201     * Gets the TouchDelegate for this View.
5202     */
5203    public TouchDelegate getTouchDelegate() {
5204        return mTouchDelegate;
5205    }
5206
5207    /**
5208     * Set flags controlling behavior of this view.
5209     *
5210     * @param flags Constant indicating the value which should be set
5211     * @param mask Constant indicating the bit range that should be changed
5212     */
5213    void setFlags(int flags, int mask) {
5214        int old = mViewFlags;
5215        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5216
5217        int changed = mViewFlags ^ old;
5218        if (changed == 0) {
5219            return;
5220        }
5221        int privateFlags = mPrivateFlags;
5222
5223        /* Check if the FOCUSABLE bit has changed */
5224        if (((changed & FOCUSABLE_MASK) != 0) &&
5225                ((privateFlags & HAS_BOUNDS) !=0)) {
5226            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5227                    && ((privateFlags & FOCUSED) != 0)) {
5228                /* Give up focus if we are no longer focusable */
5229                clearFocus();
5230            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
5231                    && ((privateFlags & FOCUSED) == 0)) {
5232                /*
5233                 * Tell the view system that we are now available to take focus
5234                 * if no one else already has it.
5235                 */
5236                if (mParent != null) mParent.focusableViewAvailable(this);
5237            }
5238        }
5239
5240        if ((flags & VISIBILITY_MASK) == VISIBLE) {
5241            if ((changed & VISIBILITY_MASK) != 0) {
5242                /*
5243                 * If this view is becoming visible, set the DRAWN flag so that
5244                 * the next invalidate() will not be skipped.
5245                 */
5246                mPrivateFlags |= DRAWN;
5247
5248                needGlobalAttributesUpdate(true);
5249
5250                // a view becoming visible is worth notifying the parent
5251                // about in case nothing has focus.  even if this specific view
5252                // isn't focusable, it may contain something that is, so let
5253                // the root view try to give this focus if nothing else does.
5254                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
5255                    mParent.focusableViewAvailable(this);
5256                }
5257            }
5258        }
5259
5260        /* Check if the GONE bit has changed */
5261        if ((changed & GONE) != 0) {
5262            needGlobalAttributesUpdate(false);
5263            requestLayout();
5264            invalidate();
5265
5266            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
5267                if (hasFocus()) clearFocus();
5268                destroyDrawingCache();
5269            }
5270            if (mAttachInfo != null) {
5271                mAttachInfo.mViewVisibilityChanged = true;
5272            }
5273        }
5274
5275        /* Check if the VISIBLE bit has changed */
5276        if ((changed & INVISIBLE) != 0) {
5277            needGlobalAttributesUpdate(false);
5278            invalidate();
5279
5280            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
5281                // root view becoming invisible shouldn't clear focus
5282                if (getRootView() != this) {
5283                    clearFocus();
5284                }
5285            }
5286            if (mAttachInfo != null) {
5287                mAttachInfo.mViewVisibilityChanged = true;
5288            }
5289        }
5290
5291        if ((changed & VISIBILITY_MASK) != 0) {
5292            if (mParent instanceof ViewGroup) {
5293                ((ViewGroup)mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
5294            }
5295            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
5296        }
5297
5298        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
5299            destroyDrawingCache();
5300        }
5301
5302        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
5303            destroyDrawingCache();
5304            mPrivateFlags &= ~DRAWING_CACHE_VALID;
5305        }
5306
5307        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
5308            destroyDrawingCache();
5309            mPrivateFlags &= ~DRAWING_CACHE_VALID;
5310        }
5311
5312        if ((changed & DRAW_MASK) != 0) {
5313            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
5314                if (mBGDrawable != null) {
5315                    mPrivateFlags &= ~SKIP_DRAW;
5316                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
5317                } else {
5318                    mPrivateFlags |= SKIP_DRAW;
5319                }
5320            } else {
5321                mPrivateFlags &= ~SKIP_DRAW;
5322            }
5323            requestLayout();
5324            invalidate();
5325        }
5326
5327        if ((changed & KEEP_SCREEN_ON) != 0) {
5328            if (mParent != null) {
5329                mParent.recomputeViewAttributes(this);
5330            }
5331        }
5332    }
5333
5334    /**
5335     * Change the view's z order in the tree, so it's on top of other sibling
5336     * views
5337     */
5338    public void bringToFront() {
5339        if (mParent != null) {
5340            mParent.bringChildToFront(this);
5341        }
5342    }
5343
5344    /**
5345     * This is called in response to an internal scroll in this view (i.e., the
5346     * view scrolled its own contents). This is typically as a result of
5347     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
5348     * called.
5349     *
5350     * @param l Current horizontal scroll origin.
5351     * @param t Current vertical scroll origin.
5352     * @param oldl Previous horizontal scroll origin.
5353     * @param oldt Previous vertical scroll origin.
5354     */
5355    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
5356        mBackgroundSizeChanged = true;
5357
5358        final AttachInfo ai = mAttachInfo;
5359        if (ai != null) {
5360            ai.mViewScrollChanged = true;
5361        }
5362    }
5363
5364    /**
5365     * Interface definition for a callback to be invoked when the layout bounds of a view
5366     * changes due to layout processing.
5367     */
5368    public interface OnLayoutChangeListener {
5369        /**
5370         * Called when the focus state of a view has changed.
5371         *
5372         * @param v The view whose state has changed.
5373         * @param left The new value of the view's left property.
5374         * @param top The new value of the view's top property.
5375         * @param right The new value of the view's right property.
5376         * @param bottom The new value of the view's bottom property.
5377         * @param oldLeft The previous value of the view's left property.
5378         * @param oldTop The previous value of the view's top property.
5379         * @param oldRight The previous value of the view's right property.
5380         * @param oldBottom The previous value of the view's bottom property.
5381         */
5382        void onLayoutChange(View v, int left, int top, int right, int bottom,
5383            int oldLeft, int oldTop, int oldRight, int oldBottom);
5384    }
5385
5386    /**
5387     * This is called during layout when the size of this view has changed. If
5388     * you were just added to the view hierarchy, you're called with the old
5389     * values of 0.
5390     *
5391     * @param w Current width of this view.
5392     * @param h Current height of this view.
5393     * @param oldw Old width of this view.
5394     * @param oldh Old height of this view.
5395     */
5396    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
5397    }
5398
5399    /**
5400     * Called by draw to draw the child views. This may be overridden
5401     * by derived classes to gain control just before its children are drawn
5402     * (but after its own view has been drawn).
5403     * @param canvas the canvas on which to draw the view
5404     */
5405    protected void dispatchDraw(Canvas canvas) {
5406    }
5407
5408    /**
5409     * Gets the parent of this view. Note that the parent is a
5410     * ViewParent and not necessarily a View.
5411     *
5412     * @return Parent of this view.
5413     */
5414    public final ViewParent getParent() {
5415        return mParent;
5416    }
5417
5418    /**
5419     * Return the scrolled left position of this view. This is the left edge of
5420     * the displayed part of your view. You do not need to draw any pixels
5421     * farther left, since those are outside of the frame of your view on
5422     * screen.
5423     *
5424     * @return The left edge of the displayed part of your view, in pixels.
5425     */
5426    public final int getScrollX() {
5427        return mScrollX;
5428    }
5429
5430    /**
5431     * Return the scrolled top position of this view. This is the top edge of
5432     * the displayed part of your view. You do not need to draw any pixels above
5433     * it, since those are outside of the frame of your view on screen.
5434     *
5435     * @return The top edge of the displayed part of your view, in pixels.
5436     */
5437    public final int getScrollY() {
5438        return mScrollY;
5439    }
5440
5441    /**
5442     * Return the width of the your view.
5443     *
5444     * @return The width of your view, in pixels.
5445     */
5446    @ViewDebug.ExportedProperty(category = "layout")
5447    public final int getWidth() {
5448        return mRight - mLeft;
5449    }
5450
5451    /**
5452     * Return the height of your view.
5453     *
5454     * @return The height of your view, in pixels.
5455     */
5456    @ViewDebug.ExportedProperty(category = "layout")
5457    public final int getHeight() {
5458        return mBottom - mTop;
5459    }
5460
5461    /**
5462     * Return the visible drawing bounds of your view. Fills in the output
5463     * rectangle with the values from getScrollX(), getScrollY(),
5464     * getWidth(), and getHeight().
5465     *
5466     * @param outRect The (scrolled) drawing bounds of the view.
5467     */
5468    public void getDrawingRect(Rect outRect) {
5469        outRect.left = mScrollX;
5470        outRect.top = mScrollY;
5471        outRect.right = mScrollX + (mRight - mLeft);
5472        outRect.bottom = mScrollY + (mBottom - mTop);
5473    }
5474
5475    /**
5476     * Like {@link #getMeasuredWidthAndState()}, but only returns the
5477     * raw width component (that is the result is masked by
5478     * {@link #MEASURED_SIZE_MASK}).
5479     *
5480     * @return The raw measured width of this view.
5481     */
5482    public final int getMeasuredWidth() {
5483        return mMeasuredWidth & MEASURED_SIZE_MASK;
5484    }
5485
5486    /**
5487     * Return the full width measurement information for this view as computed
5488     * by the most recent call to {@link #measure}.  This result is a bit mask
5489     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5490     * This should be used during measurement and layout calculations only. Use
5491     * {@link #getWidth()} to see how wide a view is after layout.
5492     *
5493     * @return The measured width of this view as a bit mask.
5494     */
5495    public final int getMeasuredWidthAndState() {
5496        return mMeasuredWidth;
5497    }
5498
5499    /**
5500     * Like {@link #getMeasuredHeightAndState()}, but only returns the
5501     * raw width component (that is the result is masked by
5502     * {@link #MEASURED_SIZE_MASK}).
5503     *
5504     * @return The raw measured height of this view.
5505     */
5506    public final int getMeasuredHeight() {
5507        return mMeasuredHeight & MEASURED_SIZE_MASK;
5508    }
5509
5510    /**
5511     * Return the full height measurement information for this view as computed
5512     * by the most recent call to {@link #measure}.  This result is a bit mask
5513     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
5514     * This should be used during measurement and layout calculations only. Use
5515     * {@link #getHeight()} to see how wide a view is after layout.
5516     *
5517     * @return The measured width of this view as a bit mask.
5518     */
5519    public final int getMeasuredHeightAndState() {
5520        return mMeasuredHeight;
5521    }
5522
5523    /**
5524     * Return only the state bits of {@link #getMeasuredWidthAndState()}
5525     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
5526     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
5527     * and the height component is at the shifted bits
5528     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
5529     */
5530    public final int getMeasuredState() {
5531        return (mMeasuredWidth&MEASURED_STATE_MASK)
5532                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
5533                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
5534    }
5535
5536    /**
5537     * The transform matrix of this view, which is calculated based on the current
5538     * roation, scale, and pivot properties.
5539     *
5540     * @see #getRotation()
5541     * @see #getScaleX()
5542     * @see #getScaleY()
5543     * @see #getPivotX()
5544     * @see #getPivotY()
5545     * @return The current transform matrix for the view
5546     */
5547    public Matrix getMatrix() {
5548        updateMatrix();
5549        return mMatrix;
5550    }
5551
5552    /**
5553     * Utility function to determine if the value is far enough away from zero to be
5554     * considered non-zero.
5555     * @param value A floating point value to check for zero-ness
5556     * @return whether the passed-in value is far enough away from zero to be considered non-zero
5557     */
5558    private static boolean nonzero(float value) {
5559        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
5560    }
5561
5562    /**
5563     * Returns true if the transform matrix is the identity matrix.
5564     * Recomputes the matrix if necessary.
5565     *
5566     * @return True if the transform matrix is the identity matrix, false otherwise.
5567     */
5568    final boolean hasIdentityMatrix() {
5569        updateMatrix();
5570        return mMatrixIsIdentity;
5571    }
5572
5573    /**
5574     * Recomputes the transform matrix if necessary.
5575     */
5576    private void updateMatrix() {
5577        if (mMatrixDirty) {
5578            // transform-related properties have changed since the last time someone
5579            // asked for the matrix; recalculate it with the current values
5580
5581            // Figure out if we need to update the pivot point
5582            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5583                if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
5584                    mPrevWidth = mRight - mLeft;
5585                    mPrevHeight = mBottom - mTop;
5586                    mPivotX = mPrevWidth / 2f;
5587                    mPivotY = mPrevHeight / 2f;
5588                }
5589            }
5590            mMatrix.reset();
5591            if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
5592                mMatrix.setTranslate(mTranslationX, mTranslationY);
5593                mMatrix.preRotate(mRotation, mPivotX, mPivotY);
5594                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5595            } else {
5596                if (mCamera == null) {
5597                    mCamera = new Camera();
5598                    matrix3D = new Matrix();
5599                }
5600                mCamera.save();
5601                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
5602                mCamera.rotateX(mRotationX);
5603                mCamera.rotateY(mRotationY);
5604                mCamera.rotateZ(-mRotation);
5605                mCamera.getMatrix(matrix3D);
5606                matrix3D.preTranslate(-mPivotX, -mPivotY);
5607                matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
5608                mMatrix.postConcat(matrix3D);
5609                mCamera.restore();
5610            }
5611            mMatrixDirty = false;
5612            mMatrixIsIdentity = mMatrix.isIdentity();
5613            mInverseMatrixDirty = true;
5614        }
5615    }
5616
5617    /**
5618     * Utility method to retrieve the inverse of the current mMatrix property.
5619     * We cache the matrix to avoid recalculating it when transform properties
5620     * have not changed.
5621     *
5622     * @return The inverse of the current matrix of this view.
5623     */
5624    final Matrix getInverseMatrix() {
5625        updateMatrix();
5626        if (mInverseMatrixDirty) {
5627            if (mInverseMatrix == null) {
5628                mInverseMatrix = new Matrix();
5629            }
5630            mMatrix.invert(mInverseMatrix);
5631            mInverseMatrixDirty = false;
5632        }
5633        return mInverseMatrix;
5634    }
5635
5636    /**
5637     * The degrees that the view is rotated around the pivot point.
5638     *
5639     * @see #getPivotX()
5640     * @see #getPivotY()
5641     * @return The degrees of rotation.
5642     */
5643    public float getRotation() {
5644        return mRotation;
5645    }
5646
5647    /**
5648     * Sets the degrees that the view is rotated around the pivot point. Increasing values
5649     * result in clockwise rotation.
5650     *
5651     * @param rotation The degrees of rotation.
5652     * @see #getPivotX()
5653     * @see #getPivotY()
5654     *
5655     * @attr ref android.R.styleable#View_rotation
5656     */
5657    public void setRotation(float rotation) {
5658        if (mRotation != rotation) {
5659            // Double-invalidation is necessary to capture view's old and new areas
5660            invalidate(false);
5661            mRotation = rotation;
5662            mMatrixDirty = true;
5663            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5664            invalidate(false);
5665        }
5666    }
5667
5668    /**
5669     * The degrees that the view is rotated around the vertical axis through the pivot point.
5670     *
5671     * @see #getPivotX()
5672     * @see #getPivotY()
5673     * @return The degrees of Y rotation.
5674     */
5675    public float getRotationY() {
5676        return mRotationY;
5677    }
5678
5679    /**
5680     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
5681     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
5682     * down the y axis.
5683     *
5684     * @param rotationY The degrees of Y rotation.
5685     * @see #getPivotX()
5686     * @see #getPivotY()
5687     *
5688     * @attr ref android.R.styleable#View_rotationY
5689     */
5690    public void setRotationY(float rotationY) {
5691        if (mRotationY != rotationY) {
5692            // Double-invalidation is necessary to capture view's old and new areas
5693            invalidate(false);
5694            mRotationY = rotationY;
5695            mMatrixDirty = true;
5696            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5697            invalidate(false);
5698        }
5699    }
5700
5701    /**
5702     * The degrees that the view is rotated around the horizontal axis through the pivot point.
5703     *
5704     * @see #getPivotX()
5705     * @see #getPivotY()
5706     * @return The degrees of X rotation.
5707     */
5708    public float getRotationX() {
5709        return mRotationX;
5710    }
5711
5712    /**
5713     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
5714     * Increasing values result in clockwise rotation from the viewpoint of looking down the
5715     * x axis.
5716     *
5717     * @param rotationX The degrees of X rotation.
5718     * @see #getPivotX()
5719     * @see #getPivotY()
5720     *
5721     * @attr ref android.R.styleable#View_rotationX
5722     */
5723    public void setRotationX(float rotationX) {
5724        if (mRotationX != rotationX) {
5725            // Double-invalidation is necessary to capture view's old and new areas
5726            invalidate(false);
5727            mRotationX = rotationX;
5728            mMatrixDirty = true;
5729            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5730            invalidate(false);
5731        }
5732    }
5733
5734    /**
5735     * The amount that the view is scaled in x around the pivot point, as a proportion of
5736     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
5737     *
5738     * <p>By default, this is 1.0f.
5739     *
5740     * @see #getPivotX()
5741     * @see #getPivotY()
5742     * @return The scaling factor.
5743     */
5744    public float getScaleX() {
5745        return mScaleX;
5746    }
5747
5748    /**
5749     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
5750     * the view's unscaled width. A value of 1 means that no scaling is applied.
5751     *
5752     * @param scaleX The scaling factor.
5753     * @see #getPivotX()
5754     * @see #getPivotY()
5755     *
5756     * @attr ref android.R.styleable#View_scaleX
5757     */
5758    public void setScaleX(float scaleX) {
5759        if (mScaleX != scaleX) {
5760            // Double-invalidation is necessary to capture view's old and new areas
5761            invalidate(false);
5762            mScaleX = scaleX;
5763            mMatrixDirty = true;
5764            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5765            invalidate(false);
5766        }
5767    }
5768
5769    /**
5770     * The amount that the view is scaled in y around the pivot point, as a proportion of
5771     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
5772     *
5773     * <p>By default, this is 1.0f.
5774     *
5775     * @see #getPivotX()
5776     * @see #getPivotY()
5777     * @return The scaling factor.
5778     */
5779    public float getScaleY() {
5780        return mScaleY;
5781    }
5782
5783    /**
5784     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
5785     * the view's unscaled width. A value of 1 means that no scaling is applied.
5786     *
5787     * @param scaleY The scaling factor.
5788     * @see #getPivotX()
5789     * @see #getPivotY()
5790     *
5791     * @attr ref android.R.styleable#View_scaleY
5792     */
5793    public void setScaleY(float scaleY) {
5794        if (mScaleY != scaleY) {
5795            // Double-invalidation is necessary to capture view's old and new areas
5796            invalidate(false);
5797            mScaleY = scaleY;
5798            mMatrixDirty = true;
5799            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5800            invalidate(false);
5801        }
5802    }
5803
5804    /**
5805     * The x location of the point around which the view is {@link #setRotation(float) rotated}
5806     * and {@link #setScaleX(float) scaled}.
5807     *
5808     * @see #getRotation()
5809     * @see #getScaleX()
5810     * @see #getScaleY()
5811     * @see #getPivotY()
5812     * @return The x location of the pivot point.
5813     */
5814    public float getPivotX() {
5815        return mPivotX;
5816    }
5817
5818    /**
5819     * Sets the x location of the point around which the view is
5820     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
5821     * By default, the pivot point is centered on the object.
5822     * Setting this property disables this behavior and causes the view to use only the
5823     * explicitly set pivotX and pivotY values.
5824     *
5825     * @param pivotX The x location of the pivot point.
5826     * @see #getRotation()
5827     * @see #getScaleX()
5828     * @see #getScaleY()
5829     * @see #getPivotY()
5830     *
5831     * @attr ref android.R.styleable#View_transformPivotX
5832     */
5833    public void setPivotX(float pivotX) {
5834        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
5835        if (mPivotX != pivotX) {
5836            // Double-invalidation is necessary to capture view's old and new areas
5837            invalidate(false);
5838            mPivotX = pivotX;
5839            mMatrixDirty = true;
5840            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5841            invalidate(false);
5842        }
5843    }
5844
5845    /**
5846     * The y location of the point around which the view is {@link #setRotation(float) rotated}
5847     * and {@link #setScaleY(float) scaled}.
5848     *
5849     * @see #getRotation()
5850     * @see #getScaleX()
5851     * @see #getScaleY()
5852     * @see #getPivotY()
5853     * @return The y location of the pivot point.
5854     */
5855    public float getPivotY() {
5856        return mPivotY;
5857    }
5858
5859    /**
5860     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
5861     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
5862     * Setting this property disables this behavior and causes the view to use only the
5863     * explicitly set pivotX and pivotY values.
5864     *
5865     * @param pivotY The y location of the pivot point.
5866     * @see #getRotation()
5867     * @see #getScaleX()
5868     * @see #getScaleY()
5869     * @see #getPivotY()
5870     *
5871     * @attr ref android.R.styleable#View_transformPivotY
5872     */
5873    public void setPivotY(float pivotY) {
5874        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
5875        if (mPivotY != pivotY) {
5876            // Double-invalidation is necessary to capture view's old and new areas
5877            invalidate(false);
5878            mPivotY = pivotY;
5879            mMatrixDirty = true;
5880            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5881            invalidate(false);
5882        }
5883    }
5884
5885    /**
5886     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
5887     * completely transparent and 1 means the view is completely opaque.
5888     *
5889     * <p>By default this is 1.0f.
5890     * @return The opacity of the view.
5891     */
5892    public float getAlpha() {
5893        return mAlpha;
5894    }
5895
5896    /**
5897     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
5898     * completely transparent and 1 means the view is completely opaque.</p>
5899     *
5900     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
5901     * responsible for applying the opacity itself. Otherwise, calling this method is
5902     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
5903     * setting a hardware layer.</p>
5904     *
5905     * @param alpha The opacity of the view.
5906     *
5907     * @see #setLayerType(int, android.graphics.Paint)
5908     *
5909     * @attr ref android.R.styleable#View_alpha
5910     */
5911    public void setAlpha(float alpha) {
5912        mAlpha = alpha;
5913        if (onSetAlpha((int) (alpha * 255))) {
5914            mPrivateFlags |= ALPHA_SET;
5915            // subclass is handling alpha - don't optimize rendering cache invalidation
5916            invalidate();
5917        } else {
5918            mPrivateFlags &= ~ALPHA_SET;
5919            invalidate(false);
5920        }
5921    }
5922
5923    /**
5924     * Top position of this view relative to its parent.
5925     *
5926     * @return The top of this view, in pixels.
5927     */
5928    @ViewDebug.CapturedViewProperty
5929    public final int getTop() {
5930        return mTop;
5931    }
5932
5933    /**
5934     * Sets the top position of this view relative to its parent. This method is meant to be called
5935     * by the layout system and should not generally be called otherwise, because the property
5936     * may be changed at any time by the layout.
5937     *
5938     * @param top The top of this view, in pixels.
5939     */
5940    public final void setTop(int top) {
5941        if (top != mTop) {
5942            updateMatrix();
5943            if (mMatrixIsIdentity) {
5944                final ViewParent p = mParent;
5945                if (p != null && mAttachInfo != null) {
5946                    final Rect r = mAttachInfo.mTmpInvalRect;
5947                    int minTop;
5948                    int yLoc;
5949                    if (top < mTop) {
5950                        minTop = top;
5951                        yLoc = top - mTop;
5952                    } else {
5953                        minTop = mTop;
5954                        yLoc = 0;
5955                    }
5956                    r.set(0, yLoc, mRight - mLeft, mBottom - minTop);
5957                    p.invalidateChild(this, r);
5958                }
5959            } else {
5960                // Double-invalidation is necessary to capture view's old and new areas
5961                invalidate();
5962            }
5963
5964            int width = mRight - mLeft;
5965            int oldHeight = mBottom - mTop;
5966
5967            mTop = top;
5968
5969            onSizeChanged(width, mBottom - mTop, width, oldHeight);
5970
5971            if (!mMatrixIsIdentity) {
5972                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
5973                    // A change in dimension means an auto-centered pivot point changes, too
5974                    mMatrixDirty = true;
5975                }
5976                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
5977                invalidate();
5978            }
5979            mBackgroundSizeChanged = true;
5980        }
5981    }
5982
5983    /**
5984     * Bottom position of this view relative to its parent.
5985     *
5986     * @return The bottom of this view, in pixels.
5987     */
5988    @ViewDebug.CapturedViewProperty
5989    public final int getBottom() {
5990        return mBottom;
5991    }
5992
5993    /**
5994     * True if this view has changed since the last time being drawn.
5995     *
5996     * @return The dirty state of this view.
5997     */
5998    public boolean isDirty() {
5999        return (mPrivateFlags & DIRTY_MASK) != 0;
6000    }
6001
6002    /**
6003     * Sets the bottom position of this view relative to its parent. This method is meant to be
6004     * called by the layout system and should not generally be called otherwise, because the
6005     * property may be changed at any time by the layout.
6006     *
6007     * @param bottom The bottom of this view, in pixels.
6008     */
6009    public final void setBottom(int bottom) {
6010        if (bottom != mBottom) {
6011            updateMatrix();
6012            if (mMatrixIsIdentity) {
6013                final ViewParent p = mParent;
6014                if (p != null && mAttachInfo != null) {
6015                    final Rect r = mAttachInfo.mTmpInvalRect;
6016                    int maxBottom;
6017                    if (bottom < mBottom) {
6018                        maxBottom = mBottom;
6019                    } else {
6020                        maxBottom = bottom;
6021                    }
6022                    r.set(0, 0, mRight - mLeft, maxBottom - mTop);
6023                    p.invalidateChild(this, r);
6024                }
6025            } else {
6026                // Double-invalidation is necessary to capture view's old and new areas
6027                invalidate();
6028            }
6029
6030            int width = mRight - mLeft;
6031            int oldHeight = mBottom - mTop;
6032
6033            mBottom = bottom;
6034
6035            onSizeChanged(width, mBottom - mTop, width, oldHeight);
6036
6037            if (!mMatrixIsIdentity) {
6038                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6039                    // A change in dimension means an auto-centered pivot point changes, too
6040                    mMatrixDirty = true;
6041                }
6042                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6043                invalidate();
6044            }
6045            mBackgroundSizeChanged = true;
6046        }
6047    }
6048
6049    /**
6050     * Left position of this view relative to its parent.
6051     *
6052     * @return The left edge of this view, in pixels.
6053     */
6054    @ViewDebug.CapturedViewProperty
6055    public final int getLeft() {
6056        return mLeft;
6057    }
6058
6059    /**
6060     * Sets the left position of this view relative to its parent. This method is meant to be called
6061     * by the layout system and should not generally be called otherwise, because the property
6062     * may be changed at any time by the layout.
6063     *
6064     * @param left The bottom of this view, in pixels.
6065     */
6066    public final void setLeft(int left) {
6067        if (left != mLeft) {
6068            updateMatrix();
6069            if (mMatrixIsIdentity) {
6070                final ViewParent p = mParent;
6071                if (p != null && mAttachInfo != null) {
6072                    final Rect r = mAttachInfo.mTmpInvalRect;
6073                    int minLeft;
6074                    int xLoc;
6075                    if (left < mLeft) {
6076                        minLeft = left;
6077                        xLoc = left - mLeft;
6078                    } else {
6079                        minLeft = mLeft;
6080                        xLoc = 0;
6081                    }
6082                    r.set(xLoc, 0, mRight - minLeft, mBottom - mTop);
6083                    p.invalidateChild(this, r);
6084                }
6085            } else {
6086                // Double-invalidation is necessary to capture view's old and new areas
6087                invalidate();
6088            }
6089
6090            int oldWidth = mRight - mLeft;
6091            int height = mBottom - mTop;
6092
6093            mLeft = left;
6094
6095            onSizeChanged(mRight - mLeft, height, oldWidth, height);
6096
6097            if (!mMatrixIsIdentity) {
6098                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6099                    // A change in dimension means an auto-centered pivot point changes, too
6100                    mMatrixDirty = true;
6101                }
6102                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6103                invalidate();
6104            }
6105            mBackgroundSizeChanged = true;
6106        }
6107    }
6108
6109    /**
6110     * Right position of this view relative to its parent.
6111     *
6112     * @return The right edge of this view, in pixels.
6113     */
6114    @ViewDebug.CapturedViewProperty
6115    public final int getRight() {
6116        return mRight;
6117    }
6118
6119    /**
6120     * Sets the right position of this view relative to its parent. This method is meant to be called
6121     * by the layout system and should not generally be called otherwise, because the property
6122     * may be changed at any time by the layout.
6123     *
6124     * @param right The bottom of this view, in pixels.
6125     */
6126    public final void setRight(int right) {
6127        if (right != mRight) {
6128            updateMatrix();
6129            if (mMatrixIsIdentity) {
6130                final ViewParent p = mParent;
6131                if (p != null && mAttachInfo != null) {
6132                    final Rect r = mAttachInfo.mTmpInvalRect;
6133                    int maxRight;
6134                    if (right < mRight) {
6135                        maxRight = mRight;
6136                    } else {
6137                        maxRight = right;
6138                    }
6139                    r.set(0, 0, maxRight - mLeft, mBottom - mTop);
6140                    p.invalidateChild(this, r);
6141                }
6142            } else {
6143                // Double-invalidation is necessary to capture view's old and new areas
6144                invalidate();
6145            }
6146
6147            int oldWidth = mRight - mLeft;
6148            int height = mBottom - mTop;
6149
6150            mRight = right;
6151
6152            onSizeChanged(mRight - mLeft, height, oldWidth, height);
6153
6154            if (!mMatrixIsIdentity) {
6155                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6156                    // A change in dimension means an auto-centered pivot point changes, too
6157                    mMatrixDirty = true;
6158                }
6159                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6160                invalidate();
6161            }
6162            mBackgroundSizeChanged = true;
6163        }
6164    }
6165
6166    /**
6167     * The visual x position of this view, in pixels. This is equivalent to the
6168     * {@link #setTranslationX(float) translationX} property plus the current
6169     * {@link #getLeft() left} property.
6170     *
6171     * @return The visual x position of this view, in pixels.
6172     */
6173    public float getX() {
6174        return mLeft + mTranslationX;
6175    }
6176
6177    /**
6178     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
6179     * {@link #setTranslationX(float) translationX} property to be the difference between
6180     * the x value passed in and the current {@link #getLeft() left} property.
6181     *
6182     * @param x The visual x position of this view, in pixels.
6183     */
6184    public void setX(float x) {
6185        setTranslationX(x - mLeft);
6186    }
6187
6188    /**
6189     * The visual y position of this view, in pixels. This is equivalent to the
6190     * {@link #setTranslationY(float) translationY} property plus the current
6191     * {@link #getTop() top} property.
6192     *
6193     * @return The visual y position of this view, in pixels.
6194     */
6195    public float getY() {
6196        return mTop + mTranslationY;
6197    }
6198
6199    /**
6200     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
6201     * {@link #setTranslationY(float) translationY} property to be the difference between
6202     * the y value passed in and the current {@link #getTop() top} property.
6203     *
6204     * @param y The visual y position of this view, in pixels.
6205     */
6206    public void setY(float y) {
6207        setTranslationY(y - mTop);
6208    }
6209
6210
6211    /**
6212     * The horizontal location of this view relative to its {@link #getLeft() left} position.
6213     * This position is post-layout, in addition to wherever the object's
6214     * layout placed it.
6215     *
6216     * @return The horizontal position of this view relative to its left position, in pixels.
6217     */
6218    public float getTranslationX() {
6219        return mTranslationX;
6220    }
6221
6222    /**
6223     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
6224     * This effectively positions the object post-layout, in addition to wherever the object's
6225     * layout placed it.
6226     *
6227     * @param translationX The horizontal position of this view relative to its left position,
6228     * in pixels.
6229     *
6230     * @attr ref android.R.styleable#View_translationX
6231     */
6232    public void setTranslationX(float translationX) {
6233        if (mTranslationX != translationX) {
6234            // Double-invalidation is necessary to capture view's old and new areas
6235            invalidate(false);
6236            mTranslationX = translationX;
6237            mMatrixDirty = true;
6238            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6239            invalidate(false);
6240        }
6241    }
6242
6243    /**
6244     * The horizontal location of this view relative to its {@link #getTop() top} position.
6245     * This position is post-layout, in addition to wherever the object's
6246     * layout placed it.
6247     *
6248     * @return The vertical position of this view relative to its top position,
6249     * in pixels.
6250     */
6251    public float getTranslationY() {
6252        return mTranslationY;
6253    }
6254
6255    /**
6256     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
6257     * This effectively positions the object post-layout, in addition to wherever the object's
6258     * layout placed it.
6259     *
6260     * @param translationY The vertical position of this view relative to its top position,
6261     * in pixels.
6262     *
6263     * @attr ref android.R.styleable#View_translationY
6264     */
6265    public void setTranslationY(float translationY) {
6266        if (mTranslationY != translationY) {
6267            // Double-invalidation is necessary to capture view's old and new areas
6268            invalidate(false);
6269            mTranslationY = translationY;
6270            mMatrixDirty = true;
6271            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6272            invalidate(false);
6273        }
6274    }
6275
6276    /**
6277     * Hit rectangle in parent's coordinates
6278     *
6279     * @param outRect The hit rectangle of the view.
6280     */
6281    public void getHitRect(Rect outRect) {
6282        updateMatrix();
6283        if (mMatrixIsIdentity || mAttachInfo == null) {
6284            outRect.set(mLeft, mTop, mRight, mBottom);
6285        } else {
6286            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
6287            tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
6288            mMatrix.mapRect(tmpRect);
6289            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
6290                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
6291        }
6292    }
6293
6294    /**
6295     * Determines whether the given point, in local coordinates is inside the view.
6296     */
6297    /*package*/ final boolean pointInView(float localX, float localY) {
6298        return localX >= 0 && localX < (mRight - mLeft)
6299                && localY >= 0 && localY < (mBottom - mTop);
6300    }
6301
6302    /**
6303     * Utility method to determine whether the given point, in local coordinates,
6304     * is inside the view, where the area of the view is expanded by the slop factor.
6305     * This method is called while processing touch-move events to determine if the event
6306     * is still within the view.
6307     */
6308    private boolean pointInView(float localX, float localY, float slop) {
6309        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
6310                localY < ((mBottom - mTop) + slop);
6311    }
6312
6313    /**
6314     * When a view has focus and the user navigates away from it, the next view is searched for
6315     * starting from the rectangle filled in by this method.
6316     *
6317     * By default, the rectange is the {@link #getDrawingRect})of the view.  However, if your
6318     * view maintains some idea of internal selection, such as a cursor, or a selected row
6319     * or column, you should override this method and fill in a more specific rectangle.
6320     *
6321     * @param r The rectangle to fill in, in this view's coordinates.
6322     */
6323    public void getFocusedRect(Rect r) {
6324        getDrawingRect(r);
6325    }
6326
6327    /**
6328     * If some part of this view is not clipped by any of its parents, then
6329     * return that area in r in global (root) coordinates. To convert r to local
6330     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
6331     * -globalOffset.y)) If the view is completely clipped or translated out,
6332     * return false.
6333     *
6334     * @param r If true is returned, r holds the global coordinates of the
6335     *        visible portion of this view.
6336     * @param globalOffset If true is returned, globalOffset holds the dx,dy
6337     *        between this view and its root. globalOffet may be null.
6338     * @return true if r is non-empty (i.e. part of the view is visible at the
6339     *         root level.
6340     */
6341    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
6342        int width = mRight - mLeft;
6343        int height = mBottom - mTop;
6344        if (width > 0 && height > 0) {
6345            r.set(0, 0, width, height);
6346            if (globalOffset != null) {
6347                globalOffset.set(-mScrollX, -mScrollY);
6348            }
6349            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
6350        }
6351        return false;
6352    }
6353
6354    public final boolean getGlobalVisibleRect(Rect r) {
6355        return getGlobalVisibleRect(r, null);
6356    }
6357
6358    public final boolean getLocalVisibleRect(Rect r) {
6359        Point offset = new Point();
6360        if (getGlobalVisibleRect(r, offset)) {
6361            r.offset(-offset.x, -offset.y); // make r local
6362            return true;
6363        }
6364        return false;
6365    }
6366
6367    /**
6368     * Offset this view's vertical location by the specified number of pixels.
6369     *
6370     * @param offset the number of pixels to offset the view by
6371     */
6372    public void offsetTopAndBottom(int offset) {
6373        if (offset != 0) {
6374            updateMatrix();
6375            if (mMatrixIsIdentity) {
6376                final ViewParent p = mParent;
6377                if (p != null && mAttachInfo != null) {
6378                    final Rect r = mAttachInfo.mTmpInvalRect;
6379                    int minTop;
6380                    int maxBottom;
6381                    int yLoc;
6382                    if (offset < 0) {
6383                        minTop = mTop + offset;
6384                        maxBottom = mBottom;
6385                        yLoc = offset;
6386                    } else {
6387                        minTop = mTop;
6388                        maxBottom = mBottom + offset;
6389                        yLoc = 0;
6390                    }
6391                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
6392                    p.invalidateChild(this, r);
6393                }
6394            } else {
6395                invalidate(false);
6396            }
6397
6398            mTop += offset;
6399            mBottom += offset;
6400
6401            if (!mMatrixIsIdentity) {
6402                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6403                invalidate(false);
6404            }
6405        }
6406    }
6407
6408    /**
6409     * Offset this view's horizontal location by the specified amount of pixels.
6410     *
6411     * @param offset the numer of pixels to offset the view by
6412     */
6413    public void offsetLeftAndRight(int offset) {
6414        if (offset != 0) {
6415            updateMatrix();
6416            if (mMatrixIsIdentity) {
6417                final ViewParent p = mParent;
6418                if (p != null && mAttachInfo != null) {
6419                    final Rect r = mAttachInfo.mTmpInvalRect;
6420                    int minLeft;
6421                    int maxRight;
6422                    if (offset < 0) {
6423                        minLeft = mLeft + offset;
6424                        maxRight = mRight;
6425                    } else {
6426                        minLeft = mLeft;
6427                        maxRight = mRight + offset;
6428                    }
6429                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
6430                    p.invalidateChild(this, r);
6431                }
6432            } else {
6433                invalidate(false);
6434            }
6435
6436            mLeft += offset;
6437            mRight += offset;
6438
6439            if (!mMatrixIsIdentity) {
6440                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6441                invalidate(false);
6442            }
6443        }
6444    }
6445
6446    /**
6447     * Get the LayoutParams associated with this view. All views should have
6448     * layout parameters. These supply parameters to the <i>parent</i> of this
6449     * view specifying how it should be arranged. There are many subclasses of
6450     * ViewGroup.LayoutParams, and these correspond to the different subclasses
6451     * of ViewGroup that are responsible for arranging their children.
6452     * @return The LayoutParams associated with this view
6453     */
6454    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
6455    public ViewGroup.LayoutParams getLayoutParams() {
6456        return mLayoutParams;
6457    }
6458
6459    /**
6460     * Set the layout parameters associated with this view. These supply
6461     * parameters to the <i>parent</i> of this view specifying how it should be
6462     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
6463     * correspond to the different subclasses of ViewGroup that are responsible
6464     * for arranging their children.
6465     *
6466     * @param params the layout parameters for this view
6467     */
6468    public void setLayoutParams(ViewGroup.LayoutParams params) {
6469        if (params == null) {
6470            throw new NullPointerException("params == null");
6471        }
6472        mLayoutParams = params;
6473        requestLayout();
6474    }
6475
6476    /**
6477     * Set the scrolled position of your view. This will cause a call to
6478     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6479     * invalidated.
6480     * @param x the x position to scroll to
6481     * @param y the y position to scroll to
6482     */
6483    public void scrollTo(int x, int y) {
6484        if (mScrollX != x || mScrollY != y) {
6485            int oldX = mScrollX;
6486            int oldY = mScrollY;
6487            mScrollX = x;
6488            mScrollY = y;
6489            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
6490            if (!awakenScrollBars()) {
6491                invalidate();
6492            }
6493        }
6494    }
6495
6496    /**
6497     * Move the scrolled position of your view. This will cause a call to
6498     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6499     * invalidated.
6500     * @param x the amount of pixels to scroll by horizontally
6501     * @param y the amount of pixels to scroll by vertically
6502     */
6503    public void scrollBy(int x, int y) {
6504        scrollTo(mScrollX + x, mScrollY + y);
6505    }
6506
6507    /**
6508     * <p>Trigger the scrollbars to draw. When invoked this method starts an
6509     * animation to fade the scrollbars out after a default delay. If a subclass
6510     * provides animated scrolling, the start delay should equal the duration
6511     * of the scrolling animation.</p>
6512     *
6513     * <p>The animation starts only if at least one of the scrollbars is
6514     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
6515     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6516     * this method returns true, and false otherwise. If the animation is
6517     * started, this method calls {@link #invalidate()}; in that case the
6518     * caller should not call {@link #invalidate()}.</p>
6519     *
6520     * <p>This method should be invoked every time a subclass directly updates
6521     * the scroll parameters.</p>
6522     *
6523     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
6524     * and {@link #scrollTo(int, int)}.</p>
6525     *
6526     * @return true if the animation is played, false otherwise
6527     *
6528     * @see #awakenScrollBars(int)
6529     * @see #scrollBy(int, int)
6530     * @see #scrollTo(int, int)
6531     * @see #isHorizontalScrollBarEnabled()
6532     * @see #isVerticalScrollBarEnabled()
6533     * @see #setHorizontalScrollBarEnabled(boolean)
6534     * @see #setVerticalScrollBarEnabled(boolean)
6535     */
6536    protected boolean awakenScrollBars() {
6537        return mScrollCache != null &&
6538                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
6539    }
6540
6541    /**
6542     * Trigger the scrollbars to draw.
6543     * This method differs from awakenScrollBars() only in its default duration.
6544     * initialAwakenScrollBars() will show the scroll bars for longer than
6545     * usual to give the user more of a chance to notice them.
6546     *
6547     * @return true if the animation is played, false otherwise.
6548     */
6549    private boolean initialAwakenScrollBars() {
6550        return mScrollCache != null &&
6551                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
6552    }
6553
6554    /**
6555     * <p>
6556     * Trigger the scrollbars to draw. When invoked this method starts an
6557     * animation to fade the scrollbars out after a fixed delay. If a subclass
6558     * provides animated scrolling, the start delay should equal the duration of
6559     * the scrolling animation.
6560     * </p>
6561     *
6562     * <p>
6563     * The animation starts only if at least one of the scrollbars is enabled,
6564     * as specified by {@link #isHorizontalScrollBarEnabled()} and
6565     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6566     * this method returns true, and false otherwise. If the animation is
6567     * started, this method calls {@link #invalidate()}; in that case the caller
6568     * should not call {@link #invalidate()}.
6569     * </p>
6570     *
6571     * <p>
6572     * This method should be invoked everytime a subclass directly updates the
6573     * scroll parameters.
6574     * </p>
6575     *
6576     * @param startDelay the delay, in milliseconds, after which the animation
6577     *        should start; when the delay is 0, the animation starts
6578     *        immediately
6579     * @return true if the animation is played, false otherwise
6580     *
6581     * @see #scrollBy(int, int)
6582     * @see #scrollTo(int, int)
6583     * @see #isHorizontalScrollBarEnabled()
6584     * @see #isVerticalScrollBarEnabled()
6585     * @see #setHorizontalScrollBarEnabled(boolean)
6586     * @see #setVerticalScrollBarEnabled(boolean)
6587     */
6588    protected boolean awakenScrollBars(int startDelay) {
6589        return awakenScrollBars(startDelay, true);
6590    }
6591
6592    /**
6593     * <p>
6594     * Trigger the scrollbars to draw. When invoked this method starts an
6595     * animation to fade the scrollbars out after a fixed delay. If a subclass
6596     * provides animated scrolling, the start delay should equal the duration of
6597     * the scrolling animation.
6598     * </p>
6599     *
6600     * <p>
6601     * The animation starts only if at least one of the scrollbars is enabled,
6602     * as specified by {@link #isHorizontalScrollBarEnabled()} and
6603     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
6604     * this method returns true, and false otherwise. If the animation is
6605     * started, this method calls {@link #invalidate()} if the invalidate parameter
6606     * is set to true; in that case the caller
6607     * should not call {@link #invalidate()}.
6608     * </p>
6609     *
6610     * <p>
6611     * This method should be invoked everytime a subclass directly updates the
6612     * scroll parameters.
6613     * </p>
6614     *
6615     * @param startDelay the delay, in milliseconds, after which the animation
6616     *        should start; when the delay is 0, the animation starts
6617     *        immediately
6618     *
6619     * @param invalidate Wheter this method should call invalidate
6620     *
6621     * @return true if the animation is played, false otherwise
6622     *
6623     * @see #scrollBy(int, int)
6624     * @see #scrollTo(int, int)
6625     * @see #isHorizontalScrollBarEnabled()
6626     * @see #isVerticalScrollBarEnabled()
6627     * @see #setHorizontalScrollBarEnabled(boolean)
6628     * @see #setVerticalScrollBarEnabled(boolean)
6629     */
6630    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
6631        final ScrollabilityCache scrollCache = mScrollCache;
6632
6633        if (scrollCache == null || !scrollCache.fadeScrollBars) {
6634            return false;
6635        }
6636
6637        if (scrollCache.scrollBar == null) {
6638            scrollCache.scrollBar = new ScrollBarDrawable();
6639        }
6640
6641        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
6642
6643            if (invalidate) {
6644                // Invalidate to show the scrollbars
6645                invalidate();
6646            }
6647
6648            if (scrollCache.state == ScrollabilityCache.OFF) {
6649                // FIXME: this is copied from WindowManagerService.
6650                // We should get this value from the system when it
6651                // is possible to do so.
6652                final int KEY_REPEAT_FIRST_DELAY = 750;
6653                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
6654            }
6655
6656            // Tell mScrollCache when we should start fading. This may
6657            // extend the fade start time if one was already scheduled
6658            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
6659            scrollCache.fadeStartTime = fadeStartTime;
6660            scrollCache.state = ScrollabilityCache.ON;
6661
6662            // Schedule our fader to run, unscheduling any old ones first
6663            if (mAttachInfo != null) {
6664                mAttachInfo.mHandler.removeCallbacks(scrollCache);
6665                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
6666            }
6667
6668            return true;
6669        }
6670
6671        return false;
6672    }
6673
6674    /**
6675     * Mark the the area defined by dirty as needing to be drawn. If the view is
6676     * visible, {@link #onDraw} will be called at some point in the future.
6677     * This must be called from a UI thread. To call from a non-UI thread, call
6678     * {@link #postInvalidate()}.
6679     *
6680     * WARNING: This method is destructive to dirty.
6681     * @param dirty the rectangle representing the bounds of the dirty region
6682     */
6683    public void invalidate(Rect dirty) {
6684        if (ViewDebug.TRACE_HIERARCHY) {
6685            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6686        }
6687
6688        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6689                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
6690            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6691            final ViewParent p = mParent;
6692            final AttachInfo ai = mAttachInfo;
6693            if (p != null && ai != null && ai.mHardwareAccelerated) {
6694                // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6695                // with a null dirty rect, which tells the ViewRoot to redraw everything
6696                p.invalidateChild(this, null);
6697                return;
6698            }
6699            if (p != null && ai != null) {
6700                final int scrollX = mScrollX;
6701                final int scrollY = mScrollY;
6702                final Rect r = ai.mTmpInvalRect;
6703                r.set(dirty.left - scrollX, dirty.top - scrollY,
6704                        dirty.right - scrollX, dirty.bottom - scrollY);
6705                mParent.invalidateChild(this, r);
6706            }
6707        }
6708    }
6709
6710    /**
6711     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6712     * The coordinates of the dirty rect are relative to the view.
6713     * If the view is visible, {@link #onDraw} will be called at some point
6714     * in the future. This must be called from a UI thread. To call
6715     * from a non-UI thread, call {@link #postInvalidate()}.
6716     * @param l the left position of the dirty region
6717     * @param t the top position of the dirty region
6718     * @param r the right position of the dirty region
6719     * @param b the bottom position of the dirty region
6720     */
6721    public void invalidate(int l, int t, int r, int b) {
6722        if (ViewDebug.TRACE_HIERARCHY) {
6723            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6724        }
6725
6726        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6727                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
6728            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6729            final ViewParent p = mParent;
6730            final AttachInfo ai = mAttachInfo;
6731            if (p != null && ai != null && ai.mHardwareAccelerated) {
6732                // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6733                // with a null dirty rect, which tells the ViewRoot to redraw everything
6734                p.invalidateChild(this, null);
6735                return;
6736            }
6737            if (p != null && ai != null && l < r && t < b) {
6738                final int scrollX = mScrollX;
6739                final int scrollY = mScrollY;
6740                final Rect tmpr = ai.mTmpInvalRect;
6741                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6742                p.invalidateChild(this, tmpr);
6743            }
6744        }
6745    }
6746
6747    /**
6748     * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6749     * be called at some point in the future. This must be called from a
6750     * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6751     */
6752    public void invalidate() {
6753        invalidate(true);
6754    }
6755
6756    /**
6757     * This is where the invalidate() work actually happens. A full invalidate()
6758     * causes the drawing cache to be invalidated, but this function can be called with
6759     * invalidateCache set to false to skip that invalidation step for cases that do not
6760     * need it (for example, a component that remains at the same dimensions with the same
6761     * content).
6762     *
6763     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6764     * well. This is usually true for a full invalidate, but may be set to false if the
6765     * View's contents or dimensions have not changed.
6766     */
6767    private void invalidate(boolean invalidateCache) {
6768        if (ViewDebug.TRACE_HIERARCHY) {
6769            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6770        }
6771
6772        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6773                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID)) {
6774            mPrivateFlags &= ~DRAWN;
6775            if (invalidateCache) {
6776                mPrivateFlags &= ~DRAWING_CACHE_VALID;
6777            }
6778            final AttachInfo ai = mAttachInfo;
6779            final ViewParent p = mParent;
6780            if (p != null && ai != null && ai.mHardwareAccelerated) {
6781                // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6782                // with a null dirty rect, which tells the ViewRoot to redraw everything
6783                p.invalidateChild(this, null);
6784                return;
6785            }
6786
6787            if (p != null && ai != null) {
6788                final Rect r = ai.mTmpInvalRect;
6789                r.set(0, 0, mRight - mLeft, mBottom - mTop);
6790                // Don't call invalidate -- we don't want to internally scroll
6791                // our own bounds
6792                p.invalidateChild(this, r);
6793            }
6794        }
6795    }
6796
6797    /**
6798     * Indicates whether this View is opaque. An opaque View guarantees that it will
6799     * draw all the pixels overlapping its bounds using a fully opaque color.
6800     *
6801     * Subclasses of View should override this method whenever possible to indicate
6802     * whether an instance is opaque. Opaque Views are treated in a special way by
6803     * the View hierarchy, possibly allowing it to perform optimizations during
6804     * invalidate/draw passes.
6805     *
6806     * @return True if this View is guaranteed to be fully opaque, false otherwise.
6807     */
6808    @ViewDebug.ExportedProperty(category = "drawing")
6809    public boolean isOpaque() {
6810        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6811                (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
6812    }
6813
6814    /**
6815     * @hide
6816     */
6817    protected void computeOpaqueFlags() {
6818        // Opaque if:
6819        //   - Has a background
6820        //   - Background is opaque
6821        //   - Doesn't have scrollbars or scrollbars are inside overlay
6822
6823        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6824            mPrivateFlags |= OPAQUE_BACKGROUND;
6825        } else {
6826            mPrivateFlags &= ~OPAQUE_BACKGROUND;
6827        }
6828
6829        final int flags = mViewFlags;
6830        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6831                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6832            mPrivateFlags |= OPAQUE_SCROLLBARS;
6833        } else {
6834            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6835        }
6836    }
6837
6838    /**
6839     * @hide
6840     */
6841    protected boolean hasOpaqueScrollbars() {
6842        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
6843    }
6844
6845    /**
6846     * @return A handler associated with the thread running the View. This
6847     * handler can be used to pump events in the UI events queue.
6848     */
6849    public Handler getHandler() {
6850        if (mAttachInfo != null) {
6851            return mAttachInfo.mHandler;
6852        }
6853        return null;
6854    }
6855
6856    /**
6857     * Causes the Runnable to be added to the message queue.
6858     * The runnable will be run on the user interface thread.
6859     *
6860     * @param action The Runnable that will be executed.
6861     *
6862     * @return Returns true if the Runnable was successfully placed in to the
6863     *         message queue.  Returns false on failure, usually because the
6864     *         looper processing the message queue is exiting.
6865     */
6866    public boolean post(Runnable action) {
6867        Handler handler;
6868        if (mAttachInfo != null) {
6869            handler = mAttachInfo.mHandler;
6870        } else {
6871            // Assume that post will succeed later
6872            ViewRoot.getRunQueue().post(action);
6873            return true;
6874        }
6875
6876        return handler.post(action);
6877    }
6878
6879    /**
6880     * Causes the Runnable to be added to the message queue, to be run
6881     * after the specified amount of time elapses.
6882     * The runnable will be run on the user interface thread.
6883     *
6884     * @param action The Runnable that will be executed.
6885     * @param delayMillis The delay (in milliseconds) until the Runnable
6886     *        will be executed.
6887     *
6888     * @return true if the Runnable was successfully placed in to the
6889     *         message queue.  Returns false on failure, usually because the
6890     *         looper processing the message queue is exiting.  Note that a
6891     *         result of true does not mean the Runnable will be processed --
6892     *         if the looper is quit before the delivery time of the message
6893     *         occurs then the message will be dropped.
6894     */
6895    public boolean postDelayed(Runnable action, long delayMillis) {
6896        Handler handler;
6897        if (mAttachInfo != null) {
6898            handler = mAttachInfo.mHandler;
6899        } else {
6900            // Assume that post will succeed later
6901            ViewRoot.getRunQueue().postDelayed(action, delayMillis);
6902            return true;
6903        }
6904
6905        return handler.postDelayed(action, delayMillis);
6906    }
6907
6908    /**
6909     * Removes the specified Runnable from the message queue.
6910     *
6911     * @param action The Runnable to remove from the message handling queue
6912     *
6913     * @return true if this view could ask the Handler to remove the Runnable,
6914     *         false otherwise. When the returned value is true, the Runnable
6915     *         may or may not have been actually removed from the message queue
6916     *         (for instance, if the Runnable was not in the queue already.)
6917     */
6918    public boolean removeCallbacks(Runnable action) {
6919        Handler handler;
6920        if (mAttachInfo != null) {
6921            handler = mAttachInfo.mHandler;
6922        } else {
6923            // Assume that post will succeed later
6924            ViewRoot.getRunQueue().removeCallbacks(action);
6925            return true;
6926        }
6927
6928        handler.removeCallbacks(action);
6929        return true;
6930    }
6931
6932    /**
6933     * Cause an invalidate to happen on a subsequent cycle through the event loop.
6934     * Use this to invalidate the View from a non-UI thread.
6935     *
6936     * @see #invalidate()
6937     */
6938    public void postInvalidate() {
6939        postInvalidateDelayed(0);
6940    }
6941
6942    /**
6943     * Cause an invalidate of the specified area to happen on a subsequent cycle
6944     * through the event loop. Use this to invalidate the View from a non-UI thread.
6945     *
6946     * @param left The left coordinate of the rectangle to invalidate.
6947     * @param top The top coordinate of the rectangle to invalidate.
6948     * @param right The right coordinate of the rectangle to invalidate.
6949     * @param bottom The bottom coordinate of the rectangle to invalidate.
6950     *
6951     * @see #invalidate(int, int, int, int)
6952     * @see #invalidate(Rect)
6953     */
6954    public void postInvalidate(int left, int top, int right, int bottom) {
6955        postInvalidateDelayed(0, left, top, right, bottom);
6956    }
6957
6958    /**
6959     * Cause an invalidate to happen on a subsequent cycle through the event
6960     * loop. Waits for the specified amount of time.
6961     *
6962     * @param delayMilliseconds the duration in milliseconds to delay the
6963     *         invalidation by
6964     */
6965    public void postInvalidateDelayed(long delayMilliseconds) {
6966        // We try only with the AttachInfo because there's no point in invalidating
6967        // if we are not attached to our window
6968        if (mAttachInfo != null) {
6969            Message msg = Message.obtain();
6970            msg.what = AttachInfo.INVALIDATE_MSG;
6971            msg.obj = this;
6972            mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
6973        }
6974    }
6975
6976    /**
6977     * Cause an invalidate of the specified area to happen on a subsequent cycle
6978     * through the event loop. Waits for the specified amount of time.
6979     *
6980     * @param delayMilliseconds the duration in milliseconds to delay the
6981     *         invalidation by
6982     * @param left The left coordinate of the rectangle to invalidate.
6983     * @param top The top coordinate of the rectangle to invalidate.
6984     * @param right The right coordinate of the rectangle to invalidate.
6985     * @param bottom The bottom coordinate of the rectangle to invalidate.
6986     */
6987    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
6988            int right, int bottom) {
6989
6990        // We try only with the AttachInfo because there's no point in invalidating
6991        // if we are not attached to our window
6992        if (mAttachInfo != null) {
6993            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
6994            info.target = this;
6995            info.left = left;
6996            info.top = top;
6997            info.right = right;
6998            info.bottom = bottom;
6999
7000            final Message msg = Message.obtain();
7001            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
7002            msg.obj = info;
7003            mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7004        }
7005    }
7006
7007    /**
7008     * Called by a parent to request that a child update its values for mScrollX
7009     * and mScrollY if necessary. This will typically be done if the child is
7010     * animating a scroll using a {@link android.widget.Scroller Scroller}
7011     * object.
7012     */
7013    public void computeScroll() {
7014    }
7015
7016    /**
7017     * <p>Indicate whether the horizontal edges are faded when the view is
7018     * scrolled horizontally.</p>
7019     *
7020     * @return true if the horizontal edges should are faded on scroll, false
7021     *         otherwise
7022     *
7023     * @see #setHorizontalFadingEdgeEnabled(boolean)
7024     * @attr ref android.R.styleable#View_fadingEdge
7025     */
7026    public boolean isHorizontalFadingEdgeEnabled() {
7027        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
7028    }
7029
7030    /**
7031     * <p>Define whether the horizontal edges should be faded when this view
7032     * is scrolled horizontally.</p>
7033     *
7034     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
7035     *                                    be faded when the view is scrolled
7036     *                                    horizontally
7037     *
7038     * @see #isHorizontalFadingEdgeEnabled()
7039     * @attr ref android.R.styleable#View_fadingEdge
7040     */
7041    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7042        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7043            if (horizontalFadingEdgeEnabled) {
7044                initScrollCache();
7045            }
7046
7047            mViewFlags ^= FADING_EDGE_HORIZONTAL;
7048        }
7049    }
7050
7051    /**
7052     * <p>Indicate whether the vertical edges are faded when the view is
7053     * scrolled horizontally.</p>
7054     *
7055     * @return true if the vertical edges should are faded on scroll, false
7056     *         otherwise
7057     *
7058     * @see #setVerticalFadingEdgeEnabled(boolean)
7059     * @attr ref android.R.styleable#View_fadingEdge
7060     */
7061    public boolean isVerticalFadingEdgeEnabled() {
7062        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7063    }
7064
7065    /**
7066     * <p>Define whether the vertical edges should be faded when this view
7067     * is scrolled vertically.</p>
7068     *
7069     * @param verticalFadingEdgeEnabled true if the vertical edges should
7070     *                                  be faded when the view is scrolled
7071     *                                  vertically
7072     *
7073     * @see #isVerticalFadingEdgeEnabled()
7074     * @attr ref android.R.styleable#View_fadingEdge
7075     */
7076    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7077        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7078            if (verticalFadingEdgeEnabled) {
7079                initScrollCache();
7080            }
7081
7082            mViewFlags ^= FADING_EDGE_VERTICAL;
7083        }
7084    }
7085
7086    /**
7087     * Returns the strength, or intensity, of the top faded edge. The strength is
7088     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7089     * returns 0.0 or 1.0 but no value in between.
7090     *
7091     * Subclasses should override this method to provide a smoother fade transition
7092     * when scrolling occurs.
7093     *
7094     * @return the intensity of the top fade as a float between 0.0f and 1.0f
7095     */
7096    protected float getTopFadingEdgeStrength() {
7097        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7098    }
7099
7100    /**
7101     * Returns the strength, or intensity, of the bottom faded edge. The strength is
7102     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7103     * returns 0.0 or 1.0 but no value in between.
7104     *
7105     * Subclasses should override this method to provide a smoother fade transition
7106     * when scrolling occurs.
7107     *
7108     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7109     */
7110    protected float getBottomFadingEdgeStrength() {
7111        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7112                computeVerticalScrollRange() ? 1.0f : 0.0f;
7113    }
7114
7115    /**
7116     * Returns the strength, or intensity, of the left faded edge. The strength is
7117     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7118     * returns 0.0 or 1.0 but no value in between.
7119     *
7120     * Subclasses should override this method to provide a smoother fade transition
7121     * when scrolling occurs.
7122     *
7123     * @return the intensity of the left fade as a float between 0.0f and 1.0f
7124     */
7125    protected float getLeftFadingEdgeStrength() {
7126        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7127    }
7128
7129    /**
7130     * Returns the strength, or intensity, of the right faded edge. The strength is
7131     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7132     * returns 0.0 or 1.0 but no value in between.
7133     *
7134     * Subclasses should override this method to provide a smoother fade transition
7135     * when scrolling occurs.
7136     *
7137     * @return the intensity of the right fade as a float between 0.0f and 1.0f
7138     */
7139    protected float getRightFadingEdgeStrength() {
7140        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7141                computeHorizontalScrollRange() ? 1.0f : 0.0f;
7142    }
7143
7144    /**
7145     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7146     * scrollbar is not drawn by default.</p>
7147     *
7148     * @return true if the horizontal scrollbar should be painted, false
7149     *         otherwise
7150     *
7151     * @see #setHorizontalScrollBarEnabled(boolean)
7152     */
7153    public boolean isHorizontalScrollBarEnabled() {
7154        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7155    }
7156
7157    /**
7158     * <p>Define whether the horizontal scrollbar should be drawn or not. The
7159     * scrollbar is not drawn by default.</p>
7160     *
7161     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7162     *                                   be painted
7163     *
7164     * @see #isHorizontalScrollBarEnabled()
7165     */
7166    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7167        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7168            mViewFlags ^= SCROLLBARS_HORIZONTAL;
7169            computeOpaqueFlags();
7170            recomputePadding();
7171        }
7172    }
7173
7174    /**
7175     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7176     * scrollbar is not drawn by default.</p>
7177     *
7178     * @return true if the vertical scrollbar should be painted, false
7179     *         otherwise
7180     *
7181     * @see #setVerticalScrollBarEnabled(boolean)
7182     */
7183    public boolean isVerticalScrollBarEnabled() {
7184        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7185    }
7186
7187    /**
7188     * <p>Define whether the vertical scrollbar should be drawn or not. The
7189     * scrollbar is not drawn by default.</p>
7190     *
7191     * @param verticalScrollBarEnabled true if the vertical scrollbar should
7192     *                                 be painted
7193     *
7194     * @see #isVerticalScrollBarEnabled()
7195     */
7196    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7197        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7198            mViewFlags ^= SCROLLBARS_VERTICAL;
7199            computeOpaqueFlags();
7200            recomputePadding();
7201        }
7202    }
7203
7204    /**
7205     * @hide
7206     */
7207    protected void recomputePadding() {
7208        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
7209    }
7210
7211    /**
7212     * Define whether scrollbars will fade when the view is not scrolling.
7213     *
7214     * @param fadeScrollbars wheter to enable fading
7215     *
7216     */
7217    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7218        initScrollCache();
7219        final ScrollabilityCache scrollabilityCache = mScrollCache;
7220        scrollabilityCache.fadeScrollBars = fadeScrollbars;
7221        if (fadeScrollbars) {
7222            scrollabilityCache.state = ScrollabilityCache.OFF;
7223        } else {
7224            scrollabilityCache.state = ScrollabilityCache.ON;
7225        }
7226    }
7227
7228    /**
7229     *
7230     * Returns true if scrollbars will fade when this view is not scrolling
7231     *
7232     * @return true if scrollbar fading is enabled
7233     */
7234    public boolean isScrollbarFadingEnabled() {
7235        return mScrollCache != null && mScrollCache.fadeScrollBars;
7236    }
7237
7238    /**
7239     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7240     * inset. When inset, they add to the padding of the view. And the scrollbars
7241     * can be drawn inside the padding area or on the edge of the view. For example,
7242     * if a view has a background drawable and you want to draw the scrollbars
7243     * inside the padding specified by the drawable, you can use
7244     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7245     * appear at the edge of the view, ignoring the padding, then you can use
7246     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7247     * @param style the style of the scrollbars. Should be one of
7248     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7249     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7250     * @see #SCROLLBARS_INSIDE_OVERLAY
7251     * @see #SCROLLBARS_INSIDE_INSET
7252     * @see #SCROLLBARS_OUTSIDE_OVERLAY
7253     * @see #SCROLLBARS_OUTSIDE_INSET
7254     */
7255    public void setScrollBarStyle(int style) {
7256        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7257            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
7258            computeOpaqueFlags();
7259            recomputePadding();
7260        }
7261    }
7262
7263    /**
7264     * <p>Returns the current scrollbar style.</p>
7265     * @return the current scrollbar style
7266     * @see #SCROLLBARS_INSIDE_OVERLAY
7267     * @see #SCROLLBARS_INSIDE_INSET
7268     * @see #SCROLLBARS_OUTSIDE_OVERLAY
7269     * @see #SCROLLBARS_OUTSIDE_INSET
7270     */
7271    public int getScrollBarStyle() {
7272        return mViewFlags & SCROLLBARS_STYLE_MASK;
7273    }
7274
7275    /**
7276     * <p>Compute the horizontal range that the horizontal scrollbar
7277     * represents.</p>
7278     *
7279     * <p>The range is expressed in arbitrary units that must be the same as the
7280     * units used by {@link #computeHorizontalScrollExtent()} and
7281     * {@link #computeHorizontalScrollOffset()}.</p>
7282     *
7283     * <p>The default range is the drawing width of this view.</p>
7284     *
7285     * @return the total horizontal range represented by the horizontal
7286     *         scrollbar
7287     *
7288     * @see #computeHorizontalScrollExtent()
7289     * @see #computeHorizontalScrollOffset()
7290     * @see android.widget.ScrollBarDrawable
7291     */
7292    protected int computeHorizontalScrollRange() {
7293        return getWidth();
7294    }
7295
7296    /**
7297     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7298     * within the horizontal range. This value is used to compute the position
7299     * of the thumb within the scrollbar's track.</p>
7300     *
7301     * <p>The range is expressed in arbitrary units that must be the same as the
7302     * units used by {@link #computeHorizontalScrollRange()} and
7303     * {@link #computeHorizontalScrollExtent()}.</p>
7304     *
7305     * <p>The default offset is the scroll offset of this view.</p>
7306     *
7307     * @return the horizontal offset of the scrollbar's thumb
7308     *
7309     * @see #computeHorizontalScrollRange()
7310     * @see #computeHorizontalScrollExtent()
7311     * @see android.widget.ScrollBarDrawable
7312     */
7313    protected int computeHorizontalScrollOffset() {
7314        return mScrollX;
7315    }
7316
7317    /**
7318     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7319     * within the horizontal range. This value is used to compute the length
7320     * of the thumb within the scrollbar's track.</p>
7321     *
7322     * <p>The range is expressed in arbitrary units that must be the same as the
7323     * units used by {@link #computeHorizontalScrollRange()} and
7324     * {@link #computeHorizontalScrollOffset()}.</p>
7325     *
7326     * <p>The default extent is the drawing width of this view.</p>
7327     *
7328     * @return the horizontal extent of the scrollbar's thumb
7329     *
7330     * @see #computeHorizontalScrollRange()
7331     * @see #computeHorizontalScrollOffset()
7332     * @see android.widget.ScrollBarDrawable
7333     */
7334    protected int computeHorizontalScrollExtent() {
7335        return getWidth();
7336    }
7337
7338    /**
7339     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7340     *
7341     * <p>The range is expressed in arbitrary units that must be the same as the
7342     * units used by {@link #computeVerticalScrollExtent()} and
7343     * {@link #computeVerticalScrollOffset()}.</p>
7344     *
7345     * @return the total vertical range represented by the vertical scrollbar
7346     *
7347     * <p>The default range is the drawing height of this view.</p>
7348     *
7349     * @see #computeVerticalScrollExtent()
7350     * @see #computeVerticalScrollOffset()
7351     * @see android.widget.ScrollBarDrawable
7352     */
7353    protected int computeVerticalScrollRange() {
7354        return getHeight();
7355    }
7356
7357    /**
7358     * <p>Compute the vertical offset of the vertical scrollbar's thumb
7359     * within the horizontal range. This value is used to compute the position
7360     * of the thumb within the scrollbar's track.</p>
7361     *
7362     * <p>The range is expressed in arbitrary units that must be the same as the
7363     * units used by {@link #computeVerticalScrollRange()} and
7364     * {@link #computeVerticalScrollExtent()}.</p>
7365     *
7366     * <p>The default offset is the scroll offset of this view.</p>
7367     *
7368     * @return the vertical offset of the scrollbar's thumb
7369     *
7370     * @see #computeVerticalScrollRange()
7371     * @see #computeVerticalScrollExtent()
7372     * @see android.widget.ScrollBarDrawable
7373     */
7374    protected int computeVerticalScrollOffset() {
7375        return mScrollY;
7376    }
7377
7378    /**
7379     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7380     * within the vertical range. This value is used to compute the length
7381     * of the thumb within the scrollbar's track.</p>
7382     *
7383     * <p>The range is expressed in arbitrary units that must be the same as the
7384     * units used by {@link #computeVerticalScrollRange()} and
7385     * {@link #computeVerticalScrollOffset()}.</p>
7386     *
7387     * <p>The default extent is the drawing height of this view.</p>
7388     *
7389     * @return the vertical extent of the scrollbar's thumb
7390     *
7391     * @see #computeVerticalScrollRange()
7392     * @see #computeVerticalScrollOffset()
7393     * @see android.widget.ScrollBarDrawable
7394     */
7395    protected int computeVerticalScrollExtent() {
7396        return getHeight();
7397    }
7398
7399    /**
7400     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7401     * scrollbars are painted only if they have been awakened first.</p>
7402     *
7403     * @param canvas the canvas on which to draw the scrollbars
7404     *
7405     * @see #awakenScrollBars(int)
7406     */
7407    protected final void onDrawScrollBars(Canvas canvas) {
7408        // scrollbars are drawn only when the animation is running
7409        final ScrollabilityCache cache = mScrollCache;
7410        if (cache != null) {
7411
7412            int state = cache.state;
7413
7414            if (state == ScrollabilityCache.OFF) {
7415                return;
7416            }
7417
7418            boolean invalidate = false;
7419
7420            if (state == ScrollabilityCache.FADING) {
7421                // We're fading -- get our fade interpolation
7422                if (cache.interpolatorValues == null) {
7423                    cache.interpolatorValues = new float[1];
7424                }
7425
7426                float[] values = cache.interpolatorValues;
7427
7428                // Stops the animation if we're done
7429                if (cache.scrollBarInterpolator.timeToValues(values) ==
7430                        Interpolator.Result.FREEZE_END) {
7431                    cache.state = ScrollabilityCache.OFF;
7432                } else {
7433                    cache.scrollBar.setAlpha(Math.round(values[0]));
7434                }
7435
7436                // This will make the scroll bars inval themselves after
7437                // drawing. We only want this when we're fading so that
7438                // we prevent excessive redraws
7439                invalidate = true;
7440            } else {
7441                // We're just on -- but we may have been fading before so
7442                // reset alpha
7443                cache.scrollBar.setAlpha(255);
7444            }
7445
7446
7447            final int viewFlags = mViewFlags;
7448
7449            final boolean drawHorizontalScrollBar =
7450                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7451            final boolean drawVerticalScrollBar =
7452                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7453                && !isVerticalScrollBarHidden();
7454
7455            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7456                final int width = mRight - mLeft;
7457                final int height = mBottom - mTop;
7458
7459                final ScrollBarDrawable scrollBar = cache.scrollBar;
7460                int size = scrollBar.getSize(false);
7461                if (size <= 0) {
7462                    size = cache.scrollBarSize;
7463                }
7464
7465                final int scrollX = mScrollX;
7466                final int scrollY = mScrollY;
7467                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7468
7469                int left, top, right, bottom;
7470
7471                if (drawHorizontalScrollBar) {
7472                    scrollBar.setParameters(computeHorizontalScrollRange(),
7473                                            computeHorizontalScrollOffset(),
7474                                            computeHorizontalScrollExtent(), false);
7475                    final int verticalScrollBarGap = drawVerticalScrollBar ?
7476                            getVerticalScrollbarWidth() : 0;
7477                    top = scrollY + height - size - (mUserPaddingBottom & inside);
7478                    left = scrollX + (mPaddingLeft & inside);
7479                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7480                    bottom = top + size;
7481                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7482                    if (invalidate) {
7483                        invalidate(left, top, right, bottom);
7484                    }
7485                }
7486
7487                if (drawVerticalScrollBar) {
7488                    scrollBar.setParameters(computeVerticalScrollRange(),
7489                                            computeVerticalScrollOffset(),
7490                                            computeVerticalScrollExtent(), true);
7491                    switch (mVerticalScrollbarPosition) {
7492                        default:
7493                        case SCROLLBAR_POSITION_DEFAULT:
7494                        case SCROLLBAR_POSITION_RIGHT:
7495                            left = scrollX + width - size - (mUserPaddingRight & inside);
7496                            break;
7497                        case SCROLLBAR_POSITION_LEFT:
7498                            left = scrollX + (mUserPaddingLeft & inside);
7499                            break;
7500                    }
7501                    top = scrollY + (mPaddingTop & inside);
7502                    right = left + size;
7503                    bottom = scrollY + height - (mUserPaddingBottom & inside);
7504                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7505                    if (invalidate) {
7506                        invalidate(left, top, right, bottom);
7507                    }
7508                }
7509            }
7510        }
7511    }
7512
7513    /**
7514     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
7515     * FastScroller is visible.
7516     * @return whether to temporarily hide the vertical scrollbar
7517     * @hide
7518     */
7519    protected boolean isVerticalScrollBarHidden() {
7520        return false;
7521    }
7522
7523    /**
7524     * <p>Draw the horizontal scrollbar if
7525     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7526     *
7527     * @param canvas the canvas on which to draw the scrollbar
7528     * @param scrollBar the scrollbar's drawable
7529     *
7530     * @see #isHorizontalScrollBarEnabled()
7531     * @see #computeHorizontalScrollRange()
7532     * @see #computeHorizontalScrollExtent()
7533     * @see #computeHorizontalScrollOffset()
7534     * @see android.widget.ScrollBarDrawable
7535     * @hide
7536     */
7537    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7538            int l, int t, int r, int b) {
7539        scrollBar.setBounds(l, t, r, b);
7540        scrollBar.draw(canvas);
7541    }
7542
7543    /**
7544     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7545     * returns true.</p>
7546     *
7547     * @param canvas the canvas on which to draw the scrollbar
7548     * @param scrollBar the scrollbar's drawable
7549     *
7550     * @see #isVerticalScrollBarEnabled()
7551     * @see #computeVerticalScrollRange()
7552     * @see #computeVerticalScrollExtent()
7553     * @see #computeVerticalScrollOffset()
7554     * @see android.widget.ScrollBarDrawable
7555     * @hide
7556     */
7557    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7558            int l, int t, int r, int b) {
7559        scrollBar.setBounds(l, t, r, b);
7560        scrollBar.draw(canvas);
7561    }
7562
7563    /**
7564     * Implement this to do your drawing.
7565     *
7566     * @param canvas the canvas on which the background will be drawn
7567     */
7568    protected void onDraw(Canvas canvas) {
7569    }
7570
7571    /*
7572     * Caller is responsible for calling requestLayout if necessary.
7573     * (This allows addViewInLayout to not request a new layout.)
7574     */
7575    void assignParent(ViewParent parent) {
7576        if (mParent == null) {
7577            mParent = parent;
7578        } else if (parent == null) {
7579            mParent = null;
7580        } else {
7581            throw new RuntimeException("view " + this + " being added, but"
7582                    + " it already has a parent");
7583        }
7584    }
7585
7586    /**
7587     * This is called when the view is attached to a window.  At this point it
7588     * has a Surface and will start drawing.  Note that this function is
7589     * guaranteed to be called before {@link #onDraw}, however it may be called
7590     * any time before the first onDraw -- including before or after
7591     * {@link #onMeasure}.
7592     *
7593     * @see #onDetachedFromWindow()
7594     */
7595    protected void onAttachedToWindow() {
7596        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7597            mParent.requestTransparentRegion(this);
7598        }
7599        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7600            initialAwakenScrollBars();
7601            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7602        }
7603        jumpDrawablesToCurrentState();
7604    }
7605
7606    /**
7607     * This is called when the view is detached from a window.  At this point it
7608     * no longer has a surface for drawing.
7609     *
7610     * @see #onAttachedToWindow()
7611     */
7612    protected void onDetachedFromWindow() {
7613        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
7614
7615        removeUnsetPressCallback();
7616        removeLongPressCallback();
7617
7618        destroyDrawingCache();
7619
7620        if (mHardwareLayer != null) {
7621            mHardwareLayer.destroy();
7622            mHardwareLayer = null;
7623        }
7624
7625        if (mAttachInfo != null) {
7626            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
7627            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
7628        }
7629
7630        mCurrentAnimation = null;
7631    }
7632
7633    /**
7634     * @return The number of times this view has been attached to a window
7635     */
7636    protected int getWindowAttachCount() {
7637        return mWindowAttachCount;
7638    }
7639
7640    /**
7641     * Retrieve a unique token identifying the window this view is attached to.
7642     * @return Return the window's token for use in
7643     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7644     */
7645    public IBinder getWindowToken() {
7646        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7647    }
7648
7649    /**
7650     * Retrieve a unique token identifying the top-level "real" window of
7651     * the window that this view is attached to.  That is, this is like
7652     * {@link #getWindowToken}, except if the window this view in is a panel
7653     * window (attached to another containing window), then the token of
7654     * the containing window is returned instead.
7655     *
7656     * @return Returns the associated window token, either
7657     * {@link #getWindowToken()} or the containing window's token.
7658     */
7659    public IBinder getApplicationWindowToken() {
7660        AttachInfo ai = mAttachInfo;
7661        if (ai != null) {
7662            IBinder appWindowToken = ai.mPanelParentWindowToken;
7663            if (appWindowToken == null) {
7664                appWindowToken = ai.mWindowToken;
7665            }
7666            return appWindowToken;
7667        }
7668        return null;
7669    }
7670
7671    /**
7672     * Retrieve private session object this view hierarchy is using to
7673     * communicate with the window manager.
7674     * @return the session object to communicate with the window manager
7675     */
7676    /*package*/ IWindowSession getWindowSession() {
7677        return mAttachInfo != null ? mAttachInfo.mSession : null;
7678    }
7679
7680    /**
7681     * @param info the {@link android.view.View.AttachInfo} to associated with
7682     *        this view
7683     */
7684    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7685        //System.out.println("Attached! " + this);
7686        mAttachInfo = info;
7687        mWindowAttachCount++;
7688        // We will need to evaluate the drawable state at least once.
7689        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
7690        if (mFloatingTreeObserver != null) {
7691            info.mTreeObserver.merge(mFloatingTreeObserver);
7692            mFloatingTreeObserver = null;
7693        }
7694        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7695            mAttachInfo.mScrollContainers.add(this);
7696            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7697        }
7698        performCollectViewAttributes(visibility);
7699        onAttachedToWindow();
7700        int vis = info.mWindowVisibility;
7701        if (vis != GONE) {
7702            onWindowVisibilityChanged(vis);
7703        }
7704        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7705            // If nobody has evaluated the drawable state yet, then do it now.
7706            refreshDrawableState();
7707        }
7708    }
7709
7710    void dispatchDetachedFromWindow() {
7711        //System.out.println("Detached! " + this);
7712        AttachInfo info = mAttachInfo;
7713        if (info != null) {
7714            int vis = info.mWindowVisibility;
7715            if (vis != GONE) {
7716                onWindowVisibilityChanged(GONE);
7717            }
7718        }
7719
7720        onDetachedFromWindow();
7721        if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7722            mAttachInfo.mScrollContainers.remove(this);
7723            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7724        }
7725        mAttachInfo = null;
7726    }
7727
7728    /**
7729     * Store this view hierarchy's frozen state into the given container.
7730     *
7731     * @param container The SparseArray in which to save the view's state.
7732     *
7733     * @see #restoreHierarchyState
7734     * @see #dispatchSaveInstanceState
7735     * @see #onSaveInstanceState
7736     */
7737    public void saveHierarchyState(SparseArray<Parcelable> container) {
7738        dispatchSaveInstanceState(container);
7739    }
7740
7741    /**
7742     * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7743     * May be overridden to modify how freezing happens to a view's children; for example, some
7744     * views may want to not store state for their children.
7745     *
7746     * @param container The SparseArray in which to save the view's state.
7747     *
7748     * @see #dispatchRestoreInstanceState
7749     * @see #saveHierarchyState
7750     * @see #onSaveInstanceState
7751     */
7752    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7753        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7754            mPrivateFlags &= ~SAVE_STATE_CALLED;
7755            Parcelable state = onSaveInstanceState();
7756            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7757                throw new IllegalStateException(
7758                        "Derived class did not call super.onSaveInstanceState()");
7759            }
7760            if (state != null) {
7761                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7762                // + ": " + state);
7763                container.put(mID, state);
7764            }
7765        }
7766    }
7767
7768    /**
7769     * Hook allowing a view to generate a representation of its internal state
7770     * that can later be used to create a new instance with that same state.
7771     * This state should only contain information that is not persistent or can
7772     * not be reconstructed later. For example, you will never store your
7773     * current position on screen because that will be computed again when a
7774     * new instance of the view is placed in its view hierarchy.
7775     * <p>
7776     * Some examples of things you may store here: the current cursor position
7777     * in a text view (but usually not the text itself since that is stored in a
7778     * content provider or other persistent storage), the currently selected
7779     * item in a list view.
7780     *
7781     * @return Returns a Parcelable object containing the view's current dynamic
7782     *         state, or null if there is nothing interesting to save. The
7783     *         default implementation returns null.
7784     * @see #onRestoreInstanceState
7785     * @see #saveHierarchyState
7786     * @see #dispatchSaveInstanceState
7787     * @see #setSaveEnabled(boolean)
7788     */
7789    protected Parcelable onSaveInstanceState() {
7790        mPrivateFlags |= SAVE_STATE_CALLED;
7791        return BaseSavedState.EMPTY_STATE;
7792    }
7793
7794    /**
7795     * Restore this view hierarchy's frozen state from the given container.
7796     *
7797     * @param container The SparseArray which holds previously frozen states.
7798     *
7799     * @see #saveHierarchyState
7800     * @see #dispatchRestoreInstanceState
7801     * @see #onRestoreInstanceState
7802     */
7803    public void restoreHierarchyState(SparseArray<Parcelable> container) {
7804        dispatchRestoreInstanceState(container);
7805    }
7806
7807    /**
7808     * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7809     * children. May be overridden to modify how restoreing happens to a view's children; for
7810     * example, some views may want to not store state for their children.
7811     *
7812     * @param container The SparseArray which holds previously saved state.
7813     *
7814     * @see #dispatchSaveInstanceState
7815     * @see #restoreHierarchyState
7816     * @see #onRestoreInstanceState
7817     */
7818    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7819        if (mID != NO_ID) {
7820            Parcelable state = container.get(mID);
7821            if (state != null) {
7822                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7823                // + ": " + state);
7824                mPrivateFlags &= ~SAVE_STATE_CALLED;
7825                onRestoreInstanceState(state);
7826                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7827                    throw new IllegalStateException(
7828                            "Derived class did not call super.onRestoreInstanceState()");
7829                }
7830            }
7831        }
7832    }
7833
7834    /**
7835     * Hook allowing a view to re-apply a representation of its internal state that had previously
7836     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7837     * null state.
7838     *
7839     * @param state The frozen state that had previously been returned by
7840     *        {@link #onSaveInstanceState}.
7841     *
7842     * @see #onSaveInstanceState
7843     * @see #restoreHierarchyState
7844     * @see #dispatchRestoreInstanceState
7845     */
7846    protected void onRestoreInstanceState(Parcelable state) {
7847        mPrivateFlags |= SAVE_STATE_CALLED;
7848        if (state != BaseSavedState.EMPTY_STATE && state != null) {
7849            throw new IllegalArgumentException("Wrong state class, expecting View State but "
7850                    + "received " + state.getClass().toString() + " instead. This usually happens "
7851                    + "when two views of different type have the same id in the same hierarchy. "
7852                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7853                    + "other views do not use the same id.");
7854        }
7855    }
7856
7857    /**
7858     * <p>Return the time at which the drawing of the view hierarchy started.</p>
7859     *
7860     * @return the drawing start time in milliseconds
7861     */
7862    public long getDrawingTime() {
7863        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7864    }
7865
7866    /**
7867     * <p>Enables or disables the duplication of the parent's state into this view. When
7868     * duplication is enabled, this view gets its drawable state from its parent rather
7869     * than from its own internal properties.</p>
7870     *
7871     * <p>Note: in the current implementation, setting this property to true after the
7872     * view was added to a ViewGroup might have no effect at all. This property should
7873     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7874     *
7875     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7876     * property is enabled, an exception will be thrown.</p>
7877     *
7878     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
7879     * parent, these states should not be affected by this method.</p>
7880     *
7881     * @param enabled True to enable duplication of the parent's drawable state, false
7882     *                to disable it.
7883     *
7884     * @see #getDrawableState()
7885     * @see #isDuplicateParentStateEnabled()
7886     */
7887    public void setDuplicateParentStateEnabled(boolean enabled) {
7888        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7889    }
7890
7891    /**
7892     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7893     *
7894     * @return True if this view's drawable state is duplicated from the parent,
7895     *         false otherwise
7896     *
7897     * @see #getDrawableState()
7898     * @see #setDuplicateParentStateEnabled(boolean)
7899     */
7900    public boolean isDuplicateParentStateEnabled() {
7901        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
7902    }
7903
7904    /**
7905     * <p>Specifies the type of layer backing this view. The layer can be
7906     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
7907     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
7908     *
7909     * <p>A layer is associated with an optional {@link android.graphics.Paint}
7910     * instance that controls how the layer is composed on screen. The following
7911     * properties of the paint are taken into account when composing the layer:</p>
7912     * <ul>
7913     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
7914     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
7915     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
7916     * </ul>
7917     *
7918     * <p>If this view has an alpha value set to < 1.0 by calling
7919     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
7920     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
7921     * equivalent to setting a hardware layer on this view and providing a paint with
7922     * the desired alpha value.<p>
7923     *
7924     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
7925     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
7926     * for more information on when and how to use layers.</p>
7927     *
7928     * @param layerType The ype of layer to use with this view, must be one of
7929     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7930     *        {@link #LAYER_TYPE_HARDWARE}
7931     * @param paint The paint used to compose the layer. This argument is optional
7932     *        and can be null. It is ignored when the layer type is
7933     *        {@link #LAYER_TYPE_NONE}
7934     *
7935     * @see #getLayerType()
7936     * @see #LAYER_TYPE_NONE
7937     * @see #LAYER_TYPE_SOFTWARE
7938     * @see #LAYER_TYPE_HARDWARE
7939     * @see #setAlpha(float)
7940     *
7941     * @attr ref android.R.styleable#View_layerType
7942     */
7943    public void setLayerType(int layerType, Paint paint) {
7944        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
7945            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
7946                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
7947        }
7948
7949        if (layerType == mLayerType) {
7950            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
7951                mLayerPaint = paint == null ? new Paint() : paint;
7952                if (mParent instanceof ViewGroup) {
7953                    ((ViewGroup) mParent).invalidate();
7954                }
7955                invalidate();
7956            }
7957            return;
7958        }
7959
7960        // Destroy any previous software drawing cache if needed
7961        switch (mLayerType) {
7962            case LAYER_TYPE_SOFTWARE:
7963                if (mDrawingCache != null) {
7964                    mDrawingCache.recycle();
7965                    mDrawingCache = null;
7966                }
7967
7968                if (mUnscaledDrawingCache != null) {
7969                    mUnscaledDrawingCache.recycle();
7970                    mUnscaledDrawingCache = null;
7971                }
7972                break;
7973            case LAYER_TYPE_HARDWARE:
7974                if (mHardwareLayer != null) {
7975                    mHardwareLayer.destroy();
7976                    mHardwareLayer = null;
7977                }
7978                break;
7979            default:
7980                break;
7981        }
7982
7983        mLayerType = layerType;
7984        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
7985
7986        if (mParent instanceof ViewGroup) {
7987            ((ViewGroup) mParent).invalidate();
7988        }
7989        invalidate();
7990    }
7991
7992    /**
7993     * Indicates what type of layer is currently associated with this view. By default
7994     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
7995     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
7996     * for more information on the different types of layers.
7997     *
7998     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
7999     *         {@link #LAYER_TYPE_HARDWARE}
8000     *
8001     * @see #setLayerType(int, android.graphics.Paint)
8002     * @see #LAYER_TYPE_NONE
8003     * @see #LAYER_TYPE_SOFTWARE
8004     * @see #LAYER_TYPE_HARDWARE
8005     */
8006    public int getLayerType() {
8007        return mLayerType;
8008    }
8009
8010    /**
8011     * <p>Returns a hardware layer that can be used to draw this view again
8012     * without executing its draw method.</p>
8013     *
8014     * @return A HardwareLayer ready to render, or null if an error occurred.
8015     */
8016    HardwareLayer getHardwareLayer(Canvas currentCanvas) {
8017        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8018            return null;
8019        }
8020
8021        final int width = mRight - mLeft;
8022        final int height = mBottom - mTop;
8023
8024        if (width == 0 || height == 0) {
8025            return null;
8026        }
8027
8028        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
8029            if (mHardwareLayer == null) {
8030                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
8031                        width, height, isOpaque());
8032            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
8033                mHardwareLayer.resize(width, height);
8034            }
8035
8036            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
8037            try {
8038                canvas.setViewport(width, height);
8039                canvas.onPreDraw();
8040
8041                computeScroll();
8042                canvas.translate(-mScrollX, -mScrollY);
8043
8044                final int restoreCount = canvas.save();
8045
8046                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8047
8048                // Fast path for layouts with no backgrounds
8049                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8050                    mPrivateFlags &= ~DIRTY_MASK;
8051                    dispatchDraw(canvas);
8052                } else {
8053                    draw(canvas);
8054                }
8055
8056                canvas.restoreToCount(restoreCount);
8057            } finally {
8058                canvas.onPostDraw();
8059                mHardwareLayer.end(currentCanvas);
8060            }
8061        }
8062
8063        return mHardwareLayer;
8064    }
8065
8066    /**
8067     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8068     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8069     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8070     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8071     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8072     * null.</p>
8073     *
8074     * <p>Enabling the drawing cache is similar to
8075     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
8076     * acceleration is turned off. When hardware acceleration is turned on enabling the
8077     * drawing cache has either no effect or the cache used at drawing time is not a bitmap.
8078     * This API can however be used to manually generate a bitmap copy of this view.</p>
8079     *
8080     * @param enabled true to enable the drawing cache, false otherwise
8081     *
8082     * @see #isDrawingCacheEnabled()
8083     * @see #getDrawingCache()
8084     * @see #buildDrawingCache()
8085     * @see #setLayerType(int, android.graphics.Paint)
8086     */
8087    public void setDrawingCacheEnabled(boolean enabled) {
8088        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8089    }
8090
8091    /**
8092     * <p>Indicates whether the drawing cache is enabled for this view.</p>
8093     *
8094     * @return true if the drawing cache is enabled
8095     *
8096     * @see #setDrawingCacheEnabled(boolean)
8097     * @see #getDrawingCache()
8098     */
8099    @ViewDebug.ExportedProperty(category = "drawing")
8100    public boolean isDrawingCacheEnabled() {
8101        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8102    }
8103
8104    /**
8105     * <p>Returns a display list that can be used to draw this view again
8106     * without executing its draw method.</p>
8107     *
8108     * @return A DisplayList ready to replay, or null if caching is not enabled.
8109     */
8110    DisplayList getDisplayList() {
8111        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8112            return null;
8113        }
8114        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8115            return null;
8116        }
8117
8118        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED &&
8119                ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8120                        mDisplayList == null || !mDisplayList.isValid())) {
8121
8122            if (mDisplayList == null) {
8123                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
8124            }
8125
8126            final HardwareCanvas canvas = mDisplayList.start();
8127            try {
8128                int width = mRight - mLeft;
8129                int height = mBottom - mTop;
8130
8131                canvas.setViewport(width, height);
8132                canvas.onPreDraw();
8133
8134                final int restoreCount = canvas.save();
8135
8136                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8137
8138                // Fast path for layouts with no backgrounds
8139                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8140                    mPrivateFlags &= ~DIRTY_MASK;
8141                    dispatchDraw(canvas);
8142                } else {
8143                    draw(canvas);
8144                }
8145
8146                canvas.restoreToCount(restoreCount);
8147            } finally {
8148                canvas.onPostDraw();
8149
8150                mDisplayList.end();
8151            }
8152        }
8153
8154        return mDisplayList;
8155    }
8156
8157    /**
8158     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8159     *
8160     * @return A non-scaled bitmap representing this view or null if cache is disabled.
8161     *
8162     * @see #getDrawingCache(boolean)
8163     */
8164    public Bitmap getDrawingCache() {
8165        return getDrawingCache(false);
8166    }
8167
8168    /**
8169     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8170     * is null when caching is disabled. If caching is enabled and the cache is not ready,
8171     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8172     * draw from the cache when the cache is enabled. To benefit from the cache, you must
8173     * request the drawing cache by calling this method and draw it on screen if the
8174     * returned bitmap is not null.</p>
8175     *
8176     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8177     * this method will create a bitmap of the same size as this view. Because this bitmap
8178     * will be drawn scaled by the parent ViewGroup, the result on screen might show
8179     * scaling artifacts. To avoid such artifacts, you should call this method by setting
8180     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8181     * size than the view. This implies that your application must be able to handle this
8182     * size.</p>
8183     *
8184     * @param autoScale Indicates whether the generated bitmap should be scaled based on
8185     *        the current density of the screen when the application is in compatibility
8186     *        mode.
8187     *
8188     * @return A bitmap representing this view or null if cache is disabled.
8189     *
8190     * @see #setDrawingCacheEnabled(boolean)
8191     * @see #isDrawingCacheEnabled()
8192     * @see #buildDrawingCache(boolean)
8193     * @see #destroyDrawingCache()
8194     */
8195    public Bitmap getDrawingCache(boolean autoScale) {
8196        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8197            return null;
8198        }
8199        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
8200            buildDrawingCache(autoScale);
8201        }
8202        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
8203    }
8204
8205    /**
8206     * <p>Frees the resources used by the drawing cache. If you call
8207     * {@link #buildDrawingCache()} manually without calling
8208     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8209     * should cleanup the cache with this method afterwards.</p>
8210     *
8211     * @see #setDrawingCacheEnabled(boolean)
8212     * @see #buildDrawingCache()
8213     * @see #getDrawingCache()
8214     */
8215    public void destroyDrawingCache() {
8216        if (mDrawingCache != null) {
8217            mDrawingCache.recycle();
8218            mDrawingCache = null;
8219        }
8220        if (mUnscaledDrawingCache != null) {
8221            mUnscaledDrawingCache.recycle();
8222            mUnscaledDrawingCache = null;
8223        }
8224        if (mDisplayList != null) {
8225            mDisplayList.invalidate();
8226        }
8227    }
8228
8229    /**
8230     * Setting a solid background color for the drawing cache's bitmaps will improve
8231     * perfromance and memory usage. Note, though that this should only be used if this
8232     * view will always be drawn on top of a solid color.
8233     *
8234     * @param color The background color to use for the drawing cache's bitmap
8235     *
8236     * @see #setDrawingCacheEnabled(boolean)
8237     * @see #buildDrawingCache()
8238     * @see #getDrawingCache()
8239     */
8240    public void setDrawingCacheBackgroundColor(int color) {
8241        if (color != mDrawingCacheBackgroundColor) {
8242            mDrawingCacheBackgroundColor = color;
8243            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8244        }
8245    }
8246
8247    /**
8248     * @see #setDrawingCacheBackgroundColor(int)
8249     *
8250     * @return The background color to used for the drawing cache's bitmap
8251     */
8252    public int getDrawingCacheBackgroundColor() {
8253        return mDrawingCacheBackgroundColor;
8254    }
8255
8256    /**
8257     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8258     *
8259     * @see #buildDrawingCache(boolean)
8260     */
8261    public void buildDrawingCache() {
8262        buildDrawingCache(false);
8263    }
8264
8265    /**
8266     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8267     *
8268     * <p>If you call {@link #buildDrawingCache()} manually without calling
8269     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8270     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
8271     *
8272     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8273     * this method will create a bitmap of the same size as this view. Because this bitmap
8274     * will be drawn scaled by the parent ViewGroup, the result on screen might show
8275     * scaling artifacts. To avoid such artifacts, you should call this method by setting
8276     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8277     * size than the view. This implies that your application must be able to handle this
8278     * size.</p>
8279     *
8280     * <p>You should avoid calling this method when hardware acceleration is enabled. If
8281     * you do not need the drawing cache bitmap, calling this method will increase memory
8282     * usage and cause the view to be rendered in software once, thus negatively impacting
8283     * performance.</p>
8284     *
8285     * @see #getDrawingCache()
8286     * @see #destroyDrawingCache()
8287     */
8288    public void buildDrawingCache(boolean autoScale) {
8289        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
8290                mDrawingCache == null : mUnscaledDrawingCache == null)) {
8291
8292            if (ViewDebug.TRACE_HIERARCHY) {
8293                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8294            }
8295
8296            int width = mRight - mLeft;
8297            int height = mBottom - mTop;
8298
8299            final AttachInfo attachInfo = mAttachInfo;
8300            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
8301
8302            if (autoScale && scalingRequired) {
8303                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8304                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
8305            }
8306
8307            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
8308            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
8309            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
8310
8311            if (width <= 0 || height <= 0 ||
8312                     // Projected bitmap size in bytes
8313                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
8314                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8315                destroyDrawingCache();
8316                return;
8317            }
8318
8319            boolean clear = true;
8320            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
8321
8322            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
8323                Bitmap.Config quality;
8324                if (!opaque) {
8325                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8326                        case DRAWING_CACHE_QUALITY_AUTO:
8327                            quality = Bitmap.Config.ARGB_8888;
8328                            break;
8329                        case DRAWING_CACHE_QUALITY_LOW:
8330                            quality = Bitmap.Config.ARGB_4444;
8331                            break;
8332                        case DRAWING_CACHE_QUALITY_HIGH:
8333                            quality = Bitmap.Config.ARGB_8888;
8334                            break;
8335                        default:
8336                            quality = Bitmap.Config.ARGB_8888;
8337                            break;
8338                    }
8339                } else {
8340                    // Optimization for translucent windows
8341                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
8342                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
8343                }
8344
8345                // Try to cleanup memory
8346                if (bitmap != null) bitmap.recycle();
8347
8348                try {
8349                    bitmap = Bitmap.createBitmap(width, height, quality);
8350                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8351                    if (autoScale) {
8352                        mDrawingCache = bitmap;
8353                    } else {
8354                        mUnscaledDrawingCache = bitmap;
8355                    }
8356                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
8357                } catch (OutOfMemoryError e) {
8358                    // If there is not enough memory to create the bitmap cache, just
8359                    // ignore the issue as bitmap caches are not required to draw the
8360                    // view hierarchy
8361                    if (autoScale) {
8362                        mDrawingCache = null;
8363                    } else {
8364                        mUnscaledDrawingCache = null;
8365                    }
8366                    return;
8367                }
8368
8369                clear = drawingCacheBackgroundColor != 0;
8370            }
8371
8372            Canvas canvas;
8373            if (attachInfo != null) {
8374                canvas = attachInfo.mCanvas;
8375                if (canvas == null) {
8376                    canvas = new Canvas();
8377                }
8378                canvas.setBitmap(bitmap);
8379                // Temporarily clobber the cached Canvas in case one of our children
8380                // is also using a drawing cache. Without this, the children would
8381                // steal the canvas by attaching their own bitmap to it and bad, bad
8382                // thing would happen (invisible views, corrupted drawings, etc.)
8383                attachInfo.mCanvas = null;
8384            } else {
8385                // This case should hopefully never or seldom happen
8386                canvas = new Canvas(bitmap);
8387            }
8388
8389            if (clear) {
8390                bitmap.eraseColor(drawingCacheBackgroundColor);
8391            }
8392
8393            computeScroll();
8394            final int restoreCount = canvas.save();
8395
8396            if (autoScale && scalingRequired) {
8397                final float scale = attachInfo.mApplicationScale;
8398                canvas.scale(scale, scale);
8399            }
8400
8401            canvas.translate(-mScrollX, -mScrollY);
8402
8403            mPrivateFlags |= DRAWN;
8404            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8405                    mLayerType != LAYER_TYPE_NONE) {
8406                mPrivateFlags |= DRAWING_CACHE_VALID;
8407            }
8408
8409            // Fast path for layouts with no backgrounds
8410            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8411                if (ViewDebug.TRACE_HIERARCHY) {
8412                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8413                }
8414                mPrivateFlags &= ~DIRTY_MASK;
8415                dispatchDraw(canvas);
8416            } else {
8417                draw(canvas);
8418            }
8419
8420            canvas.restoreToCount(restoreCount);
8421
8422            if (attachInfo != null) {
8423                // Restore the cached Canvas for our siblings
8424                attachInfo.mCanvas = canvas;
8425            }
8426        }
8427    }
8428
8429    /**
8430     * Create a snapshot of the view into a bitmap.  We should probably make
8431     * some form of this public, but should think about the API.
8432     */
8433    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
8434        int width = mRight - mLeft;
8435        int height = mBottom - mTop;
8436
8437        final AttachInfo attachInfo = mAttachInfo;
8438        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
8439        width = (int) ((width * scale) + 0.5f);
8440        height = (int) ((height * scale) + 0.5f);
8441
8442        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
8443        if (bitmap == null) {
8444            throw new OutOfMemoryError();
8445        }
8446
8447        bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8448
8449        Canvas canvas;
8450        if (attachInfo != null) {
8451            canvas = attachInfo.mCanvas;
8452            if (canvas == null) {
8453                canvas = new Canvas();
8454            }
8455            canvas.setBitmap(bitmap);
8456            // Temporarily clobber the cached Canvas in case one of our children
8457            // is also using a drawing cache. Without this, the children would
8458            // steal the canvas by attaching their own bitmap to it and bad, bad
8459            // things would happen (invisible views, corrupted drawings, etc.)
8460            attachInfo.mCanvas = null;
8461        } else {
8462            // This case should hopefully never or seldom happen
8463            canvas = new Canvas(bitmap);
8464        }
8465
8466        if ((backgroundColor & 0xff000000) != 0) {
8467            bitmap.eraseColor(backgroundColor);
8468        }
8469
8470        computeScroll();
8471        final int restoreCount = canvas.save();
8472        canvas.scale(scale, scale);
8473        canvas.translate(-mScrollX, -mScrollY);
8474
8475        // Temporarily remove the dirty mask
8476        int flags = mPrivateFlags;
8477        mPrivateFlags &= ~DIRTY_MASK;
8478
8479        // Fast path for layouts with no backgrounds
8480        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8481            dispatchDraw(canvas);
8482        } else {
8483            draw(canvas);
8484        }
8485
8486        mPrivateFlags = flags;
8487
8488        canvas.restoreToCount(restoreCount);
8489
8490        if (attachInfo != null) {
8491            // Restore the cached Canvas for our siblings
8492            attachInfo.mCanvas = canvas;
8493        }
8494
8495        return bitmap;
8496    }
8497
8498    /**
8499     * Indicates whether this View is currently in edit mode. A View is usually
8500     * in edit mode when displayed within a developer tool. For instance, if
8501     * this View is being drawn by a visual user interface builder, this method
8502     * should return true.
8503     *
8504     * Subclasses should check the return value of this method to provide
8505     * different behaviors if their normal behavior might interfere with the
8506     * host environment. For instance: the class spawns a thread in its
8507     * constructor, the drawing code relies on device-specific features, etc.
8508     *
8509     * This method is usually checked in the drawing code of custom widgets.
8510     *
8511     * @return True if this View is in edit mode, false otherwise.
8512     */
8513    public boolean isInEditMode() {
8514        return false;
8515    }
8516
8517    /**
8518     * If the View draws content inside its padding and enables fading edges,
8519     * it needs to support padding offsets. Padding offsets are added to the
8520     * fading edges to extend the length of the fade so that it covers pixels
8521     * drawn inside the padding.
8522     *
8523     * Subclasses of this class should override this method if they need
8524     * to draw content inside the padding.
8525     *
8526     * @return True if padding offset must be applied, false otherwise.
8527     *
8528     * @see #getLeftPaddingOffset()
8529     * @see #getRightPaddingOffset()
8530     * @see #getTopPaddingOffset()
8531     * @see #getBottomPaddingOffset()
8532     *
8533     * @since CURRENT
8534     */
8535    protected boolean isPaddingOffsetRequired() {
8536        return false;
8537    }
8538
8539    /**
8540     * Amount by which to extend the left fading region. Called only when
8541     * {@link #isPaddingOffsetRequired()} returns true.
8542     *
8543     * @return The left padding offset in pixels.
8544     *
8545     * @see #isPaddingOffsetRequired()
8546     *
8547     * @since CURRENT
8548     */
8549    protected int getLeftPaddingOffset() {
8550        return 0;
8551    }
8552
8553    /**
8554     * Amount by which to extend the right fading region. Called only when
8555     * {@link #isPaddingOffsetRequired()} returns true.
8556     *
8557     * @return The right padding offset in pixels.
8558     *
8559     * @see #isPaddingOffsetRequired()
8560     *
8561     * @since CURRENT
8562     */
8563    protected int getRightPaddingOffset() {
8564        return 0;
8565    }
8566
8567    /**
8568     * Amount by which to extend the top fading region. Called only when
8569     * {@link #isPaddingOffsetRequired()} returns true.
8570     *
8571     * @return The top padding offset in pixels.
8572     *
8573     * @see #isPaddingOffsetRequired()
8574     *
8575     * @since CURRENT
8576     */
8577    protected int getTopPaddingOffset() {
8578        return 0;
8579    }
8580
8581    /**
8582     * Amount by which to extend the bottom fading region. Called only when
8583     * {@link #isPaddingOffsetRequired()} returns true.
8584     *
8585     * @return The bottom padding offset in pixels.
8586     *
8587     * @see #isPaddingOffsetRequired()
8588     *
8589     * @since CURRENT
8590     */
8591    protected int getBottomPaddingOffset() {
8592        return 0;
8593    }
8594
8595    /**
8596     * <p>Indicates whether this view is attached to an hardware accelerated
8597     * window or not.</p>
8598     *
8599     * <p>Even if this method returns true, it does not mean that every call
8600     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8601     * accelerated {@link android.graphics.Canvas}. For instance, if this view
8602     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8603     * window is hardware accelerated,
8604     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8605     * return false, and this method will return true.</p>
8606     *
8607     * @return True if the view is attached to a window and the window is
8608     *         hardware accelerated; false in any other case.
8609     */
8610    public boolean isHardwareAccelerated() {
8611        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8612    }
8613
8614    /**
8615     * Manually render this view (and all of its children) to the given Canvas.
8616     * The view must have already done a full layout before this function is
8617     * called.  When implementing a view, implement {@link #onDraw} instead of
8618     * overriding this method. If you do need to override this method, call
8619     * the superclass version.
8620     *
8621     * @param canvas The Canvas to which the View is rendered.
8622     */
8623    public void draw(Canvas canvas) {
8624        if (ViewDebug.TRACE_HIERARCHY) {
8625            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8626        }
8627
8628        final int privateFlags = mPrivateFlags;
8629        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8630                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8631        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
8632
8633        /*
8634         * Draw traversal performs several drawing steps which must be executed
8635         * in the appropriate order:
8636         *
8637         *      1. Draw the background
8638         *      2. If necessary, save the canvas' layers to prepare for fading
8639         *      3. Draw view's content
8640         *      4. Draw children
8641         *      5. If necessary, draw the fading edges and restore layers
8642         *      6. Draw decorations (scrollbars for instance)
8643         */
8644
8645        // Step 1, draw the background, if needed
8646        int saveCount;
8647
8648        if (!dirtyOpaque) {
8649            final Drawable background = mBGDrawable;
8650            if (background != null) {
8651                final int scrollX = mScrollX;
8652                final int scrollY = mScrollY;
8653
8654                if (mBackgroundSizeChanged) {
8655                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
8656                    mBackgroundSizeChanged = false;
8657                }
8658
8659                if ((scrollX | scrollY) == 0) {
8660                    background.draw(canvas);
8661                } else {
8662                    canvas.translate(scrollX, scrollY);
8663                    background.draw(canvas);
8664                    canvas.translate(-scrollX, -scrollY);
8665                }
8666            }
8667        }
8668
8669        // skip step 2 & 5 if possible (common case)
8670        final int viewFlags = mViewFlags;
8671        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8672        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8673        if (!verticalEdges && !horizontalEdges) {
8674            // Step 3, draw the content
8675            if (!dirtyOpaque) onDraw(canvas);
8676
8677            // Step 4, draw the children
8678            dispatchDraw(canvas);
8679
8680            // Step 6, draw decorations (scrollbars)
8681            onDrawScrollBars(canvas);
8682
8683            // we're done...
8684            return;
8685        }
8686
8687        /*
8688         * Here we do the full fledged routine...
8689         * (this is an uncommon case where speed matters less,
8690         * this is why we repeat some of the tests that have been
8691         * done above)
8692         */
8693
8694        boolean drawTop = false;
8695        boolean drawBottom = false;
8696        boolean drawLeft = false;
8697        boolean drawRight = false;
8698
8699        float topFadeStrength = 0.0f;
8700        float bottomFadeStrength = 0.0f;
8701        float leftFadeStrength = 0.0f;
8702        float rightFadeStrength = 0.0f;
8703
8704        // Step 2, save the canvas' layers
8705        int paddingLeft = mPaddingLeft;
8706        int paddingTop = mPaddingTop;
8707
8708        final boolean offsetRequired = isPaddingOffsetRequired();
8709        if (offsetRequired) {
8710            paddingLeft += getLeftPaddingOffset();
8711            paddingTop += getTopPaddingOffset();
8712        }
8713
8714        int left = mScrollX + paddingLeft;
8715        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8716        int top = mScrollY + paddingTop;
8717        int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8718
8719        if (offsetRequired) {
8720            right += getRightPaddingOffset();
8721            bottom += getBottomPaddingOffset();
8722        }
8723
8724        final ScrollabilityCache scrollabilityCache = mScrollCache;
8725        int length = scrollabilityCache.fadingEdgeLength;
8726
8727        // clip the fade length if top and bottom fades overlap
8728        // overlapping fades produce odd-looking artifacts
8729        if (verticalEdges && (top + length > bottom - length)) {
8730            length = (bottom - top) / 2;
8731        }
8732
8733        // also clip horizontal fades if necessary
8734        if (horizontalEdges && (left + length > right - length)) {
8735            length = (right - left) / 2;
8736        }
8737
8738        if (verticalEdges) {
8739            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
8740            drawTop = topFadeStrength > 0.0f;
8741            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
8742            drawBottom = bottomFadeStrength > 0.0f;
8743        }
8744
8745        if (horizontalEdges) {
8746            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
8747            drawLeft = leftFadeStrength > 0.0f;
8748            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
8749            drawRight = rightFadeStrength > 0.0f;
8750        }
8751
8752        saveCount = canvas.getSaveCount();
8753
8754        int solidColor = getSolidColor();
8755        if (solidColor == 0) {
8756            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8757
8758            if (drawTop) {
8759                canvas.saveLayer(left, top, right, top + length, null, flags);
8760            }
8761
8762            if (drawBottom) {
8763                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8764            }
8765
8766            if (drawLeft) {
8767                canvas.saveLayer(left, top, left + length, bottom, null, flags);
8768            }
8769
8770            if (drawRight) {
8771                canvas.saveLayer(right - length, top, right, bottom, null, flags);
8772            }
8773        } else {
8774            scrollabilityCache.setFadeColor(solidColor);
8775        }
8776
8777        // Step 3, draw the content
8778        if (!dirtyOpaque) onDraw(canvas);
8779
8780        // Step 4, draw the children
8781        dispatchDraw(canvas);
8782
8783        // Step 5, draw the fade effect and restore layers
8784        final Paint p = scrollabilityCache.paint;
8785        final Matrix matrix = scrollabilityCache.matrix;
8786        final Shader fade = scrollabilityCache.shader;
8787        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8788
8789        if (drawTop) {
8790            matrix.setScale(1, fadeHeight * topFadeStrength);
8791            matrix.postTranslate(left, top);
8792            fade.setLocalMatrix(matrix);
8793            canvas.drawRect(left, top, right, top + length, p);
8794        }
8795
8796        if (drawBottom) {
8797            matrix.setScale(1, fadeHeight * bottomFadeStrength);
8798            matrix.postRotate(180);
8799            matrix.postTranslate(left, bottom);
8800            fade.setLocalMatrix(matrix);
8801            canvas.drawRect(left, bottom - length, right, bottom, p);
8802        }
8803
8804        if (drawLeft) {
8805            matrix.setScale(1, fadeHeight * leftFadeStrength);
8806            matrix.postRotate(-90);
8807            matrix.postTranslate(left, top);
8808            fade.setLocalMatrix(matrix);
8809            canvas.drawRect(left, top, left + length, bottom, p);
8810        }
8811
8812        if (drawRight) {
8813            matrix.setScale(1, fadeHeight * rightFadeStrength);
8814            matrix.postRotate(90);
8815            matrix.postTranslate(right, top);
8816            fade.setLocalMatrix(matrix);
8817            canvas.drawRect(right - length, top, right, bottom, p);
8818        }
8819
8820        canvas.restoreToCount(saveCount);
8821
8822        // Step 6, draw decorations (scrollbars)
8823        onDrawScrollBars(canvas);
8824    }
8825
8826    /**
8827     * Override this if your view is known to always be drawn on top of a solid color background,
8828     * and needs to draw fading edges. Returning a non-zero color enables the view system to
8829     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8830     * should be set to 0xFF.
8831     *
8832     * @see #setVerticalFadingEdgeEnabled
8833     * @see #setHorizontalFadingEdgeEnabled
8834     *
8835     * @return The known solid color background for this view, or 0 if the color may vary
8836     */
8837    public int getSolidColor() {
8838        return 0;
8839    }
8840
8841    /**
8842     * Build a human readable string representation of the specified view flags.
8843     *
8844     * @param flags the view flags to convert to a string
8845     * @return a String representing the supplied flags
8846     */
8847    private static String printFlags(int flags) {
8848        String output = "";
8849        int numFlags = 0;
8850        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
8851            output += "TAKES_FOCUS";
8852            numFlags++;
8853        }
8854
8855        switch (flags & VISIBILITY_MASK) {
8856        case INVISIBLE:
8857            if (numFlags > 0) {
8858                output += " ";
8859            }
8860            output += "INVISIBLE";
8861            // USELESS HERE numFlags++;
8862            break;
8863        case GONE:
8864            if (numFlags > 0) {
8865                output += " ";
8866            }
8867            output += "GONE";
8868            // USELESS HERE numFlags++;
8869            break;
8870        default:
8871            break;
8872        }
8873        return output;
8874    }
8875
8876    /**
8877     * Build a human readable string representation of the specified private
8878     * view flags.
8879     *
8880     * @param privateFlags the private view flags to convert to a string
8881     * @return a String representing the supplied flags
8882     */
8883    private static String printPrivateFlags(int privateFlags) {
8884        String output = "";
8885        int numFlags = 0;
8886
8887        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
8888            output += "WANTS_FOCUS";
8889            numFlags++;
8890        }
8891
8892        if ((privateFlags & FOCUSED) == FOCUSED) {
8893            if (numFlags > 0) {
8894                output += " ";
8895            }
8896            output += "FOCUSED";
8897            numFlags++;
8898        }
8899
8900        if ((privateFlags & SELECTED) == SELECTED) {
8901            if (numFlags > 0) {
8902                output += " ";
8903            }
8904            output += "SELECTED";
8905            numFlags++;
8906        }
8907
8908        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
8909            if (numFlags > 0) {
8910                output += " ";
8911            }
8912            output += "IS_ROOT_NAMESPACE";
8913            numFlags++;
8914        }
8915
8916        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
8917            if (numFlags > 0) {
8918                output += " ";
8919            }
8920            output += "HAS_BOUNDS";
8921            numFlags++;
8922        }
8923
8924        if ((privateFlags & DRAWN) == DRAWN) {
8925            if (numFlags > 0) {
8926                output += " ";
8927            }
8928            output += "DRAWN";
8929            // USELESS HERE numFlags++;
8930        }
8931        return output;
8932    }
8933
8934    /**
8935     * <p>Indicates whether or not this view's layout will be requested during
8936     * the next hierarchy layout pass.</p>
8937     *
8938     * @return true if the layout will be forced during next layout pass
8939     */
8940    public boolean isLayoutRequested() {
8941        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
8942    }
8943
8944    /**
8945     * Assign a size and position to a view and all of its
8946     * descendants
8947     *
8948     * <p>This is the second phase of the layout mechanism.
8949     * (The first is measuring). In this phase, each parent calls
8950     * layout on all of its children to position them.
8951     * This is typically done using the child measurements
8952     * that were stored in the measure pass().</p>
8953     *
8954     * <p>Derived classes should not override this method.
8955     * Derived classes with children should override
8956     * onLayout. In that method, they should
8957     * call layout on each of their children.</p>
8958     *
8959     * @param l Left position, relative to parent
8960     * @param t Top position, relative to parent
8961     * @param r Right position, relative to parent
8962     * @param b Bottom position, relative to parent
8963     */
8964    @SuppressWarnings({"unchecked"})
8965    public void layout(int l, int t, int r, int b) {
8966        int oldL = mLeft;
8967        int oldT = mTop;
8968        int oldB = mBottom;
8969        int oldR = mRight;
8970        boolean changed = setFrame(l, t, r, b);
8971        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
8972            if (ViewDebug.TRACE_HIERARCHY) {
8973                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
8974            }
8975
8976            onLayout(changed, l, t, r, b);
8977            mPrivateFlags &= ~LAYOUT_REQUIRED;
8978
8979            if (mOnLayoutChangeListeners != null) {
8980                ArrayList<OnLayoutChangeListener> listenersCopy =
8981                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
8982                int numListeners = listenersCopy.size();
8983                for (int i = 0; i < numListeners; ++i) {
8984                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
8985                }
8986            }
8987        }
8988        mPrivateFlags &= ~FORCE_LAYOUT;
8989    }
8990
8991    /**
8992     * Called from layout when this view should
8993     * assign a size and position to each of its children.
8994     *
8995     * Derived classes with children should override
8996     * this method and call layout on each of
8997     * their children.
8998     * @param changed This is a new size or position for this view
8999     * @param left Left position, relative to parent
9000     * @param top Top position, relative to parent
9001     * @param right Right position, relative to parent
9002     * @param bottom Bottom position, relative to parent
9003     */
9004    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
9005    }
9006
9007    /**
9008     * Assign a size and position to this view.
9009     *
9010     * This is called from layout.
9011     *
9012     * @param left Left position, relative to parent
9013     * @param top Top position, relative to parent
9014     * @param right Right position, relative to parent
9015     * @param bottom Bottom position, relative to parent
9016     * @return true if the new size and position are different than the
9017     *         previous ones
9018     * {@hide}
9019     */
9020    protected boolean setFrame(int left, int top, int right, int bottom) {
9021        boolean changed = false;
9022
9023        if (DBG) {
9024            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
9025                    + right + "," + bottom + ")");
9026        }
9027
9028        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
9029            changed = true;
9030
9031            // Remember our drawn bit
9032            int drawn = mPrivateFlags & DRAWN;
9033
9034            // Invalidate our old position
9035            invalidate();
9036
9037
9038            int oldWidth = mRight - mLeft;
9039            int oldHeight = mBottom - mTop;
9040
9041            mLeft = left;
9042            mTop = top;
9043            mRight = right;
9044            mBottom = bottom;
9045
9046            mPrivateFlags |= HAS_BOUNDS;
9047
9048            int newWidth = right - left;
9049            int newHeight = bottom - top;
9050
9051            if (newWidth != oldWidth || newHeight != oldHeight) {
9052                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9053                    // A change in dimension means an auto-centered pivot point changes, too
9054                    mMatrixDirty = true;
9055                }
9056                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9057            }
9058
9059            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9060                // If we are visible, force the DRAWN bit to on so that
9061                // this invalidate will go through (at least to our parent).
9062                // This is because someone may have invalidated this view
9063                // before this call to setFrame came in, thereby clearing
9064                // the DRAWN bit.
9065                mPrivateFlags |= DRAWN;
9066                invalidate();
9067            }
9068
9069            // Reset drawn bit to original value (invalidate turns it off)
9070            mPrivateFlags |= drawn;
9071
9072            mBackgroundSizeChanged = true;
9073        }
9074        return changed;
9075    }
9076
9077    /**
9078     * Finalize inflating a view from XML.  This is called as the last phase
9079     * of inflation, after all child views have been added.
9080     *
9081     * <p>Even if the subclass overrides onFinishInflate, they should always be
9082     * sure to call the super method, so that we get called.
9083     */
9084    protected void onFinishInflate() {
9085    }
9086
9087    /**
9088     * Returns the resources associated with this view.
9089     *
9090     * @return Resources object.
9091     */
9092    public Resources getResources() {
9093        return mResources;
9094    }
9095
9096    /**
9097     * Invalidates the specified Drawable.
9098     *
9099     * @param drawable the drawable to invalidate
9100     */
9101    public void invalidateDrawable(Drawable drawable) {
9102        if (verifyDrawable(drawable)) {
9103            final Rect dirty = drawable.getBounds();
9104            final int scrollX = mScrollX;
9105            final int scrollY = mScrollY;
9106
9107            invalidate(dirty.left + scrollX, dirty.top + scrollY,
9108                    dirty.right + scrollX, dirty.bottom + scrollY);
9109        }
9110    }
9111
9112    /**
9113     * Schedules an action on a drawable to occur at a specified time.
9114     *
9115     * @param who the recipient of the action
9116     * @param what the action to run on the drawable
9117     * @param when the time at which the action must occur. Uses the
9118     *        {@link SystemClock#uptimeMillis} timebase.
9119     */
9120    public void scheduleDrawable(Drawable who, Runnable what, long when) {
9121        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9122            mAttachInfo.mHandler.postAtTime(what, who, when);
9123        }
9124    }
9125
9126    /**
9127     * Cancels a scheduled action on a drawable.
9128     *
9129     * @param who the recipient of the action
9130     * @param what the action to cancel
9131     */
9132    public void unscheduleDrawable(Drawable who, Runnable what) {
9133        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9134            mAttachInfo.mHandler.removeCallbacks(what, who);
9135        }
9136    }
9137
9138    /**
9139     * Unschedule any events associated with the given Drawable.  This can be
9140     * used when selecting a new Drawable into a view, so that the previous
9141     * one is completely unscheduled.
9142     *
9143     * @param who The Drawable to unschedule.
9144     *
9145     * @see #drawableStateChanged
9146     */
9147    public void unscheduleDrawable(Drawable who) {
9148        if (mAttachInfo != null) {
9149            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9150        }
9151    }
9152
9153    /**
9154     * If your view subclass is displaying its own Drawable objects, it should
9155     * override this function and return true for any Drawable it is
9156     * displaying.  This allows animations for those drawables to be
9157     * scheduled.
9158     *
9159     * <p>Be sure to call through to the super class when overriding this
9160     * function.
9161     *
9162     * @param who The Drawable to verify.  Return true if it is one you are
9163     *            displaying, else return the result of calling through to the
9164     *            super class.
9165     *
9166     * @return boolean If true than the Drawable is being displayed in the
9167     *         view; else false and it is not allowed to animate.
9168     *
9169     * @see #unscheduleDrawable
9170     * @see #drawableStateChanged
9171     */
9172    protected boolean verifyDrawable(Drawable who) {
9173        return who == mBGDrawable;
9174    }
9175
9176    /**
9177     * This function is called whenever the state of the view changes in such
9178     * a way that it impacts the state of drawables being shown.
9179     *
9180     * <p>Be sure to call through to the superclass when overriding this
9181     * function.
9182     *
9183     * @see Drawable#setState
9184     */
9185    protected void drawableStateChanged() {
9186        Drawable d = mBGDrawable;
9187        if (d != null && d.isStateful()) {
9188            d.setState(getDrawableState());
9189        }
9190    }
9191
9192    /**
9193     * Call this to force a view to update its drawable state. This will cause
9194     * drawableStateChanged to be called on this view. Views that are interested
9195     * in the new state should call getDrawableState.
9196     *
9197     * @see #drawableStateChanged
9198     * @see #getDrawableState
9199     */
9200    public void refreshDrawableState() {
9201        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9202        drawableStateChanged();
9203
9204        ViewParent parent = mParent;
9205        if (parent != null) {
9206            parent.childDrawableStateChanged(this);
9207        }
9208    }
9209
9210    /**
9211     * Return an array of resource IDs of the drawable states representing the
9212     * current state of the view.
9213     *
9214     * @return The current drawable state
9215     *
9216     * @see Drawable#setState
9217     * @see #drawableStateChanged
9218     * @see #onCreateDrawableState
9219     */
9220    public final int[] getDrawableState() {
9221        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9222            return mDrawableState;
9223        } else {
9224            mDrawableState = onCreateDrawableState(0);
9225            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9226            return mDrawableState;
9227        }
9228    }
9229
9230    /**
9231     * Generate the new {@link android.graphics.drawable.Drawable} state for
9232     * this view. This is called by the view
9233     * system when the cached Drawable state is determined to be invalid.  To
9234     * retrieve the current state, you should use {@link #getDrawableState}.
9235     *
9236     * @param extraSpace if non-zero, this is the number of extra entries you
9237     * would like in the returned array in which you can place your own
9238     * states.
9239     *
9240     * @return Returns an array holding the current {@link Drawable} state of
9241     * the view.
9242     *
9243     * @see #mergeDrawableStates
9244     */
9245    protected int[] onCreateDrawableState(int extraSpace) {
9246        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9247                mParent instanceof View) {
9248            return ((View) mParent).onCreateDrawableState(extraSpace);
9249        }
9250
9251        int[] drawableState;
9252
9253        int privateFlags = mPrivateFlags;
9254
9255        int viewStateIndex = 0;
9256        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9257        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9258        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
9259        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
9260        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9261        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
9262        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9263            // This is set if HW acceleration is requested, even if the current
9264            // process doesn't allow it.  This is just to allow app preview
9265            // windows to better match their app.
9266            viewStateIndex |= VIEW_STATE_ACCELERATED;
9267        }
9268
9269        drawableState = VIEW_STATE_SETS[viewStateIndex];
9270
9271        //noinspection ConstantIfStatement
9272        if (false) {
9273            Log.i("View", "drawableStateIndex=" + viewStateIndex);
9274            Log.i("View", toString()
9275                    + " pressed=" + ((privateFlags & PRESSED) != 0)
9276                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9277                    + " fo=" + hasFocus()
9278                    + " sl=" + ((privateFlags & SELECTED) != 0)
9279                    + " wf=" + hasWindowFocus()
9280                    + ": " + Arrays.toString(drawableState));
9281        }
9282
9283        if (extraSpace == 0) {
9284            return drawableState;
9285        }
9286
9287        final int[] fullState;
9288        if (drawableState != null) {
9289            fullState = new int[drawableState.length + extraSpace];
9290            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9291        } else {
9292            fullState = new int[extraSpace];
9293        }
9294
9295        return fullState;
9296    }
9297
9298    /**
9299     * Merge your own state values in <var>additionalState</var> into the base
9300     * state values <var>baseState</var> that were returned by
9301     * {@link #onCreateDrawableState}.
9302     *
9303     * @param baseState The base state values returned by
9304     * {@link #onCreateDrawableState}, which will be modified to also hold your
9305     * own additional state values.
9306     *
9307     * @param additionalState The additional state values you would like
9308     * added to <var>baseState</var>; this array is not modified.
9309     *
9310     * @return As a convenience, the <var>baseState</var> array you originally
9311     * passed into the function is returned.
9312     *
9313     * @see #onCreateDrawableState
9314     */
9315    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9316        final int N = baseState.length;
9317        int i = N - 1;
9318        while (i >= 0 && baseState[i] == 0) {
9319            i--;
9320        }
9321        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9322        return baseState;
9323    }
9324
9325    /**
9326     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9327     * on all Drawable objects associated with this view.
9328     */
9329    public void jumpDrawablesToCurrentState() {
9330        if (mBGDrawable != null) {
9331            mBGDrawable.jumpToCurrentState();
9332        }
9333    }
9334
9335    /**
9336     * Sets the background color for this view.
9337     * @param color the color of the background
9338     */
9339    @RemotableViewMethod
9340    public void setBackgroundColor(int color) {
9341        if (mBGDrawable instanceof ColorDrawable) {
9342            ((ColorDrawable) mBGDrawable).setColor(color);
9343        } else {
9344            setBackgroundDrawable(new ColorDrawable(color));
9345        }
9346    }
9347
9348    /**
9349     * Set the background to a given resource. The resource should refer to
9350     * a Drawable object or 0 to remove the background.
9351     * @param resid The identifier of the resource.
9352     * @attr ref android.R.styleable#View_background
9353     */
9354    @RemotableViewMethod
9355    public void setBackgroundResource(int resid) {
9356        if (resid != 0 && resid == mBackgroundResource) {
9357            return;
9358        }
9359
9360        Drawable d= null;
9361        if (resid != 0) {
9362            d = mResources.getDrawable(resid);
9363        }
9364        setBackgroundDrawable(d);
9365
9366        mBackgroundResource = resid;
9367    }
9368
9369    /**
9370     * Set the background to a given Drawable, or remove the background. If the
9371     * background has padding, this View's padding is set to the background's
9372     * padding. However, when a background is removed, this View's padding isn't
9373     * touched. If setting the padding is desired, please use
9374     * {@link #setPadding(int, int, int, int)}.
9375     *
9376     * @param d The Drawable to use as the background, or null to remove the
9377     *        background
9378     */
9379    public void setBackgroundDrawable(Drawable d) {
9380        boolean requestLayout = false;
9381
9382        mBackgroundResource = 0;
9383
9384        /*
9385         * Regardless of whether we're setting a new background or not, we want
9386         * to clear the previous drawable.
9387         */
9388        if (mBGDrawable != null) {
9389            mBGDrawable.setCallback(null);
9390            unscheduleDrawable(mBGDrawable);
9391        }
9392
9393        if (d != null) {
9394            Rect padding = sThreadLocal.get();
9395            if (padding == null) {
9396                padding = new Rect();
9397                sThreadLocal.set(padding);
9398            }
9399            if (d.getPadding(padding)) {
9400                setPadding(padding.left, padding.top, padding.right, padding.bottom);
9401            }
9402
9403            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
9404            // if it has a different minimum size, we should layout again
9405            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9406                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9407                requestLayout = true;
9408            }
9409
9410            d.setCallback(this);
9411            if (d.isStateful()) {
9412                d.setState(getDrawableState());
9413            }
9414            d.setVisible(getVisibility() == VISIBLE, false);
9415            mBGDrawable = d;
9416
9417            if ((mPrivateFlags & SKIP_DRAW) != 0) {
9418                mPrivateFlags &= ~SKIP_DRAW;
9419                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9420                requestLayout = true;
9421            }
9422        } else {
9423            /* Remove the background */
9424            mBGDrawable = null;
9425
9426            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9427                /*
9428                 * This view ONLY drew the background before and we're removing
9429                 * the background, so now it won't draw anything
9430                 * (hence we SKIP_DRAW)
9431                 */
9432                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9433                mPrivateFlags |= SKIP_DRAW;
9434            }
9435
9436            /*
9437             * When the background is set, we try to apply its padding to this
9438             * View. When the background is removed, we don't touch this View's
9439             * padding. This is noted in the Javadocs. Hence, we don't need to
9440             * requestLayout(), the invalidate() below is sufficient.
9441             */
9442
9443            // The old background's minimum size could have affected this
9444            // View's layout, so let's requestLayout
9445            requestLayout = true;
9446        }
9447
9448        computeOpaqueFlags();
9449
9450        if (requestLayout) {
9451            requestLayout();
9452        }
9453
9454        mBackgroundSizeChanged = true;
9455        invalidate();
9456    }
9457
9458    /**
9459     * Gets the background drawable
9460     * @return The drawable used as the background for this view, if any.
9461     */
9462    public Drawable getBackground() {
9463        return mBGDrawable;
9464    }
9465
9466    /**
9467     * Sets the padding. The view may add on the space required to display
9468     * the scrollbars, depending on the style and visibility of the scrollbars.
9469     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9470     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9471     * from the values set in this call.
9472     *
9473     * @attr ref android.R.styleable#View_padding
9474     * @attr ref android.R.styleable#View_paddingBottom
9475     * @attr ref android.R.styleable#View_paddingLeft
9476     * @attr ref android.R.styleable#View_paddingRight
9477     * @attr ref android.R.styleable#View_paddingTop
9478     * @param left the left padding in pixels
9479     * @param top the top padding in pixels
9480     * @param right the right padding in pixels
9481     * @param bottom the bottom padding in pixels
9482     */
9483    public void setPadding(int left, int top, int right, int bottom) {
9484        boolean changed = false;
9485
9486        mUserPaddingLeft = left;
9487        mUserPaddingRight = right;
9488        mUserPaddingBottom = bottom;
9489
9490        final int viewFlags = mViewFlags;
9491
9492        // Common case is there are no scroll bars.
9493        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
9494            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
9495                // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9496                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
9497                        ? 0 : getVerticalScrollbarWidth();
9498                switch (mVerticalScrollbarPosition) {
9499                    case SCROLLBAR_POSITION_DEFAULT:
9500                    case SCROLLBAR_POSITION_RIGHT:
9501                        right += offset;
9502                        break;
9503                    case SCROLLBAR_POSITION_LEFT:
9504                        left += offset;
9505                        break;
9506                }
9507            }
9508            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
9509                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9510                        ? 0 : getHorizontalScrollbarHeight();
9511            }
9512        }
9513
9514        if (mPaddingLeft != left) {
9515            changed = true;
9516            mPaddingLeft = left;
9517        }
9518        if (mPaddingTop != top) {
9519            changed = true;
9520            mPaddingTop = top;
9521        }
9522        if (mPaddingRight != right) {
9523            changed = true;
9524            mPaddingRight = right;
9525        }
9526        if (mPaddingBottom != bottom) {
9527            changed = true;
9528            mPaddingBottom = bottom;
9529        }
9530
9531        if (changed) {
9532            requestLayout();
9533        }
9534    }
9535
9536    /**
9537     * Returns the top padding of this view.
9538     *
9539     * @return the top padding in pixels
9540     */
9541    public int getPaddingTop() {
9542        return mPaddingTop;
9543    }
9544
9545    /**
9546     * Returns the bottom padding of this view. If there are inset and enabled
9547     * scrollbars, this value may include the space required to display the
9548     * scrollbars as well.
9549     *
9550     * @return the bottom padding in pixels
9551     */
9552    public int getPaddingBottom() {
9553        return mPaddingBottom;
9554    }
9555
9556    /**
9557     * Returns the left padding of this view. If there are inset and enabled
9558     * scrollbars, this value may include the space required to display the
9559     * scrollbars as well.
9560     *
9561     * @return the left padding in pixels
9562     */
9563    public int getPaddingLeft() {
9564        return mPaddingLeft;
9565    }
9566
9567    /**
9568     * Returns the right padding of this view. If there are inset and enabled
9569     * scrollbars, this value may include the space required to display the
9570     * scrollbars as well.
9571     *
9572     * @return the right padding in pixels
9573     */
9574    public int getPaddingRight() {
9575        return mPaddingRight;
9576    }
9577
9578    /**
9579     * Changes the selection state of this view. A view can be selected or not.
9580     * Note that selection is not the same as focus. Views are typically
9581     * selected in the context of an AdapterView like ListView or GridView;
9582     * the selected view is the view that is highlighted.
9583     *
9584     * @param selected true if the view must be selected, false otherwise
9585     */
9586    public void setSelected(boolean selected) {
9587        if (((mPrivateFlags & SELECTED) != 0) != selected) {
9588            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
9589            if (!selected) resetPressedState();
9590            invalidate();
9591            refreshDrawableState();
9592            dispatchSetSelected(selected);
9593        }
9594    }
9595
9596    /**
9597     * Dispatch setSelected to all of this View's children.
9598     *
9599     * @see #setSelected(boolean)
9600     *
9601     * @param selected The new selected state
9602     */
9603    protected void dispatchSetSelected(boolean selected) {
9604    }
9605
9606    /**
9607     * Indicates the selection state of this view.
9608     *
9609     * @return true if the view is selected, false otherwise
9610     */
9611    @ViewDebug.ExportedProperty
9612    public boolean isSelected() {
9613        return (mPrivateFlags & SELECTED) != 0;
9614    }
9615
9616    /**
9617     * Changes the activated state of this view. A view can be activated or not.
9618     * Note that activation is not the same as selection.  Selection is
9619     * a transient property, representing the view (hierarchy) the user is
9620     * currently interacting with.  Activation is a longer-term state that the
9621     * user can move views in and out of.  For example, in a list view with
9622     * single or multiple selection enabled, the views in the current selection
9623     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
9624     * here.)  The activated state is propagated down to children of the view it
9625     * is set on.
9626     *
9627     * @param activated true if the view must be activated, false otherwise
9628     */
9629    public void setActivated(boolean activated) {
9630        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9631            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9632            invalidate();
9633            refreshDrawableState();
9634            dispatchSetActivated(activated);
9635        }
9636    }
9637
9638    /**
9639     * Dispatch setActivated to all of this View's children.
9640     *
9641     * @see #setActivated(boolean)
9642     *
9643     * @param activated The new activated state
9644     */
9645    protected void dispatchSetActivated(boolean activated) {
9646    }
9647
9648    /**
9649     * Indicates the activation state of this view.
9650     *
9651     * @return true if the view is activated, false otherwise
9652     */
9653    @ViewDebug.ExportedProperty
9654    public boolean isActivated() {
9655        return (mPrivateFlags & ACTIVATED) != 0;
9656    }
9657
9658    /**
9659     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9660     * observer can be used to get notifications when global events, like
9661     * layout, happen.
9662     *
9663     * The returned ViewTreeObserver observer is not guaranteed to remain
9664     * valid for the lifetime of this View. If the caller of this method keeps
9665     * a long-lived reference to ViewTreeObserver, it should always check for
9666     * the return value of {@link ViewTreeObserver#isAlive()}.
9667     *
9668     * @return The ViewTreeObserver for this view's hierarchy.
9669     */
9670    public ViewTreeObserver getViewTreeObserver() {
9671        if (mAttachInfo != null) {
9672            return mAttachInfo.mTreeObserver;
9673        }
9674        if (mFloatingTreeObserver == null) {
9675            mFloatingTreeObserver = new ViewTreeObserver();
9676        }
9677        return mFloatingTreeObserver;
9678    }
9679
9680    /**
9681     * <p>Finds the topmost view in the current view hierarchy.</p>
9682     *
9683     * @return the topmost view containing this view
9684     */
9685    public View getRootView() {
9686        if (mAttachInfo != null) {
9687            final View v = mAttachInfo.mRootView;
9688            if (v != null) {
9689                return v;
9690            }
9691        }
9692
9693        View parent = this;
9694
9695        while (parent.mParent != null && parent.mParent instanceof View) {
9696            parent = (View) parent.mParent;
9697        }
9698
9699        return parent;
9700    }
9701
9702    /**
9703     * <p>Computes the coordinates of this view on the screen. The argument
9704     * must be an array of two integers. After the method returns, the array
9705     * contains the x and y location in that order.</p>
9706     *
9707     * @param location an array of two integers in which to hold the coordinates
9708     */
9709    public void getLocationOnScreen(int[] location) {
9710        getLocationInWindow(location);
9711
9712        final AttachInfo info = mAttachInfo;
9713        if (info != null) {
9714            location[0] += info.mWindowLeft;
9715            location[1] += info.mWindowTop;
9716        }
9717    }
9718
9719    /**
9720     * <p>Computes the coordinates of this view in its window. The argument
9721     * must be an array of two integers. After the method returns, the array
9722     * contains the x and y location in that order.</p>
9723     *
9724     * @param location an array of two integers in which to hold the coordinates
9725     */
9726    public void getLocationInWindow(int[] location) {
9727        if (location == null || location.length < 2) {
9728            throw new IllegalArgumentException("location must be an array of "
9729                    + "two integers");
9730        }
9731
9732        location[0] = mLeft + (int) (mTranslationX + 0.5f);
9733        location[1] = mTop + (int) (mTranslationY + 0.5f);
9734
9735        ViewParent viewParent = mParent;
9736        while (viewParent instanceof View) {
9737            final View view = (View)viewParent;
9738            location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9739            location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
9740            viewParent = view.mParent;
9741        }
9742
9743        if (viewParent instanceof ViewRoot) {
9744            // *cough*
9745            final ViewRoot vr = (ViewRoot)viewParent;
9746            location[1] -= vr.mCurScrollY;
9747        }
9748    }
9749
9750    /**
9751     * {@hide}
9752     * @param id the id of the view to be found
9753     * @return the view of the specified id, null if cannot be found
9754     */
9755    protected View findViewTraversal(int id) {
9756        if (id == mID) {
9757            return this;
9758        }
9759        return null;
9760    }
9761
9762    /**
9763     * {@hide}
9764     * @param tag the tag of the view to be found
9765     * @return the view of specified tag, null if cannot be found
9766     */
9767    protected View findViewWithTagTraversal(Object tag) {
9768        if (tag != null && tag.equals(mTag)) {
9769            return this;
9770        }
9771        return null;
9772    }
9773
9774    /**
9775     * {@hide}
9776     * @param predicate The predicate to evaluate.
9777     * @return The first view that matches the predicate or null.
9778     */
9779    protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9780        if (predicate.apply(this)) {
9781            return this;
9782        }
9783        return null;
9784    }
9785
9786    /**
9787     * Look for a child view with the given id.  If this view has the given
9788     * id, return this view.
9789     *
9790     * @param id The id to search for.
9791     * @return The view that has the given id in the hierarchy or null
9792     */
9793    public final View findViewById(int id) {
9794        if (id < 0) {
9795            return null;
9796        }
9797        return findViewTraversal(id);
9798    }
9799
9800    /**
9801     * Look for a child view with the given tag.  If this view has the given
9802     * tag, return this view.
9803     *
9804     * @param tag The tag to search for, using "tag.equals(getTag())".
9805     * @return The View that has the given tag in the hierarchy or null
9806     */
9807    public final View findViewWithTag(Object tag) {
9808        if (tag == null) {
9809            return null;
9810        }
9811        return findViewWithTagTraversal(tag);
9812    }
9813
9814    /**
9815     * {@hide}
9816     * Look for a child view that matches the specified predicate.
9817     * If this view matches the predicate, return this view.
9818     *
9819     * @param predicate The predicate to evaluate.
9820     * @return The first view that matches the predicate or null.
9821     */
9822    public final View findViewByPredicate(Predicate<View> predicate) {
9823        return findViewByPredicateTraversal(predicate);
9824    }
9825
9826    /**
9827     * Sets the identifier for this view. The identifier does not have to be
9828     * unique in this view's hierarchy. The identifier should be a positive
9829     * number.
9830     *
9831     * @see #NO_ID
9832     * @see #getId
9833     * @see #findViewById
9834     *
9835     * @param id a number used to identify the view
9836     *
9837     * @attr ref android.R.styleable#View_id
9838     */
9839    public void setId(int id) {
9840        mID = id;
9841    }
9842
9843    /**
9844     * {@hide}
9845     *
9846     * @param isRoot true if the view belongs to the root namespace, false
9847     *        otherwise
9848     */
9849    public void setIsRootNamespace(boolean isRoot) {
9850        if (isRoot) {
9851            mPrivateFlags |= IS_ROOT_NAMESPACE;
9852        } else {
9853            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
9854        }
9855    }
9856
9857    /**
9858     * {@hide}
9859     *
9860     * @return true if the view belongs to the root namespace, false otherwise
9861     */
9862    public boolean isRootNamespace() {
9863        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
9864    }
9865
9866    /**
9867     * Returns this view's identifier.
9868     *
9869     * @return a positive integer used to identify the view or {@link #NO_ID}
9870     *         if the view has no ID
9871     *
9872     * @see #setId
9873     * @see #findViewById
9874     * @attr ref android.R.styleable#View_id
9875     */
9876    @ViewDebug.CapturedViewProperty
9877    public int getId() {
9878        return mID;
9879    }
9880
9881    /**
9882     * Returns this view's tag.
9883     *
9884     * @return the Object stored in this view as a tag
9885     *
9886     * @see #setTag(Object)
9887     * @see #getTag(int)
9888     */
9889    @ViewDebug.ExportedProperty
9890    public Object getTag() {
9891        return mTag;
9892    }
9893
9894    /**
9895     * Sets the tag associated with this view. A tag can be used to mark
9896     * a view in its hierarchy and does not have to be unique within the
9897     * hierarchy. Tags can also be used to store data within a view without
9898     * resorting to another data structure.
9899     *
9900     * @param tag an Object to tag the view with
9901     *
9902     * @see #getTag()
9903     * @see #setTag(int, Object)
9904     */
9905    public void setTag(final Object tag) {
9906        mTag = tag;
9907    }
9908
9909    /**
9910     * Returns the tag associated with this view and the specified key.
9911     *
9912     * @param key The key identifying the tag
9913     *
9914     * @return the Object stored in this view as a tag
9915     *
9916     * @see #setTag(int, Object)
9917     * @see #getTag()
9918     */
9919    public Object getTag(int key) {
9920        SparseArray<Object> tags = null;
9921        synchronized (sTagsLock) {
9922            if (sTags != null) {
9923                tags = sTags.get(this);
9924            }
9925        }
9926
9927        if (tags != null) return tags.get(key);
9928        return null;
9929    }
9930
9931    /**
9932     * Sets a tag associated with this view and a key. A tag can be used
9933     * to mark a view in its hierarchy and does not have to be unique within
9934     * the hierarchy. Tags can also be used to store data within a view
9935     * without resorting to another data structure.
9936     *
9937     * The specified key should be an id declared in the resources of the
9938     * application to ensure it is unique (see the <a
9939     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
9940     * Keys identified as belonging to
9941     * the Android framework or not associated with any package will cause
9942     * an {@link IllegalArgumentException} to be thrown.
9943     *
9944     * @param key The key identifying the tag
9945     * @param tag An Object to tag the view with
9946     *
9947     * @throws IllegalArgumentException If they specified key is not valid
9948     *
9949     * @see #setTag(Object)
9950     * @see #getTag(int)
9951     */
9952    public void setTag(int key, final Object tag) {
9953        // If the package id is 0x00 or 0x01, it's either an undefined package
9954        // or a framework id
9955        if ((key >>> 24) < 2) {
9956            throw new IllegalArgumentException("The key must be an application-specific "
9957                    + "resource id.");
9958        }
9959
9960        setTagInternal(this, key, tag);
9961    }
9962
9963    /**
9964     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
9965     * framework id.
9966     *
9967     * @hide
9968     */
9969    public void setTagInternal(int key, Object tag) {
9970        if ((key >>> 24) != 0x1) {
9971            throw new IllegalArgumentException("The key must be a framework-specific "
9972                    + "resource id.");
9973        }
9974
9975        setTagInternal(this, key, tag);
9976    }
9977
9978    private static void setTagInternal(View view, int key, Object tag) {
9979        SparseArray<Object> tags = null;
9980        synchronized (sTagsLock) {
9981            if (sTags == null) {
9982                sTags = new WeakHashMap<View, SparseArray<Object>>();
9983            } else {
9984                tags = sTags.get(view);
9985            }
9986        }
9987
9988        if (tags == null) {
9989            tags = new SparseArray<Object>(2);
9990            synchronized (sTagsLock) {
9991                sTags.put(view, tags);
9992            }
9993        }
9994
9995        tags.put(key, tag);
9996    }
9997
9998    /**
9999     * @param consistency The type of consistency. See ViewDebug for more information.
10000     *
10001     * @hide
10002     */
10003    protected boolean dispatchConsistencyCheck(int consistency) {
10004        return onConsistencyCheck(consistency);
10005    }
10006
10007    /**
10008     * Method that subclasses should implement to check their consistency. The type of
10009     * consistency check is indicated by the bit field passed as a parameter.
10010     *
10011     * @param consistency The type of consistency. See ViewDebug for more information.
10012     *
10013     * @throws IllegalStateException if the view is in an inconsistent state.
10014     *
10015     * @hide
10016     */
10017    protected boolean onConsistencyCheck(int consistency) {
10018        boolean result = true;
10019
10020        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
10021        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
10022
10023        if (checkLayout) {
10024            if (getParent() == null) {
10025                result = false;
10026                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10027                        "View " + this + " does not have a parent.");
10028            }
10029
10030            if (mAttachInfo == null) {
10031                result = false;
10032                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10033                        "View " + this + " is not attached to a window.");
10034            }
10035        }
10036
10037        if (checkDrawing) {
10038            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
10039            // from their draw() method
10040
10041            if ((mPrivateFlags & DRAWN) != DRAWN &&
10042                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
10043                result = false;
10044                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10045                        "View " + this + " was invalidated but its drawing cache is valid.");
10046            }
10047        }
10048
10049        return result;
10050    }
10051
10052    /**
10053     * Prints information about this view in the log output, with the tag
10054     * {@link #VIEW_LOG_TAG}.
10055     *
10056     * @hide
10057     */
10058    public void debug() {
10059        debug(0);
10060    }
10061
10062    /**
10063     * Prints information about this view in the log output, with the tag
10064     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10065     * indentation defined by the <code>depth</code>.
10066     *
10067     * @param depth the indentation level
10068     *
10069     * @hide
10070     */
10071    protected void debug(int depth) {
10072        String output = debugIndent(depth - 1);
10073
10074        output += "+ " + this;
10075        int id = getId();
10076        if (id != -1) {
10077            output += " (id=" + id + ")";
10078        }
10079        Object tag = getTag();
10080        if (tag != null) {
10081            output += " (tag=" + tag + ")";
10082        }
10083        Log.d(VIEW_LOG_TAG, output);
10084
10085        if ((mPrivateFlags & FOCUSED) != 0) {
10086            output = debugIndent(depth) + " FOCUSED";
10087            Log.d(VIEW_LOG_TAG, output);
10088        }
10089
10090        output = debugIndent(depth);
10091        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10092                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10093                + "} ";
10094        Log.d(VIEW_LOG_TAG, output);
10095
10096        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10097                || mPaddingBottom != 0) {
10098            output = debugIndent(depth);
10099            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10100                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10101            Log.d(VIEW_LOG_TAG, output);
10102        }
10103
10104        output = debugIndent(depth);
10105        output += "mMeasureWidth=" + mMeasuredWidth +
10106                " mMeasureHeight=" + mMeasuredHeight;
10107        Log.d(VIEW_LOG_TAG, output);
10108
10109        output = debugIndent(depth);
10110        if (mLayoutParams == null) {
10111            output += "BAD! no layout params";
10112        } else {
10113            output = mLayoutParams.debug(output);
10114        }
10115        Log.d(VIEW_LOG_TAG, output);
10116
10117        output = debugIndent(depth);
10118        output += "flags={";
10119        output += View.printFlags(mViewFlags);
10120        output += "}";
10121        Log.d(VIEW_LOG_TAG, output);
10122
10123        output = debugIndent(depth);
10124        output += "privateFlags={";
10125        output += View.printPrivateFlags(mPrivateFlags);
10126        output += "}";
10127        Log.d(VIEW_LOG_TAG, output);
10128    }
10129
10130    /**
10131     * Creates an string of whitespaces used for indentation.
10132     *
10133     * @param depth the indentation level
10134     * @return a String containing (depth * 2 + 3) * 2 white spaces
10135     *
10136     * @hide
10137     */
10138    protected static String debugIndent(int depth) {
10139        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10140        for (int i = 0; i < (depth * 2) + 3; i++) {
10141            spaces.append(' ').append(' ');
10142        }
10143        return spaces.toString();
10144    }
10145
10146    /**
10147     * <p>Return the offset of the widget's text baseline from the widget's top
10148     * boundary. If this widget does not support baseline alignment, this
10149     * method returns -1. </p>
10150     *
10151     * @return the offset of the baseline within the widget's bounds or -1
10152     *         if baseline alignment is not supported
10153     */
10154    @ViewDebug.ExportedProperty(category = "layout")
10155    public int getBaseline() {
10156        return -1;
10157    }
10158
10159    /**
10160     * Call this when something has changed which has invalidated the
10161     * layout of this view. This will schedule a layout pass of the view
10162     * tree.
10163     */
10164    public void requestLayout() {
10165        if (ViewDebug.TRACE_HIERARCHY) {
10166            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10167        }
10168
10169        mPrivateFlags |= FORCE_LAYOUT;
10170
10171        if (mParent != null && !mParent.isLayoutRequested()) {
10172            mParent.requestLayout();
10173        }
10174    }
10175
10176    /**
10177     * Forces this view to be laid out during the next layout pass.
10178     * This method does not call requestLayout() or forceLayout()
10179     * on the parent.
10180     */
10181    public void forceLayout() {
10182        mPrivateFlags |= FORCE_LAYOUT;
10183    }
10184
10185    /**
10186     * <p>
10187     * This is called to find out how big a view should be. The parent
10188     * supplies constraint information in the width and height parameters.
10189     * </p>
10190     *
10191     * <p>
10192     * The actual mesurement work of a view is performed in
10193     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10194     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10195     * </p>
10196     *
10197     *
10198     * @param widthMeasureSpec Horizontal space requirements as imposed by the
10199     *        parent
10200     * @param heightMeasureSpec Vertical space requirements as imposed by the
10201     *        parent
10202     *
10203     * @see #onMeasure(int, int)
10204     */
10205    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10206        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10207                widthMeasureSpec != mOldWidthMeasureSpec ||
10208                heightMeasureSpec != mOldHeightMeasureSpec) {
10209
10210            // first clears the measured dimension flag
10211            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10212
10213            if (ViewDebug.TRACE_HIERARCHY) {
10214                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10215            }
10216
10217            // measure ourselves, this should set the measured dimension flag back
10218            onMeasure(widthMeasureSpec, heightMeasureSpec);
10219
10220            // flag not set, setMeasuredDimension() was not invoked, we raise
10221            // an exception to warn the developer
10222            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10223                throw new IllegalStateException("onMeasure() did not set the"
10224                        + " measured dimension by calling"
10225                        + " setMeasuredDimension()");
10226            }
10227
10228            mPrivateFlags |= LAYOUT_REQUIRED;
10229        }
10230
10231        mOldWidthMeasureSpec = widthMeasureSpec;
10232        mOldHeightMeasureSpec = heightMeasureSpec;
10233    }
10234
10235    /**
10236     * <p>
10237     * Measure the view and its content to determine the measured width and the
10238     * measured height. This method is invoked by {@link #measure(int, int)} and
10239     * should be overriden by subclasses to provide accurate and efficient
10240     * measurement of their contents.
10241     * </p>
10242     *
10243     * <p>
10244     * <strong>CONTRACT:</strong> When overriding this method, you
10245     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10246     * measured width and height of this view. Failure to do so will trigger an
10247     * <code>IllegalStateException</code>, thrown by
10248     * {@link #measure(int, int)}. Calling the superclass'
10249     * {@link #onMeasure(int, int)} is a valid use.
10250     * </p>
10251     *
10252     * <p>
10253     * The base class implementation of measure defaults to the background size,
10254     * unless a larger size is allowed by the MeasureSpec. Subclasses should
10255     * override {@link #onMeasure(int, int)} to provide better measurements of
10256     * their content.
10257     * </p>
10258     *
10259     * <p>
10260     * If this method is overridden, it is the subclass's responsibility to make
10261     * sure the measured height and width are at least the view's minimum height
10262     * and width ({@link #getSuggestedMinimumHeight()} and
10263     * {@link #getSuggestedMinimumWidth()}).
10264     * </p>
10265     *
10266     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10267     *                         The requirements are encoded with
10268     *                         {@link android.view.View.MeasureSpec}.
10269     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10270     *                         The requirements are encoded with
10271     *                         {@link android.view.View.MeasureSpec}.
10272     *
10273     * @see #getMeasuredWidth()
10274     * @see #getMeasuredHeight()
10275     * @see #setMeasuredDimension(int, int)
10276     * @see #getSuggestedMinimumHeight()
10277     * @see #getSuggestedMinimumWidth()
10278     * @see android.view.View.MeasureSpec#getMode(int)
10279     * @see android.view.View.MeasureSpec#getSize(int)
10280     */
10281    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10282        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10283                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10284    }
10285
10286    /**
10287     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10288     * measured width and measured height. Failing to do so will trigger an
10289     * exception at measurement time.</p>
10290     *
10291     * @param measuredWidth The measured width of this view.  May be a complex
10292     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10293     * {@link #MEASURED_STATE_TOO_SMALL}.
10294     * @param measuredHeight The measured height of this view.  May be a complex
10295     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10296     * {@link #MEASURED_STATE_TOO_SMALL}.
10297     */
10298    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10299        mMeasuredWidth = measuredWidth;
10300        mMeasuredHeight = measuredHeight;
10301
10302        mPrivateFlags |= MEASURED_DIMENSION_SET;
10303    }
10304
10305    /**
10306     * Merge two states as returned by {@link #getMeasuredState()}.
10307     * @param curState The current state as returned from a view or the result
10308     * of combining multiple views.
10309     * @param newState The new view state to combine.
10310     * @return Returns a new integer reflecting the combination of the two
10311     * states.
10312     */
10313    public static int combineMeasuredStates(int curState, int newState) {
10314        return curState | newState;
10315    }
10316
10317    /**
10318     * Version of {@link #resolveSizeAndState(int, int, int)}
10319     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10320     */
10321    public static int resolveSize(int size, int measureSpec) {
10322        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10323    }
10324
10325    /**
10326     * Utility to reconcile a desired size and state, with constraints imposed
10327     * by a MeasureSpec.  Will take the desired size, unless a different size
10328     * is imposed by the constraints.  The returned value is a compound integer,
10329     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10330     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10331     * size is smaller than the size the view wants to be.
10332     *
10333     * @param size How big the view wants to be
10334     * @param measureSpec Constraints imposed by the parent
10335     * @return Size information bit mask as defined by
10336     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10337     */
10338    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
10339        int result = size;
10340        int specMode = MeasureSpec.getMode(measureSpec);
10341        int specSize =  MeasureSpec.getSize(measureSpec);
10342        switch (specMode) {
10343        case MeasureSpec.UNSPECIFIED:
10344            result = size;
10345            break;
10346        case MeasureSpec.AT_MOST:
10347            if (specSize < size) {
10348                result = specSize | MEASURED_STATE_TOO_SMALL;
10349            } else {
10350                result = size;
10351            }
10352            break;
10353        case MeasureSpec.EXACTLY:
10354            result = specSize;
10355            break;
10356        }
10357        return result | (childMeasuredState&MEASURED_STATE_MASK);
10358    }
10359
10360    /**
10361     * Utility to return a default size. Uses the supplied size if the
10362     * MeasureSpec imposed no contraints. Will get larger if allowed
10363     * by the MeasureSpec.
10364     *
10365     * @param size Default size for this view
10366     * @param measureSpec Constraints imposed by the parent
10367     * @return The size this view should be.
10368     */
10369    public static int getDefaultSize(int size, int measureSpec) {
10370        int result = size;
10371        int specMode = MeasureSpec.getMode(measureSpec);
10372        int specSize =  MeasureSpec.getSize(measureSpec);
10373
10374        switch (specMode) {
10375        case MeasureSpec.UNSPECIFIED:
10376            result = size;
10377            break;
10378        case MeasureSpec.AT_MOST:
10379        case MeasureSpec.EXACTLY:
10380            result = specSize;
10381            break;
10382        }
10383        return result;
10384    }
10385
10386    /**
10387     * Returns the suggested minimum height that the view should use. This
10388     * returns the maximum of the view's minimum height
10389     * and the background's minimum height
10390     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10391     * <p>
10392     * When being used in {@link #onMeasure(int, int)}, the caller should still
10393     * ensure the returned height is within the requirements of the parent.
10394     *
10395     * @return The suggested minimum height of the view.
10396     */
10397    protected int getSuggestedMinimumHeight() {
10398        int suggestedMinHeight = mMinHeight;
10399
10400        if (mBGDrawable != null) {
10401            final int bgMinHeight = mBGDrawable.getMinimumHeight();
10402            if (suggestedMinHeight < bgMinHeight) {
10403                suggestedMinHeight = bgMinHeight;
10404            }
10405        }
10406
10407        return suggestedMinHeight;
10408    }
10409
10410    /**
10411     * Returns the suggested minimum width that the view should use. This
10412     * returns the maximum of the view's minimum width)
10413     * and the background's minimum width
10414     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10415     * <p>
10416     * When being used in {@link #onMeasure(int, int)}, the caller should still
10417     * ensure the returned width is within the requirements of the parent.
10418     *
10419     * @return The suggested minimum width of the view.
10420     */
10421    protected int getSuggestedMinimumWidth() {
10422        int suggestedMinWidth = mMinWidth;
10423
10424        if (mBGDrawable != null) {
10425            final int bgMinWidth = mBGDrawable.getMinimumWidth();
10426            if (suggestedMinWidth < bgMinWidth) {
10427                suggestedMinWidth = bgMinWidth;
10428            }
10429        }
10430
10431        return suggestedMinWidth;
10432    }
10433
10434    /**
10435     * Sets the minimum height of the view. It is not guaranteed the view will
10436     * be able to achieve this minimum height (for example, if its parent layout
10437     * constrains it with less available height).
10438     *
10439     * @param minHeight The minimum height the view will try to be.
10440     */
10441    public void setMinimumHeight(int minHeight) {
10442        mMinHeight = minHeight;
10443    }
10444
10445    /**
10446     * Sets the minimum width of the view. It is not guaranteed the view will
10447     * be able to achieve this minimum width (for example, if its parent layout
10448     * constrains it with less available width).
10449     *
10450     * @param minWidth The minimum width the view will try to be.
10451     */
10452    public void setMinimumWidth(int minWidth) {
10453        mMinWidth = minWidth;
10454    }
10455
10456    /**
10457     * Get the animation currently associated with this view.
10458     *
10459     * @return The animation that is currently playing or
10460     *         scheduled to play for this view.
10461     */
10462    public Animation getAnimation() {
10463        return mCurrentAnimation;
10464    }
10465
10466    /**
10467     * Start the specified animation now.
10468     *
10469     * @param animation the animation to start now
10470     */
10471    public void startAnimation(Animation animation) {
10472        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10473        setAnimation(animation);
10474        invalidate();
10475    }
10476
10477    /**
10478     * Cancels any animations for this view.
10479     */
10480    public void clearAnimation() {
10481        if (mCurrentAnimation != null) {
10482            mCurrentAnimation.detach();
10483        }
10484        mCurrentAnimation = null;
10485    }
10486
10487    /**
10488     * Sets the next animation to play for this view.
10489     * If you want the animation to play immediately, use
10490     * startAnimation. This method provides allows fine-grained
10491     * control over the start time and invalidation, but you
10492     * must make sure that 1) the animation has a start time set, and
10493     * 2) the view will be invalidated when the animation is supposed to
10494     * start.
10495     *
10496     * @param animation The next animation, or null.
10497     */
10498    public void setAnimation(Animation animation) {
10499        mCurrentAnimation = animation;
10500        if (animation != null) {
10501            animation.reset();
10502        }
10503    }
10504
10505    /**
10506     * Invoked by a parent ViewGroup to notify the start of the animation
10507     * currently associated with this view. If you override this method,
10508     * always call super.onAnimationStart();
10509     *
10510     * @see #setAnimation(android.view.animation.Animation)
10511     * @see #getAnimation()
10512     */
10513    protected void onAnimationStart() {
10514        mPrivateFlags |= ANIMATION_STARTED;
10515    }
10516
10517    /**
10518     * Invoked by a parent ViewGroup to notify the end of the animation
10519     * currently associated with this view. If you override this method,
10520     * always call super.onAnimationEnd();
10521     *
10522     * @see #setAnimation(android.view.animation.Animation)
10523     * @see #getAnimation()
10524     */
10525    protected void onAnimationEnd() {
10526        mPrivateFlags &= ~ANIMATION_STARTED;
10527    }
10528
10529    /**
10530     * Invoked if there is a Transform that involves alpha. Subclass that can
10531     * draw themselves with the specified alpha should return true, and then
10532     * respect that alpha when their onDraw() is called. If this returns false
10533     * then the view may be redirected to draw into an offscreen buffer to
10534     * fulfill the request, which will look fine, but may be slower than if the
10535     * subclass handles it internally. The default implementation returns false.
10536     *
10537     * @param alpha The alpha (0..255) to apply to the view's drawing
10538     * @return true if the view can draw with the specified alpha.
10539     */
10540    protected boolean onSetAlpha(int alpha) {
10541        return false;
10542    }
10543
10544    /**
10545     * This is used by the RootView to perform an optimization when
10546     * the view hierarchy contains one or several SurfaceView.
10547     * SurfaceView is always considered transparent, but its children are not,
10548     * therefore all View objects remove themselves from the global transparent
10549     * region (passed as a parameter to this function).
10550     *
10551     * @param region The transparent region for this ViewRoot (window).
10552     *
10553     * @return Returns true if the effective visibility of the view at this
10554     * point is opaque, regardless of the transparent region; returns false
10555     * if it is possible for underlying windows to be seen behind the view.
10556     *
10557     * {@hide}
10558     */
10559    public boolean gatherTransparentRegion(Region region) {
10560        final AttachInfo attachInfo = mAttachInfo;
10561        if (region != null && attachInfo != null) {
10562            final int pflags = mPrivateFlags;
10563            if ((pflags & SKIP_DRAW) == 0) {
10564                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10565                // remove it from the transparent region.
10566                final int[] location = attachInfo.mTransparentLocation;
10567                getLocationInWindow(location);
10568                region.op(location[0], location[1], location[0] + mRight - mLeft,
10569                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10570            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10571                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10572                // exists, so we remove the background drawable's non-transparent
10573                // parts from this transparent region.
10574                applyDrawableToTransparentRegion(mBGDrawable, region);
10575            }
10576        }
10577        return true;
10578    }
10579
10580    /**
10581     * Play a sound effect for this view.
10582     *
10583     * <p>The framework will play sound effects for some built in actions, such as
10584     * clicking, but you may wish to play these effects in your widget,
10585     * for instance, for internal navigation.
10586     *
10587     * <p>The sound effect will only be played if sound effects are enabled by the user, and
10588     * {@link #isSoundEffectsEnabled()} is true.
10589     *
10590     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10591     */
10592    public void playSoundEffect(int soundConstant) {
10593        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10594            return;
10595        }
10596        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10597    }
10598
10599    /**
10600     * BZZZTT!!1!
10601     *
10602     * <p>Provide haptic feedback to the user for this view.
10603     *
10604     * <p>The framework will provide haptic feedback for some built in actions,
10605     * such as long presses, but you may wish to provide feedback for your
10606     * own widget.
10607     *
10608     * <p>The feedback will only be performed if
10609     * {@link #isHapticFeedbackEnabled()} is true.
10610     *
10611     * @param feedbackConstant One of the constants defined in
10612     * {@link HapticFeedbackConstants}
10613     */
10614    public boolean performHapticFeedback(int feedbackConstant) {
10615        return performHapticFeedback(feedbackConstant, 0);
10616    }
10617
10618    /**
10619     * BZZZTT!!1!
10620     *
10621     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
10622     *
10623     * @param feedbackConstant One of the constants defined in
10624     * {@link HapticFeedbackConstants}
10625     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10626     */
10627    public boolean performHapticFeedback(int feedbackConstant, int flags) {
10628        if (mAttachInfo == null) {
10629            return false;
10630        }
10631        //noinspection SimplifiableIfStatement
10632        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
10633                && !isHapticFeedbackEnabled()) {
10634            return false;
10635        }
10636        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10637                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
10638    }
10639
10640    /**
10641     * !!! TODO: real docs
10642     *
10643     * The base class implementation makes the shadow the same size and appearance
10644     * as the view itself, and positions it with its center at the touch point.
10645     */
10646    public static class DragShadowBuilder {
10647        private final WeakReference<View> mView;
10648
10649        /**
10650         * Construct a shadow builder object for use with the given View object.  The
10651         * default implementation will construct a drag shadow the same size and
10652         * appearance as the supplied View.
10653         *
10654         * @param view A view within the application's layout whose appearance
10655         *        should be replicated as the drag shadow.
10656         */
10657        public DragShadowBuilder(View view) {
10658            mView = new WeakReference<View>(view);
10659        }
10660
10661        /**
10662         * Construct a shadow builder object with no associated View.  This
10663         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
10664         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
10665         * to supply the drag shadow's dimensions and appearance without
10666         * reference to any View object.
10667         */
10668        public DragShadowBuilder() {
10669            mView = new WeakReference<View>(null);
10670        }
10671
10672        /**
10673         * Returns the View object that had been passed to the
10674         * {@link #View.DragShadowBuilder(View)}
10675         * constructor.  If that View parameter was {@code null} or if the
10676         * {@link #View.DragShadowBuilder()}
10677         * constructor was used to instantiate the builder object, this method will return
10678         * null.
10679         *
10680         * @return The View object associate with this builder object.
10681         */
10682        final public View getView() {
10683            return mView.get();
10684        }
10685
10686        /**
10687         * Provide the draggable-shadow metrics for the operation: the dimensions of
10688         * the shadow image itself, and the point within that shadow that should
10689         * be centered under the touch location while dragging.
10690         * <p>
10691         * The default implementation sets the dimensions of the shadow to be the
10692         * same as the dimensions of the View object that had been supplied to the
10693         * {@link #View.DragShadowBuilder(View)} constructor
10694         * when the builder object was instantiated, and centers the shadow under the touch
10695         * point.
10696         *
10697         * @param shadowSize The application should set the {@code x} member of this
10698         *        parameter to the desired shadow width, and the {@code y} member to
10699         *        the desired height.
10700         * @param shadowTouchPoint The application should set this point to be the
10701         *        location within the shadow that should track directly underneath
10702         *        the touch point on the screen during a drag.
10703         */
10704        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
10705            final View view = mView.get();
10706            if (view != null) {
10707                shadowSize.set(view.getWidth(), view.getHeight());
10708                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
10709            } else {
10710                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10711            }
10712        }
10713
10714        /**
10715         * Draw the shadow image for the upcoming drag.  The shadow canvas was
10716         * created with the dimensions supplied by the
10717         * {@link #onProvideShadowMetrics(Point, Point)} callback.
10718         * <p>
10719         * The default implementation replicates the appearance of the View object
10720         * that had been supplied to the
10721         * {@link #View.DragShadowBuilder(View)}
10722         * constructor when the builder object was instantiated.
10723         *
10724         * @param canvas
10725         */
10726        public void onDrawShadow(Canvas canvas) {
10727            final View view = mView.get();
10728            if (view != null) {
10729                view.draw(canvas);
10730            } else {
10731                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
10732            }
10733        }
10734    }
10735
10736    /**
10737     * Drag and drop.  App calls startDrag(), then callbacks to the shadow builder's
10738     * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10739     * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
10740     * operation is handed over to the OS.
10741     * !!! TODO: real docs
10742     *
10743     * @param data !!! TODO
10744     * @param shadowBuilder !!! TODO
10745     * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10746     *     delivered to the calling application during the course of the current drag operation.
10747     *     This object is private to the application that called startDrag(), and is not
10748     *     visible to other applications. It provides a lightweight way for the application to
10749     *     propagate information from the initiator to the recipient of a drag within its own
10750     *     application; for example, to help disambiguate between 'copy' and 'move' semantics.
10751     * @param flags Flags affecting the drag operation.  At present no flags are defined;
10752     *     pass 0 for this parameter.
10753     * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10754     *     an error prevented the drag from taking place.
10755     */
10756    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
10757            Object myLocalState, int flags) {
10758        if (ViewDebug.DEBUG_DRAG) {
10759            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
10760        }
10761        boolean okay = false;
10762
10763        Point shadowSize = new Point();
10764        Point shadowTouchPoint = new Point();
10765        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
10766
10767        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10768                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10769            throw new IllegalStateException("Drag shadow dimensions must not be negative");
10770        }
10771
10772        if (ViewDebug.DEBUG_DRAG) {
10773            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10774                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
10775        }
10776        Surface surface = new Surface();
10777        try {
10778            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
10779                    flags, shadowSize.x, shadowSize.y, surface);
10780            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
10781                    + " surface=" + surface);
10782            if (token != null) {
10783                Canvas canvas = surface.lockCanvas(null);
10784                try {
10785                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
10786                    shadowBuilder.onDrawShadow(canvas);
10787                } finally {
10788                    surface.unlockCanvasAndPost(canvas);
10789                }
10790
10791                final ViewRoot root = getViewRoot();
10792
10793                // Cache the local state object for delivery with DragEvents
10794                root.setLocalDragState(myLocalState);
10795
10796                // repurpose 'shadowSize' for the last touch point
10797                root.getLastTouchPoint(shadowSize);
10798
10799                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
10800                        shadowSize.x, shadowSize.y,
10801                        shadowTouchPoint.x, shadowTouchPoint.y, data);
10802                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
10803            }
10804        } catch (Exception e) {
10805            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
10806            surface.destroy();
10807        }
10808
10809        return okay;
10810    }
10811
10812    /**
10813     * Drag-and-drop event dispatch.  The event.getAction() verb is one of the DragEvent
10814     * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
10815     *
10816     * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
10817     * being dragged.  onDragEvent() should return 'true' if the view can handle
10818     * a drop of that content.  A view that returns 'false' here will receive no
10819     * further calls to onDragEvent() about the drag/drop operation.
10820     *
10821     * For DRAG_ENTERED, event.getClipDescription() describes the content being
10822     * dragged.  This will be the same content description passed in the
10823     * DRAG_STARTED_EVENT invocation.
10824     *
10825     * For DRAG_EXITED, event.getClipDescription() describes the content being
10826     * dragged.  This will be the same content description passed in the
10827     * DRAG_STARTED_EVENT invocation.  The view should return to its approriate
10828     * drag-acceptance visual state.
10829     *
10830     * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
10831     * coordinates of the current drag point.  The view must return 'true' if it
10832     * can accept a drop of the current drag content, false otherwise.
10833     *
10834     * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
10835     * within the view; also, event.getClipData() returns the full data payload
10836     * being dropped.  The view should return 'true' if it consumed the dropped
10837     * content, 'false' if it did not.
10838     *
10839     * For DRAG_ENDED_EVENT, the 'event' argument may be null.  The view should return
10840     * to its normal visual state.
10841     */
10842    public boolean onDragEvent(DragEvent event) {
10843        return false;
10844    }
10845
10846    /**
10847     * Views typically don't need to override dispatchDragEvent(); it just calls
10848     * onDragEvent(event) and passes the result up appropriately.
10849     */
10850    public boolean dispatchDragEvent(DragEvent event) {
10851        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
10852                && mOnDragListener.onDrag(this, event)) {
10853            return true;
10854        }
10855        return onDragEvent(event);
10856    }
10857
10858    /**
10859     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
10860     * it is ever exposed at all.
10861     * @hide
10862     */
10863    public void onCloseSystemDialogs(String reason) {
10864    }
10865
10866    /**
10867     * Given a Drawable whose bounds have been set to draw into this view,
10868     * update a Region being computed for {@link #gatherTransparentRegion} so
10869     * that any non-transparent parts of the Drawable are removed from the
10870     * given transparent region.
10871     *
10872     * @param dr The Drawable whose transparency is to be applied to the region.
10873     * @param region A Region holding the current transparency information,
10874     * where any parts of the region that are set are considered to be
10875     * transparent.  On return, this region will be modified to have the
10876     * transparency information reduced by the corresponding parts of the
10877     * Drawable that are not transparent.
10878     * {@hide}
10879     */
10880    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
10881        if (DBG) {
10882            Log.i("View", "Getting transparent region for: " + this);
10883        }
10884        final Region r = dr.getTransparentRegion();
10885        final Rect db = dr.getBounds();
10886        final AttachInfo attachInfo = mAttachInfo;
10887        if (r != null && attachInfo != null) {
10888            final int w = getRight()-getLeft();
10889            final int h = getBottom()-getTop();
10890            if (db.left > 0) {
10891                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
10892                r.op(0, 0, db.left, h, Region.Op.UNION);
10893            }
10894            if (db.right < w) {
10895                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
10896                r.op(db.right, 0, w, h, Region.Op.UNION);
10897            }
10898            if (db.top > 0) {
10899                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
10900                r.op(0, 0, w, db.top, Region.Op.UNION);
10901            }
10902            if (db.bottom < h) {
10903                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
10904                r.op(0, db.bottom, w, h, Region.Op.UNION);
10905            }
10906            final int[] location = attachInfo.mTransparentLocation;
10907            getLocationInWindow(location);
10908            r.translate(location[0], location[1]);
10909            region.op(r, Region.Op.INTERSECT);
10910        } else {
10911            region.op(db, Region.Op.DIFFERENCE);
10912        }
10913    }
10914
10915    private void postCheckForLongClick(int delayOffset) {
10916        mHasPerformedLongPress = false;
10917
10918        if (mPendingCheckForLongPress == null) {
10919            mPendingCheckForLongPress = new CheckForLongPress();
10920        }
10921        mPendingCheckForLongPress.rememberWindowAttachCount();
10922        postDelayed(mPendingCheckForLongPress,
10923                ViewConfiguration.getLongPressTimeout() - delayOffset);
10924    }
10925
10926    /**
10927     * Inflate a view from an XML resource.  This convenience method wraps the {@link
10928     * LayoutInflater} class, which provides a full range of options for view inflation.
10929     *
10930     * @param context The Context object for your activity or application.
10931     * @param resource The resource ID to inflate
10932     * @param root A view group that will be the parent.  Used to properly inflate the
10933     * layout_* parameters.
10934     * @see LayoutInflater
10935     */
10936    public static View inflate(Context context, int resource, ViewGroup root) {
10937        LayoutInflater factory = LayoutInflater.from(context);
10938        return factory.inflate(resource, root);
10939    }
10940
10941    /**
10942     * Scroll the view with standard behavior for scrolling beyond the normal
10943     * content boundaries. Views that call this method should override
10944     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
10945     * results of an over-scroll operation.
10946     *
10947     * Views can use this method to handle any touch or fling-based scrolling.
10948     *
10949     * @param deltaX Change in X in pixels
10950     * @param deltaY Change in Y in pixels
10951     * @param scrollX Current X scroll value in pixels before applying deltaX
10952     * @param scrollY Current Y scroll value in pixels before applying deltaY
10953     * @param scrollRangeX Maximum content scroll range along the X axis
10954     * @param scrollRangeY Maximum content scroll range along the Y axis
10955     * @param maxOverScrollX Number of pixels to overscroll by in either direction
10956     *          along the X axis.
10957     * @param maxOverScrollY Number of pixels to overscroll by in either direction
10958     *          along the Y axis.
10959     * @param isTouchEvent true if this scroll operation is the result of a touch event.
10960     * @return true if scrolling was clamped to an over-scroll boundary along either
10961     *          axis, false otherwise.
10962     */
10963    protected boolean overScrollBy(int deltaX, int deltaY,
10964            int scrollX, int scrollY,
10965            int scrollRangeX, int scrollRangeY,
10966            int maxOverScrollX, int maxOverScrollY,
10967            boolean isTouchEvent) {
10968        final int overScrollMode = mOverScrollMode;
10969        final boolean canScrollHorizontal =
10970                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
10971        final boolean canScrollVertical =
10972                computeVerticalScrollRange() > computeVerticalScrollExtent();
10973        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
10974                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
10975        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
10976                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
10977
10978        int newScrollX = scrollX + deltaX;
10979        if (!overScrollHorizontal) {
10980            maxOverScrollX = 0;
10981        }
10982
10983        int newScrollY = scrollY + deltaY;
10984        if (!overScrollVertical) {
10985            maxOverScrollY = 0;
10986        }
10987
10988        // Clamp values if at the limits and record
10989        final int left = -maxOverScrollX;
10990        final int right = maxOverScrollX + scrollRangeX;
10991        final int top = -maxOverScrollY;
10992        final int bottom = maxOverScrollY + scrollRangeY;
10993
10994        boolean clampedX = false;
10995        if (newScrollX > right) {
10996            newScrollX = right;
10997            clampedX = true;
10998        } else if (newScrollX < left) {
10999            newScrollX = left;
11000            clampedX = true;
11001        }
11002
11003        boolean clampedY = false;
11004        if (newScrollY > bottom) {
11005            newScrollY = bottom;
11006            clampedY = true;
11007        } else if (newScrollY < top) {
11008            newScrollY = top;
11009            clampedY = true;
11010        }
11011
11012        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
11013
11014        return clampedX || clampedY;
11015    }
11016
11017    /**
11018     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
11019     * respond to the results of an over-scroll operation.
11020     *
11021     * @param scrollX New X scroll value in pixels
11022     * @param scrollY New Y scroll value in pixels
11023     * @param clampedX True if scrollX was clamped to an over-scroll boundary
11024     * @param clampedY True if scrollY was clamped to an over-scroll boundary
11025     */
11026    protected void onOverScrolled(int scrollX, int scrollY,
11027            boolean clampedX, boolean clampedY) {
11028        // Intentionally empty.
11029    }
11030
11031    /**
11032     * Returns the over-scroll mode for this view. The result will be
11033     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11034     * (allow over-scrolling only if the view content is larger than the container),
11035     * or {@link #OVER_SCROLL_NEVER}.
11036     *
11037     * @return This view's over-scroll mode.
11038     */
11039    public int getOverScrollMode() {
11040        return mOverScrollMode;
11041    }
11042
11043    /**
11044     * Set the over-scroll mode for this view. Valid over-scroll modes are
11045     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11046     * (allow over-scrolling only if the view content is larger than the container),
11047     * or {@link #OVER_SCROLL_NEVER}.
11048     *
11049     * Setting the over-scroll mode of a view will have an effect only if the
11050     * view is capable of scrolling.
11051     *
11052     * @param overScrollMode The new over-scroll mode for this view.
11053     */
11054    public void setOverScrollMode(int overScrollMode) {
11055        if (overScrollMode != OVER_SCROLL_ALWAYS &&
11056                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
11057                overScrollMode != OVER_SCROLL_NEVER) {
11058            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
11059        }
11060        mOverScrollMode = overScrollMode;
11061    }
11062
11063    /**
11064     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
11065     * Each MeasureSpec represents a requirement for either the width or the height.
11066     * A MeasureSpec is comprised of a size and a mode. There are three possible
11067     * modes:
11068     * <dl>
11069     * <dt>UNSPECIFIED</dt>
11070     * <dd>
11071     * The parent has not imposed any constraint on the child. It can be whatever size
11072     * it wants.
11073     * </dd>
11074     *
11075     * <dt>EXACTLY</dt>
11076     * <dd>
11077     * The parent has determined an exact size for the child. The child is going to be
11078     * given those bounds regardless of how big it wants to be.
11079     * </dd>
11080     *
11081     * <dt>AT_MOST</dt>
11082     * <dd>
11083     * The child can be as large as it wants up to the specified size.
11084     * </dd>
11085     * </dl>
11086     *
11087     * MeasureSpecs are implemented as ints to reduce object allocation. This class
11088     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11089     */
11090    public static class MeasureSpec {
11091        private static final int MODE_SHIFT = 30;
11092        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
11093
11094        /**
11095         * Measure specification mode: The parent has not imposed any constraint
11096         * on the child. It can be whatever size it wants.
11097         */
11098        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11099
11100        /**
11101         * Measure specification mode: The parent has determined an exact size
11102         * for the child. The child is going to be given those bounds regardless
11103         * of how big it wants to be.
11104         */
11105        public static final int EXACTLY     = 1 << MODE_SHIFT;
11106
11107        /**
11108         * Measure specification mode: The child can be as large as it wants up
11109         * to the specified size.
11110         */
11111        public static final int AT_MOST     = 2 << MODE_SHIFT;
11112
11113        /**
11114         * Creates a measure specification based on the supplied size and mode.
11115         *
11116         * The mode must always be one of the following:
11117         * <ul>
11118         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11119         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11120         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11121         * </ul>
11122         *
11123         * @param size the size of the measure specification
11124         * @param mode the mode of the measure specification
11125         * @return the measure specification based on size and mode
11126         */
11127        public static int makeMeasureSpec(int size, int mode) {
11128            return size + mode;
11129        }
11130
11131        /**
11132         * Extracts the mode from the supplied measure specification.
11133         *
11134         * @param measureSpec the measure specification to extract the mode from
11135         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11136         *         {@link android.view.View.MeasureSpec#AT_MOST} or
11137         *         {@link android.view.View.MeasureSpec#EXACTLY}
11138         */
11139        public static int getMode(int measureSpec) {
11140            return (measureSpec & MODE_MASK);
11141        }
11142
11143        /**
11144         * Extracts the size from the supplied measure specification.
11145         *
11146         * @param measureSpec the measure specification to extract the size from
11147         * @return the size in pixels defined in the supplied measure specification
11148         */
11149        public static int getSize(int measureSpec) {
11150            return (measureSpec & ~MODE_MASK);
11151        }
11152
11153        /**
11154         * Returns a String representation of the specified measure
11155         * specification.
11156         *
11157         * @param measureSpec the measure specification to convert to a String
11158         * @return a String with the following format: "MeasureSpec: MODE SIZE"
11159         */
11160        public static String toString(int measureSpec) {
11161            int mode = getMode(measureSpec);
11162            int size = getSize(measureSpec);
11163
11164            StringBuilder sb = new StringBuilder("MeasureSpec: ");
11165
11166            if (mode == UNSPECIFIED)
11167                sb.append("UNSPECIFIED ");
11168            else if (mode == EXACTLY)
11169                sb.append("EXACTLY ");
11170            else if (mode == AT_MOST)
11171                sb.append("AT_MOST ");
11172            else
11173                sb.append(mode).append(" ");
11174
11175            sb.append(size);
11176            return sb.toString();
11177        }
11178    }
11179
11180    class CheckForLongPress implements Runnable {
11181
11182        private int mOriginalWindowAttachCount;
11183
11184        public void run() {
11185            if (isPressed() && (mParent != null)
11186                    && mOriginalWindowAttachCount == mWindowAttachCount) {
11187                if (performLongClick()) {
11188                    mHasPerformedLongPress = true;
11189                }
11190            }
11191        }
11192
11193        public void rememberWindowAttachCount() {
11194            mOriginalWindowAttachCount = mWindowAttachCount;
11195        }
11196    }
11197
11198    private final class CheckForTap implements Runnable {
11199        public void run() {
11200            mPrivateFlags &= ~PREPRESSED;
11201            mPrivateFlags |= PRESSED;
11202            refreshDrawableState();
11203            if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11204                postCheckForLongClick(ViewConfiguration.getTapTimeout());
11205            }
11206        }
11207    }
11208
11209    private final class PerformClick implements Runnable {
11210        public void run() {
11211            performClick();
11212        }
11213    }
11214
11215    /**
11216     * Interface definition for a callback to be invoked when a key event is
11217     * dispatched to this view. The callback will be invoked before the key
11218     * event is given to the view.
11219     */
11220    public interface OnKeyListener {
11221        /**
11222         * Called when a key is dispatched to a view. This allows listeners to
11223         * get a chance to respond before the target view.
11224         *
11225         * @param v The view the key has been dispatched to.
11226         * @param keyCode The code for the physical key that was pressed
11227         * @param event The KeyEvent object containing full information about
11228         *        the event.
11229         * @return True if the listener has consumed the event, false otherwise.
11230         */
11231        boolean onKey(View v, int keyCode, KeyEvent event);
11232    }
11233
11234    /**
11235     * Interface definition for a callback to be invoked when a touch event is
11236     * dispatched to this view. The callback will be invoked before the touch
11237     * event is given to the view.
11238     */
11239    public interface OnTouchListener {
11240        /**
11241         * Called when a touch event is dispatched to a view. This allows listeners to
11242         * get a chance to respond before the target view.
11243         *
11244         * @param v The view the touch event has been dispatched to.
11245         * @param event The MotionEvent object containing full information about
11246         *        the event.
11247         * @return True if the listener has consumed the event, false otherwise.
11248         */
11249        boolean onTouch(View v, MotionEvent event);
11250    }
11251
11252    /**
11253     * Interface definition for a callback to be invoked when a view has been clicked and held.
11254     */
11255    public interface OnLongClickListener {
11256        /**
11257         * Called when a view has been clicked and held.
11258         *
11259         * @param v The view that was clicked and held.
11260         *
11261         * @return true if the callback consumed the long click, false otherwise.
11262         */
11263        boolean onLongClick(View v);
11264    }
11265
11266    /**
11267     * Interface definition for a callback to be invoked when a drag is being dispatched
11268     * to this view.  The callback will be invoked before the hosting view's own
11269     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
11270     * onDrag(event) behavior, it should return 'false' from this callback.
11271     */
11272    public interface OnDragListener {
11273        /**
11274         * Called when a drag event is dispatched to a view. This allows listeners
11275         * to get a chance to override base View behavior.
11276         *
11277         * @param v The view the drag has been dispatched to.
11278         * @param event The DragEvent object containing full information
11279         *        about the event.
11280         * @return true if the listener consumed the DragEvent, false in order to fall
11281         *         back to the view's default handling.
11282         */
11283        boolean onDrag(View v, DragEvent event);
11284    }
11285
11286    /**
11287     * Interface definition for a callback to be invoked when the focus state of
11288     * a view changed.
11289     */
11290    public interface OnFocusChangeListener {
11291        /**
11292         * Called when the focus state of a view has changed.
11293         *
11294         * @param v The view whose state has changed.
11295         * @param hasFocus The new focus state of v.
11296         */
11297        void onFocusChange(View v, boolean hasFocus);
11298    }
11299
11300    /**
11301     * Interface definition for a callback to be invoked when a view is clicked.
11302     */
11303    public interface OnClickListener {
11304        /**
11305         * Called when a view has been clicked.
11306         *
11307         * @param v The view that was clicked.
11308         */
11309        void onClick(View v);
11310    }
11311
11312    /**
11313     * Interface definition for a callback to be invoked when the context menu
11314     * for this view is being built.
11315     */
11316    public interface OnCreateContextMenuListener {
11317        /**
11318         * Called when the context menu for this view is being built. It is not
11319         * safe to hold onto the menu after this method returns.
11320         *
11321         * @param menu The context menu that is being built
11322         * @param v The view for which the context menu is being built
11323         * @param menuInfo Extra information about the item for which the
11324         *            context menu should be shown. This information will vary
11325         *            depending on the class of v.
11326         */
11327        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11328    }
11329
11330    private final class UnsetPressedState implements Runnable {
11331        public void run() {
11332            setPressed(false);
11333        }
11334    }
11335
11336    /**
11337     * Base class for derived classes that want to save and restore their own
11338     * state in {@link android.view.View#onSaveInstanceState()}.
11339     */
11340    public static class BaseSavedState extends AbsSavedState {
11341        /**
11342         * Constructor used when reading from a parcel. Reads the state of the superclass.
11343         *
11344         * @param source
11345         */
11346        public BaseSavedState(Parcel source) {
11347            super(source);
11348        }
11349
11350        /**
11351         * Constructor called by derived classes when creating their SavedState objects
11352         *
11353         * @param superState The state of the superclass of this view
11354         */
11355        public BaseSavedState(Parcelable superState) {
11356            super(superState);
11357        }
11358
11359        public static final Parcelable.Creator<BaseSavedState> CREATOR =
11360                new Parcelable.Creator<BaseSavedState>() {
11361            public BaseSavedState createFromParcel(Parcel in) {
11362                return new BaseSavedState(in);
11363            }
11364
11365            public BaseSavedState[] newArray(int size) {
11366                return new BaseSavedState[size];
11367            }
11368        };
11369    }
11370
11371    /**
11372     * A set of information given to a view when it is attached to its parent
11373     * window.
11374     */
11375    static class AttachInfo {
11376        interface Callbacks {
11377            void playSoundEffect(int effectId);
11378            boolean performHapticFeedback(int effectId, boolean always);
11379        }
11380
11381        /**
11382         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11383         * to a Handler. This class contains the target (View) to invalidate and
11384         * the coordinates of the dirty rectangle.
11385         *
11386         * For performance purposes, this class also implements a pool of up to
11387         * POOL_LIMIT objects that get reused. This reduces memory allocations
11388         * whenever possible.
11389         */
11390        static class InvalidateInfo implements Poolable<InvalidateInfo> {
11391            private static final int POOL_LIMIT = 10;
11392            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11393                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
11394                        public InvalidateInfo newInstance() {
11395                            return new InvalidateInfo();
11396                        }
11397
11398                        public void onAcquired(InvalidateInfo element) {
11399                        }
11400
11401                        public void onReleased(InvalidateInfo element) {
11402                        }
11403                    }, POOL_LIMIT)
11404            );
11405
11406            private InvalidateInfo mNext;
11407
11408            View target;
11409
11410            int left;
11411            int top;
11412            int right;
11413            int bottom;
11414
11415            public void setNextPoolable(InvalidateInfo element) {
11416                mNext = element;
11417            }
11418
11419            public InvalidateInfo getNextPoolable() {
11420                return mNext;
11421            }
11422
11423            static InvalidateInfo acquire() {
11424                return sPool.acquire();
11425            }
11426
11427            void release() {
11428                sPool.release(this);
11429            }
11430        }
11431
11432        final IWindowSession mSession;
11433
11434        final IWindow mWindow;
11435
11436        final IBinder mWindowToken;
11437
11438        final Callbacks mRootCallbacks;
11439
11440        /**
11441         * The top view of the hierarchy.
11442         */
11443        View mRootView;
11444
11445        IBinder mPanelParentWindowToken;
11446        Surface mSurface;
11447
11448        boolean mHardwareAccelerated;
11449        boolean mHardwareAccelerationRequested;
11450        HardwareRenderer mHardwareRenderer;
11451
11452        /**
11453         * Scale factor used by the compatibility mode
11454         */
11455        float mApplicationScale;
11456
11457        /**
11458         * Indicates whether the application is in compatibility mode
11459         */
11460        boolean mScalingRequired;
11461
11462        /**
11463         * Left position of this view's window
11464         */
11465        int mWindowLeft;
11466
11467        /**
11468         * Top position of this view's window
11469         */
11470        int mWindowTop;
11471
11472        /**
11473         * Indicates whether views need to use 32-bit drawing caches
11474         */
11475        boolean mUse32BitDrawingCache;
11476
11477        /**
11478         * For windows that are full-screen but using insets to layout inside
11479         * of the screen decorations, these are the current insets for the
11480         * content of the window.
11481         */
11482        final Rect mContentInsets = new Rect();
11483
11484        /**
11485         * For windows that are full-screen but using insets to layout inside
11486         * of the screen decorations, these are the current insets for the
11487         * actual visible parts of the window.
11488         */
11489        final Rect mVisibleInsets = new Rect();
11490
11491        /**
11492         * The internal insets given by this window.  This value is
11493         * supplied by the client (through
11494         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11495         * be given to the window manager when changed to be used in laying
11496         * out windows behind it.
11497         */
11498        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11499                = new ViewTreeObserver.InternalInsetsInfo();
11500
11501        /**
11502         * All views in the window's hierarchy that serve as scroll containers,
11503         * used to determine if the window can be resized or must be panned
11504         * to adjust for a soft input area.
11505         */
11506        final ArrayList<View> mScrollContainers = new ArrayList<View>();
11507
11508        final KeyEvent.DispatcherState mKeyDispatchState
11509                = new KeyEvent.DispatcherState();
11510
11511        /**
11512         * Indicates whether the view's window currently has the focus.
11513         */
11514        boolean mHasWindowFocus;
11515
11516        /**
11517         * The current visibility of the window.
11518         */
11519        int mWindowVisibility;
11520
11521        /**
11522         * Indicates the time at which drawing started to occur.
11523         */
11524        long mDrawingTime;
11525
11526        /**
11527         * Indicates whether or not ignoring the DIRTY_MASK flags.
11528         */
11529        boolean mIgnoreDirtyState;
11530
11531        /**
11532         * Indicates whether the view's window is currently in touch mode.
11533         */
11534        boolean mInTouchMode;
11535
11536        /**
11537         * Indicates that ViewRoot should trigger a global layout change
11538         * the next time it performs a traversal
11539         */
11540        boolean mRecomputeGlobalAttributes;
11541
11542        /**
11543         * Set during a traveral if any views want to keep the screen on.
11544         */
11545        boolean mKeepScreenOn;
11546
11547        /**
11548         * Set if the visibility of any views has changed.
11549         */
11550        boolean mViewVisibilityChanged;
11551
11552        /**
11553         * Set to true if a view has been scrolled.
11554         */
11555        boolean mViewScrollChanged;
11556
11557        /**
11558         * Global to the view hierarchy used as a temporary for dealing with
11559         * x/y points in the transparent region computations.
11560         */
11561        final int[] mTransparentLocation = new int[2];
11562
11563        /**
11564         * Global to the view hierarchy used as a temporary for dealing with
11565         * x/y points in the ViewGroup.invalidateChild implementation.
11566         */
11567        final int[] mInvalidateChildLocation = new int[2];
11568
11569
11570        /**
11571         * Global to the view hierarchy used as a temporary for dealing with
11572         * x/y location when view is transformed.
11573         */
11574        final float[] mTmpTransformLocation = new float[2];
11575
11576        /**
11577         * The view tree observer used to dispatch global events like
11578         * layout, pre-draw, touch mode change, etc.
11579         */
11580        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11581
11582        /**
11583         * A Canvas used by the view hierarchy to perform bitmap caching.
11584         */
11585        Canvas mCanvas;
11586
11587        /**
11588         * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11589         * handler can be used to pump events in the UI events queue.
11590         */
11591        final Handler mHandler;
11592
11593        /**
11594         * Identifier for messages requesting the view to be invalidated.
11595         * Such messages should be sent to {@link #mHandler}.
11596         */
11597        static final int INVALIDATE_MSG = 0x1;
11598
11599        /**
11600         * Identifier for messages requesting the view to invalidate a region.
11601         * Such messages should be sent to {@link #mHandler}.
11602         */
11603        static final int INVALIDATE_RECT_MSG = 0x2;
11604
11605        /**
11606         * Temporary for use in computing invalidate rectangles while
11607         * calling up the hierarchy.
11608         */
11609        final Rect mTmpInvalRect = new Rect();
11610
11611        /**
11612         * Temporary for use in computing hit areas with transformed views
11613         */
11614        final RectF mTmpTransformRect = new RectF();
11615
11616        /**
11617         * Temporary list for use in collecting focusable descendents of a view.
11618         */
11619        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11620
11621        /**
11622         * Creates a new set of attachment information with the specified
11623         * events handler and thread.
11624         *
11625         * @param handler the events handler the view must use
11626         */
11627        AttachInfo(IWindowSession session, IWindow window,
11628                Handler handler, Callbacks effectPlayer) {
11629            mSession = session;
11630            mWindow = window;
11631            mWindowToken = window.asBinder();
11632            mHandler = handler;
11633            mRootCallbacks = effectPlayer;
11634        }
11635    }
11636
11637    /**
11638     * <p>ScrollabilityCache holds various fields used by a View when scrolling
11639     * is supported. This avoids keeping too many unused fields in most
11640     * instances of View.</p>
11641     */
11642    private static class ScrollabilityCache implements Runnable {
11643
11644        /**
11645         * Scrollbars are not visible
11646         */
11647        public static final int OFF = 0;
11648
11649        /**
11650         * Scrollbars are visible
11651         */
11652        public static final int ON = 1;
11653
11654        /**
11655         * Scrollbars are fading away
11656         */
11657        public static final int FADING = 2;
11658
11659        public boolean fadeScrollBars;
11660
11661        public int fadingEdgeLength;
11662        public int scrollBarDefaultDelayBeforeFade;
11663        public int scrollBarFadeDuration;
11664
11665        public int scrollBarSize;
11666        public ScrollBarDrawable scrollBar;
11667        public float[] interpolatorValues;
11668        public View host;
11669
11670        public final Paint paint;
11671        public final Matrix matrix;
11672        public Shader shader;
11673
11674        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11675
11676        private static final float[] OPAQUE = { 255 };
11677        private static final float[] TRANSPARENT = { 0.0f };
11678
11679        /**
11680         * When fading should start. This time moves into the future every time
11681         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11682         */
11683        public long fadeStartTime;
11684
11685
11686        /**
11687         * The current state of the scrollbars: ON, OFF, or FADING
11688         */
11689        public int state = OFF;
11690
11691        private int mLastColor;
11692
11693        public ScrollabilityCache(ViewConfiguration configuration, View host) {
11694            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11695            scrollBarSize = configuration.getScaledScrollBarSize();
11696            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11697            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
11698
11699            paint = new Paint();
11700            matrix = new Matrix();
11701            // use use a height of 1, and then wack the matrix each time we
11702            // actually use it.
11703            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
11704
11705            paint.setShader(shader);
11706            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
11707            this.host = host;
11708        }
11709
11710        public void setFadeColor(int color) {
11711            if (color != 0 && color != mLastColor) {
11712                mLastColor = color;
11713                color |= 0xFF000000;
11714
11715                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11716                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
11717
11718                paint.setShader(shader);
11719                // Restore the default transfer mode (src_over)
11720                paint.setXfermode(null);
11721            }
11722        }
11723
11724        public void run() {
11725            long now = AnimationUtils.currentAnimationTimeMillis();
11726            if (now >= fadeStartTime) {
11727
11728                // the animation fades the scrollbars out by changing
11729                // the opacity (alpha) from fully opaque to fully
11730                // transparent
11731                int nextFrame = (int) now;
11732                int framesCount = 0;
11733
11734                Interpolator interpolator = scrollBarInterpolator;
11735
11736                // Start opaque
11737                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
11738
11739                // End transparent
11740                nextFrame += scrollBarFadeDuration;
11741                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
11742
11743                state = FADING;
11744
11745                // Kick off the fade animation
11746                host.invalidate();
11747            }
11748        }
11749
11750    }
11751}
11752