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