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