View.java revision b05aacc1aea4eb7dec3126c88fd53680fb8765cc
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            if (p != null && ai != null && ai.mHardwareAccelerated) {
6775                // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6776                // with a null dirty rect, which tells the ViewRoot to redraw everything
6777                p.invalidateChild(this, null);
6778                return;
6779            }
6780            if (p != null && ai != null) {
6781                final int scrollX = mScrollX;
6782                final int scrollY = mScrollY;
6783                final Rect r = ai.mTmpInvalRect;
6784                r.set(dirty.left - scrollX, dirty.top - scrollY,
6785                        dirty.right - scrollX, dirty.bottom - scrollY);
6786                mParent.invalidateChild(this, r);
6787            }
6788        }
6789    }
6790
6791    /**
6792     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
6793     * The coordinates of the dirty rect are relative to the view.
6794     * If the view is visible, {@link #onDraw} will be called at some point
6795     * in the future. This must be called from a UI thread. To call
6796     * from a non-UI thread, call {@link #postInvalidate()}.
6797     * @param l the left position of the dirty region
6798     * @param t the top position of the dirty region
6799     * @param r the right position of the dirty region
6800     * @param b the bottom position of the dirty region
6801     */
6802    public void invalidate(int l, int t, int r, int b) {
6803        if (ViewDebug.TRACE_HIERARCHY) {
6804            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6805        }
6806
6807        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6808                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
6809                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
6810            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6811            mPrivateFlags |= INVALIDATED;
6812            final ViewParent p = mParent;
6813            final AttachInfo ai = mAttachInfo;
6814            if (p != null && ai != null && ai.mHardwareAccelerated) {
6815                // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6816                // with a null dirty rect, which tells the ViewRoot to redraw everything
6817                p.invalidateChild(this, null);
6818                return;
6819            }
6820            if (p != null && ai != null && l < r && t < b) {
6821                final int scrollX = mScrollX;
6822                final int scrollY = mScrollY;
6823                final Rect tmpr = ai.mTmpInvalRect;
6824                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
6825                p.invalidateChild(this, tmpr);
6826            }
6827        }
6828    }
6829
6830    /**
6831     * Invalidate the whole view. If the view is visible, {@link #onDraw} will
6832     * be called at some point in the future. This must be called from a
6833     * UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
6834     */
6835    public void invalidate() {
6836        invalidate(true);
6837    }
6838
6839    /**
6840     * This is where the invalidate() work actually happens. A full invalidate()
6841     * causes the drawing cache to be invalidated, but this function can be called with
6842     * invalidateCache set to false to skip that invalidation step for cases that do not
6843     * need it (for example, a component that remains at the same dimensions with the same
6844     * content).
6845     *
6846     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
6847     * well. This is usually true for a full invalidate, but may be set to false if the
6848     * View's contents or dimensions have not changed.
6849     */
6850    private void invalidate(boolean invalidateCache) {
6851        if (ViewDebug.TRACE_HIERARCHY) {
6852            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
6853        }
6854
6855        boolean opaque = isOpaque();
6856        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
6857                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
6858                opaque != mLastIsOpaque || (mPrivateFlags & INVALIDATED) != INVALIDATED) {
6859            mLastIsOpaque = opaque;
6860            mPrivateFlags &= ~DRAWN;
6861            if (invalidateCache) {
6862                mPrivateFlags |= INVALIDATED;
6863                mPrivateFlags &= ~DRAWING_CACHE_VALID;
6864            }
6865            final AttachInfo ai = mAttachInfo;
6866            final ViewParent p = mParent;
6867            if (p != null && ai != null && ai.mHardwareAccelerated) {
6868                // fast-track for GL-enabled applications; just invalidate the whole hierarchy
6869                // with a null dirty rect, which tells the ViewRoot to redraw everything
6870                p.invalidateChild(this, null);
6871                return;
6872            }
6873
6874            if (p != null && ai != null) {
6875                final Rect r = ai.mTmpInvalRect;
6876                r.set(0, 0, mRight - mLeft, mBottom - mTop);
6877                // Don't call invalidate -- we don't want to internally scroll
6878                // our own bounds
6879                p.invalidateChild(this, r);
6880            }
6881        }
6882    }
6883
6884    /**
6885     * Used to indicate that the parent of this view should be invalidated. This functionality
6886     * is used to force the parent to rebuild its display list (when hardware-accelerated),
6887     * which is necessary when various parent-managed properties of the view change, such as
6888     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y.
6889     *
6890     * @hide
6891     */
6892    protected void invalidateParentIfAccelerated() {
6893        if (isHardwareAccelerated() && mParent instanceof View) {
6894            ((View) mParent).invalidate();
6895        }
6896    }
6897
6898    /**
6899     * Indicates whether this View is opaque. An opaque View guarantees that it will
6900     * draw all the pixels overlapping its bounds using a fully opaque color.
6901     *
6902     * Subclasses of View should override this method whenever possible to indicate
6903     * whether an instance is opaque. Opaque Views are treated in a special way by
6904     * the View hierarchy, possibly allowing it to perform optimizations during
6905     * invalidate/draw passes.
6906     *
6907     * @return True if this View is guaranteed to be fully opaque, false otherwise.
6908     */
6909    @ViewDebug.ExportedProperty(category = "drawing")
6910    public boolean isOpaque() {
6911        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
6912                (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
6913    }
6914
6915    /**
6916     * @hide
6917     */
6918    protected void computeOpaqueFlags() {
6919        // Opaque if:
6920        //   - Has a background
6921        //   - Background is opaque
6922        //   - Doesn't have scrollbars or scrollbars are inside overlay
6923
6924        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
6925            mPrivateFlags |= OPAQUE_BACKGROUND;
6926        } else {
6927            mPrivateFlags &= ~OPAQUE_BACKGROUND;
6928        }
6929
6930        final int flags = mViewFlags;
6931        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
6932                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
6933            mPrivateFlags |= OPAQUE_SCROLLBARS;
6934        } else {
6935            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
6936        }
6937    }
6938
6939    /**
6940     * @hide
6941     */
6942    protected boolean hasOpaqueScrollbars() {
6943        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
6944    }
6945
6946    /**
6947     * @return A handler associated with the thread running the View. This
6948     * handler can be used to pump events in the UI events queue.
6949     */
6950    public Handler getHandler() {
6951        if (mAttachInfo != null) {
6952            return mAttachInfo.mHandler;
6953        }
6954        return null;
6955    }
6956
6957    /**
6958     * Causes the Runnable to be added to the message queue.
6959     * The runnable will be run on the user interface thread.
6960     *
6961     * @param action The Runnable that will be executed.
6962     *
6963     * @return Returns true if the Runnable was successfully placed in to the
6964     *         message queue.  Returns false on failure, usually because the
6965     *         looper processing the message queue is exiting.
6966     */
6967    public boolean post(Runnable action) {
6968        Handler handler;
6969        if (mAttachInfo != null) {
6970            handler = mAttachInfo.mHandler;
6971        } else {
6972            // Assume that post will succeed later
6973            ViewRoot.getRunQueue().post(action);
6974            return true;
6975        }
6976
6977        return handler.post(action);
6978    }
6979
6980    /**
6981     * Causes the Runnable to be added to the message queue, to be run
6982     * after the specified amount of time elapses.
6983     * The runnable will be run on the user interface thread.
6984     *
6985     * @param action The Runnable that will be executed.
6986     * @param delayMillis The delay (in milliseconds) until the Runnable
6987     *        will be executed.
6988     *
6989     * @return true if the Runnable was successfully placed in to the
6990     *         message queue.  Returns false on failure, usually because the
6991     *         looper processing the message queue is exiting.  Note that a
6992     *         result of true does not mean the Runnable will be processed --
6993     *         if the looper is quit before the delivery time of the message
6994     *         occurs then the message will be dropped.
6995     */
6996    public boolean postDelayed(Runnable action, long delayMillis) {
6997        Handler handler;
6998        if (mAttachInfo != null) {
6999            handler = mAttachInfo.mHandler;
7000        } else {
7001            // Assume that post will succeed later
7002            ViewRoot.getRunQueue().postDelayed(action, delayMillis);
7003            return true;
7004        }
7005
7006        return handler.postDelayed(action, delayMillis);
7007    }
7008
7009    /**
7010     * Removes the specified Runnable from the message queue.
7011     *
7012     * @param action The Runnable to remove from the message handling queue
7013     *
7014     * @return true if this view could ask the Handler to remove the Runnable,
7015     *         false otherwise. When the returned value is true, the Runnable
7016     *         may or may not have been actually removed from the message queue
7017     *         (for instance, if the Runnable was not in the queue already.)
7018     */
7019    public boolean removeCallbacks(Runnable action) {
7020        Handler handler;
7021        if (mAttachInfo != null) {
7022            handler = mAttachInfo.mHandler;
7023        } else {
7024            // Assume that post will succeed later
7025            ViewRoot.getRunQueue().removeCallbacks(action);
7026            return true;
7027        }
7028
7029        handler.removeCallbacks(action);
7030        return true;
7031    }
7032
7033    /**
7034     * Cause an invalidate to happen on a subsequent cycle through the event loop.
7035     * Use this to invalidate the View from a non-UI thread.
7036     *
7037     * @see #invalidate()
7038     */
7039    public void postInvalidate() {
7040        postInvalidateDelayed(0);
7041    }
7042
7043    /**
7044     * Cause an invalidate of the specified area to happen on a subsequent cycle
7045     * through the event loop. Use this to invalidate the View from a non-UI thread.
7046     *
7047     * @param left The left coordinate of the rectangle to invalidate.
7048     * @param top The top coordinate of the rectangle to invalidate.
7049     * @param right The right coordinate of the rectangle to invalidate.
7050     * @param bottom The bottom coordinate of the rectangle to invalidate.
7051     *
7052     * @see #invalidate(int, int, int, int)
7053     * @see #invalidate(Rect)
7054     */
7055    public void postInvalidate(int left, int top, int right, int bottom) {
7056        postInvalidateDelayed(0, left, top, right, bottom);
7057    }
7058
7059    /**
7060     * Cause an invalidate to happen on a subsequent cycle through the event
7061     * loop. Waits for the specified amount of time.
7062     *
7063     * @param delayMilliseconds the duration in milliseconds to delay the
7064     *         invalidation by
7065     */
7066    public void postInvalidateDelayed(long delayMilliseconds) {
7067        // We try only with the AttachInfo because there's no point in invalidating
7068        // if we are not attached to our window
7069        if (mAttachInfo != null) {
7070            Message msg = Message.obtain();
7071            msg.what = AttachInfo.INVALIDATE_MSG;
7072            msg.obj = this;
7073            mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7074        }
7075    }
7076
7077    /**
7078     * Cause an invalidate of the specified area to happen on a subsequent cycle
7079     * through the event loop. Waits for the specified amount of time.
7080     *
7081     * @param delayMilliseconds the duration in milliseconds to delay the
7082     *         invalidation by
7083     * @param left The left coordinate of the rectangle to invalidate.
7084     * @param top The top coordinate of the rectangle to invalidate.
7085     * @param right The right coordinate of the rectangle to invalidate.
7086     * @param bottom The bottom coordinate of the rectangle to invalidate.
7087     */
7088    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
7089            int right, int bottom) {
7090
7091        // We try only with the AttachInfo because there's no point in invalidating
7092        // if we are not attached to our window
7093        if (mAttachInfo != null) {
7094            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
7095            info.target = this;
7096            info.left = left;
7097            info.top = top;
7098            info.right = right;
7099            info.bottom = bottom;
7100
7101            final Message msg = Message.obtain();
7102            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
7103            msg.obj = info;
7104            mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
7105        }
7106    }
7107
7108    /**
7109     * Called by a parent to request that a child update its values for mScrollX
7110     * and mScrollY if necessary. This will typically be done if the child is
7111     * animating a scroll using a {@link android.widget.Scroller Scroller}
7112     * object.
7113     */
7114    public void computeScroll() {
7115    }
7116
7117    /**
7118     * <p>Indicate whether the horizontal edges are faded when the view is
7119     * scrolled horizontally.</p>
7120     *
7121     * @return true if the horizontal edges should are faded on scroll, false
7122     *         otherwise
7123     *
7124     * @see #setHorizontalFadingEdgeEnabled(boolean)
7125     * @attr ref android.R.styleable#View_fadingEdge
7126     */
7127    public boolean isHorizontalFadingEdgeEnabled() {
7128        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
7129    }
7130
7131    /**
7132     * <p>Define whether the horizontal edges should be faded when this view
7133     * is scrolled horizontally.</p>
7134     *
7135     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
7136     *                                    be faded when the view is scrolled
7137     *                                    horizontally
7138     *
7139     * @see #isHorizontalFadingEdgeEnabled()
7140     * @attr ref android.R.styleable#View_fadingEdge
7141     */
7142    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
7143        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
7144            if (horizontalFadingEdgeEnabled) {
7145                initScrollCache();
7146            }
7147
7148            mViewFlags ^= FADING_EDGE_HORIZONTAL;
7149        }
7150    }
7151
7152    /**
7153     * <p>Indicate whether the vertical edges are faded when the view is
7154     * scrolled horizontally.</p>
7155     *
7156     * @return true if the vertical edges should are faded on scroll, false
7157     *         otherwise
7158     *
7159     * @see #setVerticalFadingEdgeEnabled(boolean)
7160     * @attr ref android.R.styleable#View_fadingEdge
7161     */
7162    public boolean isVerticalFadingEdgeEnabled() {
7163        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
7164    }
7165
7166    /**
7167     * <p>Define whether the vertical edges should be faded when this view
7168     * is scrolled vertically.</p>
7169     *
7170     * @param verticalFadingEdgeEnabled true if the vertical edges should
7171     *                                  be faded when the view is scrolled
7172     *                                  vertically
7173     *
7174     * @see #isVerticalFadingEdgeEnabled()
7175     * @attr ref android.R.styleable#View_fadingEdge
7176     */
7177    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
7178        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
7179            if (verticalFadingEdgeEnabled) {
7180                initScrollCache();
7181            }
7182
7183            mViewFlags ^= FADING_EDGE_VERTICAL;
7184        }
7185    }
7186
7187    /**
7188     * Returns the strength, or intensity, of the top faded edge. The strength is
7189     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7190     * returns 0.0 or 1.0 but no value in between.
7191     *
7192     * Subclasses should override this method to provide a smoother fade transition
7193     * when scrolling occurs.
7194     *
7195     * @return the intensity of the top fade as a float between 0.0f and 1.0f
7196     */
7197    protected float getTopFadingEdgeStrength() {
7198        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
7199    }
7200
7201    /**
7202     * Returns the strength, or intensity, of the bottom faded edge. The strength is
7203     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7204     * returns 0.0 or 1.0 but no value in between.
7205     *
7206     * Subclasses should override this method to provide a smoother fade transition
7207     * when scrolling occurs.
7208     *
7209     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
7210     */
7211    protected float getBottomFadingEdgeStrength() {
7212        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
7213                computeVerticalScrollRange() ? 1.0f : 0.0f;
7214    }
7215
7216    /**
7217     * Returns the strength, or intensity, of the left faded edge. The strength is
7218     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7219     * returns 0.0 or 1.0 but no value in between.
7220     *
7221     * Subclasses should override this method to provide a smoother fade transition
7222     * when scrolling occurs.
7223     *
7224     * @return the intensity of the left fade as a float between 0.0f and 1.0f
7225     */
7226    protected float getLeftFadingEdgeStrength() {
7227        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
7228    }
7229
7230    /**
7231     * Returns the strength, or intensity, of the right faded edge. The strength is
7232     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
7233     * returns 0.0 or 1.0 but no value in between.
7234     *
7235     * Subclasses should override this method to provide a smoother fade transition
7236     * when scrolling occurs.
7237     *
7238     * @return the intensity of the right fade as a float between 0.0f and 1.0f
7239     */
7240    protected float getRightFadingEdgeStrength() {
7241        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
7242                computeHorizontalScrollRange() ? 1.0f : 0.0f;
7243    }
7244
7245    /**
7246     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
7247     * scrollbar is not drawn by default.</p>
7248     *
7249     * @return true if the horizontal scrollbar should be painted, false
7250     *         otherwise
7251     *
7252     * @see #setHorizontalScrollBarEnabled(boolean)
7253     */
7254    public boolean isHorizontalScrollBarEnabled() {
7255        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7256    }
7257
7258    /**
7259     * <p>Define whether the horizontal scrollbar should be drawn or not. The
7260     * scrollbar is not drawn by default.</p>
7261     *
7262     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
7263     *                                   be painted
7264     *
7265     * @see #isHorizontalScrollBarEnabled()
7266     */
7267    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
7268        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
7269            mViewFlags ^= SCROLLBARS_HORIZONTAL;
7270            computeOpaqueFlags();
7271            recomputePadding();
7272        }
7273    }
7274
7275    /**
7276     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
7277     * scrollbar is not drawn by default.</p>
7278     *
7279     * @return true if the vertical scrollbar should be painted, false
7280     *         otherwise
7281     *
7282     * @see #setVerticalScrollBarEnabled(boolean)
7283     */
7284    public boolean isVerticalScrollBarEnabled() {
7285        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
7286    }
7287
7288    /**
7289     * <p>Define whether the vertical scrollbar should be drawn or not. The
7290     * scrollbar is not drawn by default.</p>
7291     *
7292     * @param verticalScrollBarEnabled true if the vertical scrollbar should
7293     *                                 be painted
7294     *
7295     * @see #isVerticalScrollBarEnabled()
7296     */
7297    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
7298        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
7299            mViewFlags ^= SCROLLBARS_VERTICAL;
7300            computeOpaqueFlags();
7301            recomputePadding();
7302        }
7303    }
7304
7305    /**
7306     * @hide
7307     */
7308    protected void recomputePadding() {
7309        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
7310    }
7311
7312    /**
7313     * Define whether scrollbars will fade when the view is not scrolling.
7314     *
7315     * @param fadeScrollbars wheter to enable fading
7316     *
7317     */
7318    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
7319        initScrollCache();
7320        final ScrollabilityCache scrollabilityCache = mScrollCache;
7321        scrollabilityCache.fadeScrollBars = fadeScrollbars;
7322        if (fadeScrollbars) {
7323            scrollabilityCache.state = ScrollabilityCache.OFF;
7324        } else {
7325            scrollabilityCache.state = ScrollabilityCache.ON;
7326        }
7327    }
7328
7329    /**
7330     *
7331     * Returns true if scrollbars will fade when this view is not scrolling
7332     *
7333     * @return true if scrollbar fading is enabled
7334     */
7335    public boolean isScrollbarFadingEnabled() {
7336        return mScrollCache != null && mScrollCache.fadeScrollBars;
7337    }
7338
7339    /**
7340     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
7341     * inset. When inset, they add to the padding of the view. And the scrollbars
7342     * can be drawn inside the padding area or on the edge of the view. For example,
7343     * if a view has a background drawable and you want to draw the scrollbars
7344     * inside the padding specified by the drawable, you can use
7345     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
7346     * appear at the edge of the view, ignoring the padding, then you can use
7347     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
7348     * @param style the style of the scrollbars. Should be one of
7349     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
7350     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
7351     * @see #SCROLLBARS_INSIDE_OVERLAY
7352     * @see #SCROLLBARS_INSIDE_INSET
7353     * @see #SCROLLBARS_OUTSIDE_OVERLAY
7354     * @see #SCROLLBARS_OUTSIDE_INSET
7355     */
7356    public void setScrollBarStyle(int style) {
7357        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
7358            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
7359            computeOpaqueFlags();
7360            recomputePadding();
7361        }
7362    }
7363
7364    /**
7365     * <p>Returns the current scrollbar style.</p>
7366     * @return the current scrollbar style
7367     * @see #SCROLLBARS_INSIDE_OVERLAY
7368     * @see #SCROLLBARS_INSIDE_INSET
7369     * @see #SCROLLBARS_OUTSIDE_OVERLAY
7370     * @see #SCROLLBARS_OUTSIDE_INSET
7371     */
7372    public int getScrollBarStyle() {
7373        return mViewFlags & SCROLLBARS_STYLE_MASK;
7374    }
7375
7376    /**
7377     * <p>Compute the horizontal range that the horizontal scrollbar
7378     * represents.</p>
7379     *
7380     * <p>The range is expressed in arbitrary units that must be the same as the
7381     * units used by {@link #computeHorizontalScrollExtent()} and
7382     * {@link #computeHorizontalScrollOffset()}.</p>
7383     *
7384     * <p>The default range is the drawing width of this view.</p>
7385     *
7386     * @return the total horizontal range represented by the horizontal
7387     *         scrollbar
7388     *
7389     * @see #computeHorizontalScrollExtent()
7390     * @see #computeHorizontalScrollOffset()
7391     * @see android.widget.ScrollBarDrawable
7392     */
7393    protected int computeHorizontalScrollRange() {
7394        return getWidth();
7395    }
7396
7397    /**
7398     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
7399     * within the horizontal range. This value is used to compute the position
7400     * of the thumb within the scrollbar's track.</p>
7401     *
7402     * <p>The range is expressed in arbitrary units that must be the same as the
7403     * units used by {@link #computeHorizontalScrollRange()} and
7404     * {@link #computeHorizontalScrollExtent()}.</p>
7405     *
7406     * <p>The default offset is the scroll offset of this view.</p>
7407     *
7408     * @return the horizontal offset of the scrollbar's thumb
7409     *
7410     * @see #computeHorizontalScrollRange()
7411     * @see #computeHorizontalScrollExtent()
7412     * @see android.widget.ScrollBarDrawable
7413     */
7414    protected int computeHorizontalScrollOffset() {
7415        return mScrollX;
7416    }
7417
7418    /**
7419     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
7420     * within the horizontal range. This value is used to compute the length
7421     * of the thumb within the scrollbar's track.</p>
7422     *
7423     * <p>The range is expressed in arbitrary units that must be the same as the
7424     * units used by {@link #computeHorizontalScrollRange()} and
7425     * {@link #computeHorizontalScrollOffset()}.</p>
7426     *
7427     * <p>The default extent is the drawing width of this view.</p>
7428     *
7429     * @return the horizontal extent of the scrollbar's thumb
7430     *
7431     * @see #computeHorizontalScrollRange()
7432     * @see #computeHorizontalScrollOffset()
7433     * @see android.widget.ScrollBarDrawable
7434     */
7435    protected int computeHorizontalScrollExtent() {
7436        return getWidth();
7437    }
7438
7439    /**
7440     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
7441     *
7442     * <p>The range is expressed in arbitrary units that must be the same as the
7443     * units used by {@link #computeVerticalScrollExtent()} and
7444     * {@link #computeVerticalScrollOffset()}.</p>
7445     *
7446     * @return the total vertical range represented by the vertical scrollbar
7447     *
7448     * <p>The default range is the drawing height of this view.</p>
7449     *
7450     * @see #computeVerticalScrollExtent()
7451     * @see #computeVerticalScrollOffset()
7452     * @see android.widget.ScrollBarDrawable
7453     */
7454    protected int computeVerticalScrollRange() {
7455        return getHeight();
7456    }
7457
7458    /**
7459     * <p>Compute the vertical offset of the vertical scrollbar's thumb
7460     * within the horizontal range. This value is used to compute the position
7461     * of the thumb within the scrollbar's track.</p>
7462     *
7463     * <p>The range is expressed in arbitrary units that must be the same as the
7464     * units used by {@link #computeVerticalScrollRange()} and
7465     * {@link #computeVerticalScrollExtent()}.</p>
7466     *
7467     * <p>The default offset is the scroll offset of this view.</p>
7468     *
7469     * @return the vertical offset of the scrollbar's thumb
7470     *
7471     * @see #computeVerticalScrollRange()
7472     * @see #computeVerticalScrollExtent()
7473     * @see android.widget.ScrollBarDrawable
7474     */
7475    protected int computeVerticalScrollOffset() {
7476        return mScrollY;
7477    }
7478
7479    /**
7480     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
7481     * within the vertical range. This value is used to compute the length
7482     * of the thumb within the scrollbar's track.</p>
7483     *
7484     * <p>The range is expressed in arbitrary units that must be the same as the
7485     * units used by {@link #computeVerticalScrollRange()} and
7486     * {@link #computeVerticalScrollOffset()}.</p>
7487     *
7488     * <p>The default extent is the drawing height of this view.</p>
7489     *
7490     * @return the vertical extent of the scrollbar's thumb
7491     *
7492     * @see #computeVerticalScrollRange()
7493     * @see #computeVerticalScrollOffset()
7494     * @see android.widget.ScrollBarDrawable
7495     */
7496    protected int computeVerticalScrollExtent() {
7497        return getHeight();
7498    }
7499
7500    /**
7501     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
7502     * scrollbars are painted only if they have been awakened first.</p>
7503     *
7504     * @param canvas the canvas on which to draw the scrollbars
7505     *
7506     * @see #awakenScrollBars(int)
7507     */
7508    protected final void onDrawScrollBars(Canvas canvas) {
7509        // scrollbars are drawn only when the animation is running
7510        final ScrollabilityCache cache = mScrollCache;
7511        if (cache != null) {
7512
7513            int state = cache.state;
7514
7515            if (state == ScrollabilityCache.OFF) {
7516                return;
7517            }
7518
7519            boolean invalidate = false;
7520
7521            if (state == ScrollabilityCache.FADING) {
7522                // We're fading -- get our fade interpolation
7523                if (cache.interpolatorValues == null) {
7524                    cache.interpolatorValues = new float[1];
7525                }
7526
7527                float[] values = cache.interpolatorValues;
7528
7529                // Stops the animation if we're done
7530                if (cache.scrollBarInterpolator.timeToValues(values) ==
7531                        Interpolator.Result.FREEZE_END) {
7532                    cache.state = ScrollabilityCache.OFF;
7533                } else {
7534                    cache.scrollBar.setAlpha(Math.round(values[0]));
7535                }
7536
7537                // This will make the scroll bars inval themselves after
7538                // drawing. We only want this when we're fading so that
7539                // we prevent excessive redraws
7540                invalidate = true;
7541            } else {
7542                // We're just on -- but we may have been fading before so
7543                // reset alpha
7544                cache.scrollBar.setAlpha(255);
7545            }
7546
7547
7548            final int viewFlags = mViewFlags;
7549
7550            final boolean drawHorizontalScrollBar =
7551                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
7552            final boolean drawVerticalScrollBar =
7553                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
7554                && !isVerticalScrollBarHidden();
7555
7556            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
7557                final int width = mRight - mLeft;
7558                final int height = mBottom - mTop;
7559
7560                final ScrollBarDrawable scrollBar = cache.scrollBar;
7561                int size = scrollBar.getSize(false);
7562                if (size <= 0) {
7563                    size = cache.scrollBarSize;
7564                }
7565
7566                final int scrollX = mScrollX;
7567                final int scrollY = mScrollY;
7568                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
7569
7570                int left, top, right, bottom;
7571
7572                if (drawHorizontalScrollBar) {
7573                    scrollBar.setParameters(computeHorizontalScrollRange(),
7574                                            computeHorizontalScrollOffset(),
7575                                            computeHorizontalScrollExtent(), false);
7576                    final int verticalScrollBarGap = drawVerticalScrollBar ?
7577                            getVerticalScrollbarWidth() : 0;
7578                    top = scrollY + height - size - (mUserPaddingBottom & inside);
7579                    left = scrollX + (mPaddingLeft & inside);
7580                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
7581                    bottom = top + size;
7582                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
7583                    if (invalidate) {
7584                        invalidate(left, top, right, bottom);
7585                    }
7586                }
7587
7588                if (drawVerticalScrollBar) {
7589                    scrollBar.setParameters(computeVerticalScrollRange(),
7590                                            computeVerticalScrollOffset(),
7591                                            computeVerticalScrollExtent(), true);
7592                    switch (mVerticalScrollbarPosition) {
7593                        default:
7594                        case SCROLLBAR_POSITION_DEFAULT:
7595                        case SCROLLBAR_POSITION_RIGHT:
7596                            left = scrollX + width - size - (mUserPaddingRight & inside);
7597                            break;
7598                        case SCROLLBAR_POSITION_LEFT:
7599                            left = scrollX + (mUserPaddingLeft & inside);
7600                            break;
7601                    }
7602                    top = scrollY + (mPaddingTop & inside);
7603                    right = left + size;
7604                    bottom = scrollY + height - (mUserPaddingBottom & inside);
7605                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
7606                    if (invalidate) {
7607                        invalidate(left, top, right, bottom);
7608                    }
7609                }
7610            }
7611        }
7612    }
7613
7614    /**
7615     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
7616     * FastScroller is visible.
7617     * @return whether to temporarily hide the vertical scrollbar
7618     * @hide
7619     */
7620    protected boolean isVerticalScrollBarHidden() {
7621        return false;
7622    }
7623
7624    /**
7625     * <p>Draw the horizontal scrollbar if
7626     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
7627     *
7628     * @param canvas the canvas on which to draw the scrollbar
7629     * @param scrollBar the scrollbar's drawable
7630     *
7631     * @see #isHorizontalScrollBarEnabled()
7632     * @see #computeHorizontalScrollRange()
7633     * @see #computeHorizontalScrollExtent()
7634     * @see #computeHorizontalScrollOffset()
7635     * @see android.widget.ScrollBarDrawable
7636     * @hide
7637     */
7638    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
7639            int l, int t, int r, int b) {
7640        scrollBar.setBounds(l, t, r, b);
7641        scrollBar.draw(canvas);
7642    }
7643
7644    /**
7645     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
7646     * returns true.</p>
7647     *
7648     * @param canvas the canvas on which to draw the scrollbar
7649     * @param scrollBar the scrollbar's drawable
7650     *
7651     * @see #isVerticalScrollBarEnabled()
7652     * @see #computeVerticalScrollRange()
7653     * @see #computeVerticalScrollExtent()
7654     * @see #computeVerticalScrollOffset()
7655     * @see android.widget.ScrollBarDrawable
7656     * @hide
7657     */
7658    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
7659            int l, int t, int r, int b) {
7660        scrollBar.setBounds(l, t, r, b);
7661        scrollBar.draw(canvas);
7662    }
7663
7664    /**
7665     * Implement this to do your drawing.
7666     *
7667     * @param canvas the canvas on which the background will be drawn
7668     */
7669    protected void onDraw(Canvas canvas) {
7670    }
7671
7672    /*
7673     * Caller is responsible for calling requestLayout if necessary.
7674     * (This allows addViewInLayout to not request a new layout.)
7675     */
7676    void assignParent(ViewParent parent) {
7677        if (mParent == null) {
7678            mParent = parent;
7679        } else if (parent == null) {
7680            mParent = null;
7681        } else {
7682            throw new RuntimeException("view " + this + " being added, but"
7683                    + " it already has a parent");
7684        }
7685    }
7686
7687    /**
7688     * This is called when the view is attached to a window.  At this point it
7689     * has a Surface and will start drawing.  Note that this function is
7690     * guaranteed to be called before {@link #onDraw}, however it may be called
7691     * any time before the first onDraw -- including before or after
7692     * {@link #onMeasure}.
7693     *
7694     * @see #onDetachedFromWindow()
7695     */
7696    protected void onAttachedToWindow() {
7697        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
7698            mParent.requestTransparentRegion(this);
7699        }
7700        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
7701            initialAwakenScrollBars();
7702            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
7703        }
7704        jumpDrawablesToCurrentState();
7705    }
7706
7707    /**
7708     * This is called when the view is detached from a window.  At this point it
7709     * no longer has a surface for drawing.
7710     *
7711     * @see #onAttachedToWindow()
7712     */
7713    protected void onDetachedFromWindow() {
7714        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
7715
7716        removeUnsetPressCallback();
7717        removeLongPressCallback();
7718        removePerformClickCallback();
7719
7720        destroyDrawingCache();
7721
7722        if (mHardwareLayer != null) {
7723            mHardwareLayer.destroy();
7724            mHardwareLayer = null;
7725        }
7726
7727        if (mDisplayList != null) {
7728            mDisplayList.invalidate();
7729        }
7730
7731        if (mAttachInfo != null) {
7732            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
7733            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
7734        }
7735
7736        mCurrentAnimation = null;
7737    }
7738
7739    /**
7740     * @return The number of times this view has been attached to a window
7741     */
7742    protected int getWindowAttachCount() {
7743        return mWindowAttachCount;
7744    }
7745
7746    /**
7747     * Retrieve a unique token identifying the window this view is attached to.
7748     * @return Return the window's token for use in
7749     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
7750     */
7751    public IBinder getWindowToken() {
7752        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
7753    }
7754
7755    /**
7756     * Retrieve a unique token identifying the top-level "real" window of
7757     * the window that this view is attached to.  That is, this is like
7758     * {@link #getWindowToken}, except if the window this view in is a panel
7759     * window (attached to another containing window), then the token of
7760     * the containing window is returned instead.
7761     *
7762     * @return Returns the associated window token, either
7763     * {@link #getWindowToken()} or the containing window's token.
7764     */
7765    public IBinder getApplicationWindowToken() {
7766        AttachInfo ai = mAttachInfo;
7767        if (ai != null) {
7768            IBinder appWindowToken = ai.mPanelParentWindowToken;
7769            if (appWindowToken == null) {
7770                appWindowToken = ai.mWindowToken;
7771            }
7772            return appWindowToken;
7773        }
7774        return null;
7775    }
7776
7777    /**
7778     * Retrieve private session object this view hierarchy is using to
7779     * communicate with the window manager.
7780     * @return the session object to communicate with the window manager
7781     */
7782    /*package*/ IWindowSession getWindowSession() {
7783        return mAttachInfo != null ? mAttachInfo.mSession : null;
7784    }
7785
7786    /**
7787     * @param info the {@link android.view.View.AttachInfo} to associated with
7788     *        this view
7789     */
7790    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
7791        //System.out.println("Attached! " + this);
7792        mAttachInfo = info;
7793        mWindowAttachCount++;
7794        // We will need to evaluate the drawable state at least once.
7795        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
7796        if (mFloatingTreeObserver != null) {
7797            info.mTreeObserver.merge(mFloatingTreeObserver);
7798            mFloatingTreeObserver = null;
7799        }
7800        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
7801            mAttachInfo.mScrollContainers.add(this);
7802            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
7803        }
7804        performCollectViewAttributes(visibility);
7805        onAttachedToWindow();
7806        int vis = info.mWindowVisibility;
7807        if (vis != GONE) {
7808            onWindowVisibilityChanged(vis);
7809        }
7810        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
7811            // If nobody has evaluated the drawable state yet, then do it now.
7812            refreshDrawableState();
7813        }
7814    }
7815
7816    void dispatchDetachedFromWindow() {
7817        //System.out.println("Detached! " + this);
7818        AttachInfo info = mAttachInfo;
7819        if (info != null) {
7820            int vis = info.mWindowVisibility;
7821            if (vis != GONE) {
7822                onWindowVisibilityChanged(GONE);
7823            }
7824        }
7825
7826        onDetachedFromWindow();
7827        if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
7828            mAttachInfo.mScrollContainers.remove(this);
7829            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
7830        }
7831        mAttachInfo = null;
7832    }
7833
7834    /**
7835     * Store this view hierarchy's frozen state into the given container.
7836     *
7837     * @param container The SparseArray in which to save the view's state.
7838     *
7839     * @see #restoreHierarchyState
7840     * @see #dispatchSaveInstanceState
7841     * @see #onSaveInstanceState
7842     */
7843    public void saveHierarchyState(SparseArray<Parcelable> container) {
7844        dispatchSaveInstanceState(container);
7845    }
7846
7847    /**
7848     * Called by {@link #saveHierarchyState} to store the state for this view and its children.
7849     * May be overridden to modify how freezing happens to a view's children; for example, some
7850     * views may want to not store state for their children.
7851     *
7852     * @param container The SparseArray in which to save the view's state.
7853     *
7854     * @see #dispatchRestoreInstanceState
7855     * @see #saveHierarchyState
7856     * @see #onSaveInstanceState
7857     */
7858    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
7859        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
7860            mPrivateFlags &= ~SAVE_STATE_CALLED;
7861            Parcelable state = onSaveInstanceState();
7862            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7863                throw new IllegalStateException(
7864                        "Derived class did not call super.onSaveInstanceState()");
7865            }
7866            if (state != null) {
7867                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
7868                // + ": " + state);
7869                container.put(mID, state);
7870            }
7871        }
7872    }
7873
7874    /**
7875     * Hook allowing a view to generate a representation of its internal state
7876     * that can later be used to create a new instance with that same state.
7877     * This state should only contain information that is not persistent or can
7878     * not be reconstructed later. For example, you will never store your
7879     * current position on screen because that will be computed again when a
7880     * new instance of the view is placed in its view hierarchy.
7881     * <p>
7882     * Some examples of things you may store here: the current cursor position
7883     * in a text view (but usually not the text itself since that is stored in a
7884     * content provider or other persistent storage), the currently selected
7885     * item in a list view.
7886     *
7887     * @return Returns a Parcelable object containing the view's current dynamic
7888     *         state, or null if there is nothing interesting to save. The
7889     *         default implementation returns null.
7890     * @see #onRestoreInstanceState
7891     * @see #saveHierarchyState
7892     * @see #dispatchSaveInstanceState
7893     * @see #setSaveEnabled(boolean)
7894     */
7895    protected Parcelable onSaveInstanceState() {
7896        mPrivateFlags |= SAVE_STATE_CALLED;
7897        return BaseSavedState.EMPTY_STATE;
7898    }
7899
7900    /**
7901     * Restore this view hierarchy's frozen state from the given container.
7902     *
7903     * @param container The SparseArray which holds previously frozen states.
7904     *
7905     * @see #saveHierarchyState
7906     * @see #dispatchRestoreInstanceState
7907     * @see #onRestoreInstanceState
7908     */
7909    public void restoreHierarchyState(SparseArray<Parcelable> container) {
7910        dispatchRestoreInstanceState(container);
7911    }
7912
7913    /**
7914     * Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
7915     * children. May be overridden to modify how restoreing happens to a view's children; for
7916     * example, some views may want to not store state for their children.
7917     *
7918     * @param container The SparseArray which holds previously saved state.
7919     *
7920     * @see #dispatchSaveInstanceState
7921     * @see #restoreHierarchyState
7922     * @see #onRestoreInstanceState
7923     */
7924    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
7925        if (mID != NO_ID) {
7926            Parcelable state = container.get(mID);
7927            if (state != null) {
7928                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
7929                // + ": " + state);
7930                mPrivateFlags &= ~SAVE_STATE_CALLED;
7931                onRestoreInstanceState(state);
7932                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
7933                    throw new IllegalStateException(
7934                            "Derived class did not call super.onRestoreInstanceState()");
7935                }
7936            }
7937        }
7938    }
7939
7940    /**
7941     * Hook allowing a view to re-apply a representation of its internal state that had previously
7942     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
7943     * null state.
7944     *
7945     * @param state The frozen state that had previously been returned by
7946     *        {@link #onSaveInstanceState}.
7947     *
7948     * @see #onSaveInstanceState
7949     * @see #restoreHierarchyState
7950     * @see #dispatchRestoreInstanceState
7951     */
7952    protected void onRestoreInstanceState(Parcelable state) {
7953        mPrivateFlags |= SAVE_STATE_CALLED;
7954        if (state != BaseSavedState.EMPTY_STATE && state != null) {
7955            throw new IllegalArgumentException("Wrong state class, expecting View State but "
7956                    + "received " + state.getClass().toString() + " instead. This usually happens "
7957                    + "when two views of different type have the same id in the same hierarchy. "
7958                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
7959                    + "other views do not use the same id.");
7960        }
7961    }
7962
7963    /**
7964     * <p>Return the time at which the drawing of the view hierarchy started.</p>
7965     *
7966     * @return the drawing start time in milliseconds
7967     */
7968    public long getDrawingTime() {
7969        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
7970    }
7971
7972    /**
7973     * <p>Enables or disables the duplication of the parent's state into this view. When
7974     * duplication is enabled, this view gets its drawable state from its parent rather
7975     * than from its own internal properties.</p>
7976     *
7977     * <p>Note: in the current implementation, setting this property to true after the
7978     * view was added to a ViewGroup might have no effect at all. This property should
7979     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
7980     *
7981     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
7982     * property is enabled, an exception will be thrown.</p>
7983     *
7984     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
7985     * parent, these states should not be affected by this method.</p>
7986     *
7987     * @param enabled True to enable duplication of the parent's drawable state, false
7988     *                to disable it.
7989     *
7990     * @see #getDrawableState()
7991     * @see #isDuplicateParentStateEnabled()
7992     */
7993    public void setDuplicateParentStateEnabled(boolean enabled) {
7994        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
7995    }
7996
7997    /**
7998     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
7999     *
8000     * @return True if this view's drawable state is duplicated from the parent,
8001     *         false otherwise
8002     *
8003     * @see #getDrawableState()
8004     * @see #setDuplicateParentStateEnabled(boolean)
8005     */
8006    public boolean isDuplicateParentStateEnabled() {
8007        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
8008    }
8009
8010    /**
8011     * <p>Specifies the type of layer backing this view. The layer can be
8012     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
8013     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
8014     *
8015     * <p>A layer is associated with an optional {@link android.graphics.Paint}
8016     * instance that controls how the layer is composed on screen. The following
8017     * properties of the paint are taken into account when composing the layer:</p>
8018     * <ul>
8019     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
8020     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
8021     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
8022     * </ul>
8023     *
8024     * <p>If this view has an alpha value set to < 1.0 by calling
8025     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
8026     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
8027     * equivalent to setting a hardware layer on this view and providing a paint with
8028     * the desired alpha value.<p>
8029     *
8030     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
8031     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
8032     * for more information on when and how to use layers.</p>
8033     *
8034     * @param layerType The ype of layer to use with this view, must be one of
8035     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8036     *        {@link #LAYER_TYPE_HARDWARE}
8037     * @param paint The paint used to compose the layer. This argument is optional
8038     *        and can be null. It is ignored when the layer type is
8039     *        {@link #LAYER_TYPE_NONE}
8040     *
8041     * @see #getLayerType()
8042     * @see #LAYER_TYPE_NONE
8043     * @see #LAYER_TYPE_SOFTWARE
8044     * @see #LAYER_TYPE_HARDWARE
8045     * @see #setAlpha(float)
8046     *
8047     * @attr ref android.R.styleable#View_layerType
8048     */
8049    public void setLayerType(int layerType, Paint paint) {
8050        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
8051            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
8052                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
8053        }
8054
8055        if (layerType == mLayerType) {
8056            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
8057                mLayerPaint = paint == null ? new Paint() : paint;
8058                if (mParent instanceof ViewGroup) {
8059                    ((ViewGroup) mParent).invalidate();
8060                }
8061                invalidate();
8062            }
8063            return;
8064        }
8065
8066        // Destroy any previous software drawing cache if needed
8067        switch (mLayerType) {
8068            case LAYER_TYPE_SOFTWARE:
8069                if (mDrawingCache != null) {
8070                    mDrawingCache.recycle();
8071                    mDrawingCache = null;
8072                }
8073
8074                if (mUnscaledDrawingCache != null) {
8075                    mUnscaledDrawingCache.recycle();
8076                    mUnscaledDrawingCache = null;
8077                }
8078                break;
8079            case LAYER_TYPE_HARDWARE:
8080                if (mHardwareLayer != null) {
8081                    mHardwareLayer.destroy();
8082                    mHardwareLayer = null;
8083                }
8084                break;
8085            default:
8086                break;
8087        }
8088
8089        mLayerType = layerType;
8090        mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : (paint == null ? new Paint() : paint);
8091
8092        if (mParent instanceof ViewGroup) {
8093            ((ViewGroup) mParent).invalidate();
8094        }
8095        invalidate();
8096    }
8097
8098    /**
8099     * Indicates what type of layer is currently associated with this view. By default
8100     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
8101     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
8102     * for more information on the different types of layers.
8103     *
8104     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
8105     *         {@link #LAYER_TYPE_HARDWARE}
8106     *
8107     * @see #setLayerType(int, android.graphics.Paint)
8108     * @see #LAYER_TYPE_NONE
8109     * @see #LAYER_TYPE_SOFTWARE
8110     * @see #LAYER_TYPE_HARDWARE
8111     */
8112    public int getLayerType() {
8113        return mLayerType;
8114    }
8115
8116    /**
8117     * <p>Returns a hardware layer that can be used to draw this view again
8118     * without executing its draw method.</p>
8119     *
8120     * @return A HardwareLayer ready to render, or null if an error occurred.
8121     */
8122    HardwareLayer getHardwareLayer(Canvas currentCanvas) {
8123        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8124            return null;
8125        }
8126
8127        final int width = mRight - mLeft;
8128        final int height = mBottom - mTop;
8129
8130        if (width == 0 || height == 0) {
8131            return null;
8132        }
8133
8134        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
8135            if (mHardwareLayer == null) {
8136                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
8137                        width, height, isOpaque());
8138            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
8139                mHardwareLayer.resize(width, height);
8140            }
8141
8142            final HardwareCanvas canvas = mHardwareLayer.start(mAttachInfo.mHardwareCanvas);
8143            try {
8144                canvas.setViewport(width, height);
8145                canvas.onPreDraw();
8146
8147                computeScroll();
8148                canvas.translate(-mScrollX, -mScrollY);
8149
8150                final int restoreCount = canvas.save();
8151
8152                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8153
8154                // Fast path for layouts with no backgrounds
8155                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8156                    mPrivateFlags &= ~DIRTY_MASK;
8157                    dispatchDraw(canvas);
8158                } else {
8159                    draw(canvas);
8160                }
8161
8162                canvas.restoreToCount(restoreCount);
8163            } finally {
8164                canvas.onPostDraw();
8165                mHardwareLayer.end(mAttachInfo.mHardwareCanvas);
8166            }
8167        }
8168
8169        return mHardwareLayer;
8170    }
8171
8172    /**
8173     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
8174     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
8175     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
8176     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
8177     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
8178     * null.</p>
8179     *
8180     * <p>Enabling the drawing cache is similar to
8181     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
8182     * acceleration is turned off. When hardware acceleration is turned on, enabling the
8183     * drawing cache has no effect on rendering because the system uses a different mechanism
8184     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
8185     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
8186     * for information on how to enable software and hardware layers.</p>
8187     *
8188     * <p>This API can be used to manually generate
8189     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
8190     * {@link #getDrawingCache()}.</p>
8191     *
8192     * @param enabled true to enable the drawing cache, false otherwise
8193     *
8194     * @see #isDrawingCacheEnabled()
8195     * @see #getDrawingCache()
8196     * @see #buildDrawingCache()
8197     * @see #setLayerType(int, android.graphics.Paint)
8198     */
8199    public void setDrawingCacheEnabled(boolean enabled) {
8200        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
8201    }
8202
8203    /**
8204     * <p>Indicates whether the drawing cache is enabled for this view.</p>
8205     *
8206     * @return true if the drawing cache is enabled
8207     *
8208     * @see #setDrawingCacheEnabled(boolean)
8209     * @see #getDrawingCache()
8210     */
8211    @ViewDebug.ExportedProperty(category = "drawing")
8212    public boolean isDrawingCacheEnabled() {
8213        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
8214    }
8215
8216    /**
8217     * Debugging utility which recursively outputs the dirty state of a view and its
8218     * descendants.
8219     *
8220     * @hide
8221     */
8222    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
8223        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
8224                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
8225                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
8226                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
8227        if (clear) {
8228            mPrivateFlags &= clearMask;
8229        }
8230        if (this instanceof ViewGroup) {
8231            ViewGroup parent = (ViewGroup) this;
8232            final int count = parent.getChildCount();
8233            for (int i = 0; i < count; i++) {
8234                final View child = (View) parent.getChildAt(i);
8235                child.outputDirtyFlags(indent + "  ", clear, clearMask);
8236            }
8237        }
8238    }
8239
8240    /**
8241     * This method is used by ViewGroup to cause its children to restore or recreate their
8242     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
8243     * to recreate its own display list, which would happen if it went through the normal
8244     * draw/dispatchDraw mechanisms.
8245     *
8246     * @hide
8247     */
8248    protected void dispatchGetDisplayList() {}
8249
8250    /**
8251     * <p>Returns a display list that can be used to draw this view again
8252     * without executing its draw method.</p>
8253     *
8254     * @return A DisplayList ready to replay, or null if caching is not enabled.
8255     *
8256     * @hide
8257     */
8258    public DisplayList getDisplayList() {
8259        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
8260            return null;
8261        }
8262
8263        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
8264                mDisplayList == null || !mDisplayList.isValid() ||
8265                mRecreateDisplayList)) {
8266            // Don't need to recreate the display list, just need to tell our
8267            // children to restore/recreate theirs
8268            if (mDisplayList != null && mDisplayList.isValid() &&
8269                    !mRecreateDisplayList) {
8270                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8271                mPrivateFlags &= ~DIRTY_MASK;
8272                dispatchGetDisplayList();
8273
8274                return mDisplayList;
8275            }
8276
8277            // If we got here, we're recreating it. Mark it as such to ensure that
8278            // we copy in child display lists into ours in drawChild()
8279            mRecreateDisplayList = true;
8280
8281            if (mDisplayList == null) {
8282                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this);
8283                // If we're creating a new display list, make sure our parent gets invalidated
8284                // since they will need to recreate their display list to account for this
8285                // new child display list.
8286                invalidateParentIfAccelerated();
8287            }
8288
8289            final HardwareCanvas canvas = mDisplayList.start();
8290            try {
8291                int width = mRight - mLeft;
8292                int height = mBottom - mTop;
8293
8294                canvas.setViewport(width, height);
8295                canvas.onPreDraw();
8296
8297                final int restoreCount = canvas.save();
8298
8299                computeScroll();
8300                canvas.translate(-mScrollX, -mScrollY);
8301                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
8302
8303                // Fast path for layouts with no backgrounds
8304                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8305                    mPrivateFlags &= ~DIRTY_MASK;
8306                    dispatchDraw(canvas);
8307                } else {
8308                    draw(canvas);
8309                }
8310
8311                canvas.restoreToCount(restoreCount);
8312            } finally {
8313                canvas.onPostDraw();
8314
8315                mDisplayList.end();
8316            }
8317        }
8318
8319        return mDisplayList;
8320    }
8321
8322    /**
8323     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
8324     *
8325     * @return A non-scaled bitmap representing this view or null if cache is disabled.
8326     *
8327     * @see #getDrawingCache(boolean)
8328     */
8329    public Bitmap getDrawingCache() {
8330        return getDrawingCache(false);
8331    }
8332
8333    /**
8334     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
8335     * is null when caching is disabled. If caching is enabled and the cache is not ready,
8336     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
8337     * draw from the cache when the cache is enabled. To benefit from the cache, you must
8338     * request the drawing cache by calling this method and draw it on screen if the
8339     * returned bitmap is not null.</p>
8340     *
8341     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8342     * this method will create a bitmap of the same size as this view. Because this bitmap
8343     * will be drawn scaled by the parent ViewGroup, the result on screen might show
8344     * scaling artifacts. To avoid such artifacts, you should call this method by setting
8345     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8346     * size than the view. This implies that your application must be able to handle this
8347     * size.</p>
8348     *
8349     * @param autoScale Indicates whether the generated bitmap should be scaled based on
8350     *        the current density of the screen when the application is in compatibility
8351     *        mode.
8352     *
8353     * @return A bitmap representing this view or null if cache is disabled.
8354     *
8355     * @see #setDrawingCacheEnabled(boolean)
8356     * @see #isDrawingCacheEnabled()
8357     * @see #buildDrawingCache(boolean)
8358     * @see #destroyDrawingCache()
8359     */
8360    public Bitmap getDrawingCache(boolean autoScale) {
8361        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
8362            return null;
8363        }
8364        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
8365            buildDrawingCache(autoScale);
8366        }
8367        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
8368    }
8369
8370    /**
8371     * <p>Frees the resources used by the drawing cache. If you call
8372     * {@link #buildDrawingCache()} manually without calling
8373     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8374     * should cleanup the cache with this method afterwards.</p>
8375     *
8376     * @see #setDrawingCacheEnabled(boolean)
8377     * @see #buildDrawingCache()
8378     * @see #getDrawingCache()
8379     */
8380    public void destroyDrawingCache() {
8381        if (mDrawingCache != null) {
8382            mDrawingCache.recycle();
8383            mDrawingCache = null;
8384        }
8385        if (mUnscaledDrawingCache != null) {
8386            mUnscaledDrawingCache.recycle();
8387            mUnscaledDrawingCache = null;
8388        }
8389    }
8390
8391    /**
8392     * Setting a solid background color for the drawing cache's bitmaps will improve
8393     * perfromance and memory usage. Note, though that this should only be used if this
8394     * view will always be drawn on top of a solid color.
8395     *
8396     * @param color The background color to use for the drawing cache's bitmap
8397     *
8398     * @see #setDrawingCacheEnabled(boolean)
8399     * @see #buildDrawingCache()
8400     * @see #getDrawingCache()
8401     */
8402    public void setDrawingCacheBackgroundColor(int color) {
8403        if (color != mDrawingCacheBackgroundColor) {
8404            mDrawingCacheBackgroundColor = color;
8405            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8406        }
8407    }
8408
8409    /**
8410     * @see #setDrawingCacheBackgroundColor(int)
8411     *
8412     * @return The background color to used for the drawing cache's bitmap
8413     */
8414    public int getDrawingCacheBackgroundColor() {
8415        return mDrawingCacheBackgroundColor;
8416    }
8417
8418    /**
8419     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
8420     *
8421     * @see #buildDrawingCache(boolean)
8422     */
8423    public void buildDrawingCache() {
8424        buildDrawingCache(false);
8425    }
8426
8427    /**
8428     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
8429     *
8430     * <p>If you call {@link #buildDrawingCache()} manually without calling
8431     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
8432     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
8433     *
8434     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
8435     * this method will create a bitmap of the same size as this view. Because this bitmap
8436     * will be drawn scaled by the parent ViewGroup, the result on screen might show
8437     * scaling artifacts. To avoid such artifacts, you should call this method by setting
8438     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
8439     * size than the view. This implies that your application must be able to handle this
8440     * size.</p>
8441     *
8442     * <p>You should avoid calling this method when hardware acceleration is enabled. If
8443     * you do not need the drawing cache bitmap, calling this method will increase memory
8444     * usage and cause the view to be rendered in software once, thus negatively impacting
8445     * performance.</p>
8446     *
8447     * @see #getDrawingCache()
8448     * @see #destroyDrawingCache()
8449     */
8450    public void buildDrawingCache(boolean autoScale) {
8451        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
8452                mDrawingCache == null : mUnscaledDrawingCache == null)) {
8453
8454            if (ViewDebug.TRACE_HIERARCHY) {
8455                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
8456            }
8457
8458            int width = mRight - mLeft;
8459            int height = mBottom - mTop;
8460
8461            final AttachInfo attachInfo = mAttachInfo;
8462            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
8463
8464            if (autoScale && scalingRequired) {
8465                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
8466                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
8467            }
8468
8469            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
8470            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
8471            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
8472
8473            if (width <= 0 || height <= 0 ||
8474                     // Projected bitmap size in bytes
8475                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
8476                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
8477                destroyDrawingCache();
8478                return;
8479            }
8480
8481            boolean clear = true;
8482            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
8483
8484            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
8485                Bitmap.Config quality;
8486                if (!opaque) {
8487                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
8488                        case DRAWING_CACHE_QUALITY_AUTO:
8489                            quality = Bitmap.Config.ARGB_8888;
8490                            break;
8491                        case DRAWING_CACHE_QUALITY_LOW:
8492                            quality = Bitmap.Config.ARGB_4444;
8493                            break;
8494                        case DRAWING_CACHE_QUALITY_HIGH:
8495                            quality = Bitmap.Config.ARGB_8888;
8496                            break;
8497                        default:
8498                            quality = Bitmap.Config.ARGB_8888;
8499                            break;
8500                    }
8501                } else {
8502                    // Optimization for translucent windows
8503                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
8504                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
8505                }
8506
8507                // Try to cleanup memory
8508                if (bitmap != null) bitmap.recycle();
8509
8510                try {
8511                    bitmap = Bitmap.createBitmap(width, height, quality);
8512                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8513                    if (autoScale) {
8514                        mDrawingCache = bitmap;
8515                    } else {
8516                        mUnscaledDrawingCache = bitmap;
8517                    }
8518                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
8519                } catch (OutOfMemoryError e) {
8520                    // If there is not enough memory to create the bitmap cache, just
8521                    // ignore the issue as bitmap caches are not required to draw the
8522                    // view hierarchy
8523                    if (autoScale) {
8524                        mDrawingCache = null;
8525                    } else {
8526                        mUnscaledDrawingCache = null;
8527                    }
8528                    return;
8529                }
8530
8531                clear = drawingCacheBackgroundColor != 0;
8532            }
8533
8534            Canvas canvas;
8535            if (attachInfo != null) {
8536                canvas = attachInfo.mCanvas;
8537                if (canvas == null) {
8538                    canvas = new Canvas();
8539                }
8540                canvas.setBitmap(bitmap);
8541                // Temporarily clobber the cached Canvas in case one of our children
8542                // is also using a drawing cache. Without this, the children would
8543                // steal the canvas by attaching their own bitmap to it and bad, bad
8544                // thing would happen (invisible views, corrupted drawings, etc.)
8545                attachInfo.mCanvas = null;
8546            } else {
8547                // This case should hopefully never or seldom happen
8548                canvas = new Canvas(bitmap);
8549            }
8550
8551            if (clear) {
8552                bitmap.eraseColor(drawingCacheBackgroundColor);
8553            }
8554
8555            computeScroll();
8556            final int restoreCount = canvas.save();
8557
8558            if (autoScale && scalingRequired) {
8559                final float scale = attachInfo.mApplicationScale;
8560                canvas.scale(scale, scale);
8561            }
8562
8563            canvas.translate(-mScrollX, -mScrollY);
8564
8565            mPrivateFlags |= DRAWN;
8566            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
8567                    mLayerType != LAYER_TYPE_NONE) {
8568                mPrivateFlags |= DRAWING_CACHE_VALID;
8569            }
8570
8571            // Fast path for layouts with no backgrounds
8572            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8573                if (ViewDebug.TRACE_HIERARCHY) {
8574                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8575                }
8576                mPrivateFlags &= ~DIRTY_MASK;
8577                dispatchDraw(canvas);
8578            } else {
8579                draw(canvas);
8580            }
8581
8582            canvas.restoreToCount(restoreCount);
8583
8584            if (attachInfo != null) {
8585                // Restore the cached Canvas for our siblings
8586                attachInfo.mCanvas = canvas;
8587            }
8588        }
8589    }
8590
8591    /**
8592     * Create a snapshot of the view into a bitmap.  We should probably make
8593     * some form of this public, but should think about the API.
8594     */
8595    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
8596        int width = mRight - mLeft;
8597        int height = mBottom - mTop;
8598
8599        final AttachInfo attachInfo = mAttachInfo;
8600        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
8601        width = (int) ((width * scale) + 0.5f);
8602        height = (int) ((height * scale) + 0.5f);
8603
8604        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
8605        if (bitmap == null) {
8606            throw new OutOfMemoryError();
8607        }
8608
8609        bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
8610
8611        Canvas canvas;
8612        if (attachInfo != null) {
8613            canvas = attachInfo.mCanvas;
8614            if (canvas == null) {
8615                canvas = new Canvas();
8616            }
8617            canvas.setBitmap(bitmap);
8618            // Temporarily clobber the cached Canvas in case one of our children
8619            // is also using a drawing cache. Without this, the children would
8620            // steal the canvas by attaching their own bitmap to it and bad, bad
8621            // things would happen (invisible views, corrupted drawings, etc.)
8622            attachInfo.mCanvas = null;
8623        } else {
8624            // This case should hopefully never or seldom happen
8625            canvas = new Canvas(bitmap);
8626        }
8627
8628        if ((backgroundColor & 0xff000000) != 0) {
8629            bitmap.eraseColor(backgroundColor);
8630        }
8631
8632        computeScroll();
8633        final int restoreCount = canvas.save();
8634        canvas.scale(scale, scale);
8635        canvas.translate(-mScrollX, -mScrollY);
8636
8637        // Temporarily remove the dirty mask
8638        int flags = mPrivateFlags;
8639        mPrivateFlags &= ~DIRTY_MASK;
8640
8641        // Fast path for layouts with no backgrounds
8642        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
8643            dispatchDraw(canvas);
8644        } else {
8645            draw(canvas);
8646        }
8647
8648        mPrivateFlags = flags;
8649
8650        canvas.restoreToCount(restoreCount);
8651
8652        if (attachInfo != null) {
8653            // Restore the cached Canvas for our siblings
8654            attachInfo.mCanvas = canvas;
8655        }
8656
8657        return bitmap;
8658    }
8659
8660    /**
8661     * Indicates whether this View is currently in edit mode. A View is usually
8662     * in edit mode when displayed within a developer tool. For instance, if
8663     * this View is being drawn by a visual user interface builder, this method
8664     * should return true.
8665     *
8666     * Subclasses should check the return value of this method to provide
8667     * different behaviors if their normal behavior might interfere with the
8668     * host environment. For instance: the class spawns a thread in its
8669     * constructor, the drawing code relies on device-specific features, etc.
8670     *
8671     * This method is usually checked in the drawing code of custom widgets.
8672     *
8673     * @return True if this View is in edit mode, false otherwise.
8674     */
8675    public boolean isInEditMode() {
8676        return false;
8677    }
8678
8679    /**
8680     * If the View draws content inside its padding and enables fading edges,
8681     * it needs to support padding offsets. Padding offsets are added to the
8682     * fading edges to extend the length of the fade so that it covers pixels
8683     * drawn inside the padding.
8684     *
8685     * Subclasses of this class should override this method if they need
8686     * to draw content inside the padding.
8687     *
8688     * @return True if padding offset must be applied, false otherwise.
8689     *
8690     * @see #getLeftPaddingOffset()
8691     * @see #getRightPaddingOffset()
8692     * @see #getTopPaddingOffset()
8693     * @see #getBottomPaddingOffset()
8694     *
8695     * @since CURRENT
8696     */
8697    protected boolean isPaddingOffsetRequired() {
8698        return false;
8699    }
8700
8701    /**
8702     * Amount by which to extend the left fading region. Called only when
8703     * {@link #isPaddingOffsetRequired()} returns true.
8704     *
8705     * @return The left padding offset in pixels.
8706     *
8707     * @see #isPaddingOffsetRequired()
8708     *
8709     * @since CURRENT
8710     */
8711    protected int getLeftPaddingOffset() {
8712        return 0;
8713    }
8714
8715    /**
8716     * Amount by which to extend the right fading region. Called only when
8717     * {@link #isPaddingOffsetRequired()} returns true.
8718     *
8719     * @return The right padding offset in pixels.
8720     *
8721     * @see #isPaddingOffsetRequired()
8722     *
8723     * @since CURRENT
8724     */
8725    protected int getRightPaddingOffset() {
8726        return 0;
8727    }
8728
8729    /**
8730     * Amount by which to extend the top fading region. Called only when
8731     * {@link #isPaddingOffsetRequired()} returns true.
8732     *
8733     * @return The top padding offset in pixels.
8734     *
8735     * @see #isPaddingOffsetRequired()
8736     *
8737     * @since CURRENT
8738     */
8739    protected int getTopPaddingOffset() {
8740        return 0;
8741    }
8742
8743    /**
8744     * Amount by which to extend the bottom fading region. Called only when
8745     * {@link #isPaddingOffsetRequired()} returns true.
8746     *
8747     * @return The bottom padding offset in pixels.
8748     *
8749     * @see #isPaddingOffsetRequired()
8750     *
8751     * @since CURRENT
8752     */
8753    protected int getBottomPaddingOffset() {
8754        return 0;
8755    }
8756
8757    /**
8758     * <p>Indicates whether this view is attached to an hardware accelerated
8759     * window or not.</p>
8760     *
8761     * <p>Even if this method returns true, it does not mean that every call
8762     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
8763     * accelerated {@link android.graphics.Canvas}. For instance, if this view
8764     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
8765     * window is hardware accelerated,
8766     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
8767     * return false, and this method will return true.</p>
8768     *
8769     * @return True if the view is attached to a window and the window is
8770     *         hardware accelerated; false in any other case.
8771     */
8772    public boolean isHardwareAccelerated() {
8773        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
8774    }
8775
8776    /**
8777     * Manually render this view (and all of its children) to the given Canvas.
8778     * The view must have already done a full layout before this function is
8779     * called.  When implementing a view, implement {@link #onDraw} instead of
8780     * overriding this method. If you do need to override this method, call
8781     * the superclass version.
8782     *
8783     * @param canvas The Canvas to which the View is rendered.
8784     */
8785    public void draw(Canvas canvas) {
8786        if (ViewDebug.TRACE_HIERARCHY) {
8787            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
8788        }
8789
8790        final int privateFlags = mPrivateFlags;
8791        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
8792                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
8793        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
8794
8795        /*
8796         * Draw traversal performs several drawing steps which must be executed
8797         * in the appropriate order:
8798         *
8799         *      1. Draw the background
8800         *      2. If necessary, save the canvas' layers to prepare for fading
8801         *      3. Draw view's content
8802         *      4. Draw children
8803         *      5. If necessary, draw the fading edges and restore layers
8804         *      6. Draw decorations (scrollbars for instance)
8805         */
8806
8807        // Step 1, draw the background, if needed
8808        int saveCount;
8809
8810        if (!dirtyOpaque) {
8811            final Drawable background = mBGDrawable;
8812            if (background != null) {
8813                final int scrollX = mScrollX;
8814                final int scrollY = mScrollY;
8815
8816                if (mBackgroundSizeChanged) {
8817                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
8818                    mBackgroundSizeChanged = false;
8819                }
8820
8821                if ((scrollX | scrollY) == 0) {
8822                    background.draw(canvas);
8823                } else {
8824                    canvas.translate(scrollX, scrollY);
8825                    background.draw(canvas);
8826                    canvas.translate(-scrollX, -scrollY);
8827                }
8828            }
8829        }
8830
8831        // skip step 2 & 5 if possible (common case)
8832        final int viewFlags = mViewFlags;
8833        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
8834        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
8835        if (!verticalEdges && !horizontalEdges) {
8836            // Step 3, draw the content
8837            if (!dirtyOpaque) onDraw(canvas);
8838
8839            // Step 4, draw the children
8840            dispatchDraw(canvas);
8841
8842            // Step 6, draw decorations (scrollbars)
8843            onDrawScrollBars(canvas);
8844
8845            // we're done...
8846            return;
8847        }
8848
8849        /*
8850         * Here we do the full fledged routine...
8851         * (this is an uncommon case where speed matters less,
8852         * this is why we repeat some of the tests that have been
8853         * done above)
8854         */
8855
8856        boolean drawTop = false;
8857        boolean drawBottom = false;
8858        boolean drawLeft = false;
8859        boolean drawRight = false;
8860
8861        float topFadeStrength = 0.0f;
8862        float bottomFadeStrength = 0.0f;
8863        float leftFadeStrength = 0.0f;
8864        float rightFadeStrength = 0.0f;
8865
8866        // Step 2, save the canvas' layers
8867        int paddingLeft = mPaddingLeft;
8868        int paddingTop = mPaddingTop;
8869
8870        final boolean offsetRequired = isPaddingOffsetRequired();
8871        if (offsetRequired) {
8872            paddingLeft += getLeftPaddingOffset();
8873            paddingTop += getTopPaddingOffset();
8874        }
8875
8876        int left = mScrollX + paddingLeft;
8877        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
8878        int top = mScrollY + paddingTop;
8879        int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
8880
8881        if (offsetRequired) {
8882            right += getRightPaddingOffset();
8883            bottom += getBottomPaddingOffset();
8884        }
8885
8886        final ScrollabilityCache scrollabilityCache = mScrollCache;
8887        int length = scrollabilityCache.fadingEdgeLength;
8888
8889        // clip the fade length if top and bottom fades overlap
8890        // overlapping fades produce odd-looking artifacts
8891        if (verticalEdges && (top + length > bottom - length)) {
8892            length = (bottom - top) / 2;
8893        }
8894
8895        // also clip horizontal fades if necessary
8896        if (horizontalEdges && (left + length > right - length)) {
8897            length = (right - left) / 2;
8898        }
8899
8900        if (verticalEdges) {
8901            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
8902            drawTop = topFadeStrength > 0.0f;
8903            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
8904            drawBottom = bottomFadeStrength > 0.0f;
8905        }
8906
8907        if (horizontalEdges) {
8908            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
8909            drawLeft = leftFadeStrength > 0.0f;
8910            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
8911            drawRight = rightFadeStrength > 0.0f;
8912        }
8913
8914        saveCount = canvas.getSaveCount();
8915
8916        int solidColor = getSolidColor();
8917        if (solidColor == 0) {
8918            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
8919
8920            if (drawTop) {
8921                canvas.saveLayer(left, top, right, top + length, null, flags);
8922            }
8923
8924            if (drawBottom) {
8925                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
8926            }
8927
8928            if (drawLeft) {
8929                canvas.saveLayer(left, top, left + length, bottom, null, flags);
8930            }
8931
8932            if (drawRight) {
8933                canvas.saveLayer(right - length, top, right, bottom, null, flags);
8934            }
8935        } else {
8936            scrollabilityCache.setFadeColor(solidColor);
8937        }
8938
8939        // Step 3, draw the content
8940        if (!dirtyOpaque) onDraw(canvas);
8941
8942        // Step 4, draw the children
8943        dispatchDraw(canvas);
8944
8945        // Step 5, draw the fade effect and restore layers
8946        final Paint p = scrollabilityCache.paint;
8947        final Matrix matrix = scrollabilityCache.matrix;
8948        final Shader fade = scrollabilityCache.shader;
8949        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
8950
8951        if (drawTop) {
8952            matrix.setScale(1, fadeHeight * topFadeStrength);
8953            matrix.postTranslate(left, top);
8954            fade.setLocalMatrix(matrix);
8955            canvas.drawRect(left, top, right, top + length, p);
8956        }
8957
8958        if (drawBottom) {
8959            matrix.setScale(1, fadeHeight * bottomFadeStrength);
8960            matrix.postRotate(180);
8961            matrix.postTranslate(left, bottom);
8962            fade.setLocalMatrix(matrix);
8963            canvas.drawRect(left, bottom - length, right, bottom, p);
8964        }
8965
8966        if (drawLeft) {
8967            matrix.setScale(1, fadeHeight * leftFadeStrength);
8968            matrix.postRotate(-90);
8969            matrix.postTranslate(left, top);
8970            fade.setLocalMatrix(matrix);
8971            canvas.drawRect(left, top, left + length, bottom, p);
8972        }
8973
8974        if (drawRight) {
8975            matrix.setScale(1, fadeHeight * rightFadeStrength);
8976            matrix.postRotate(90);
8977            matrix.postTranslate(right, top);
8978            fade.setLocalMatrix(matrix);
8979            canvas.drawRect(right - length, top, right, bottom, p);
8980        }
8981
8982        canvas.restoreToCount(saveCount);
8983
8984        // Step 6, draw decorations (scrollbars)
8985        onDrawScrollBars(canvas);
8986    }
8987
8988    /**
8989     * Override this if your view is known to always be drawn on top of a solid color background,
8990     * and needs to draw fading edges. Returning a non-zero color enables the view system to
8991     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
8992     * should be set to 0xFF.
8993     *
8994     * @see #setVerticalFadingEdgeEnabled
8995     * @see #setHorizontalFadingEdgeEnabled
8996     *
8997     * @return The known solid color background for this view, or 0 if the color may vary
8998     */
8999    public int getSolidColor() {
9000        return 0;
9001    }
9002
9003    /**
9004     * Build a human readable string representation of the specified view flags.
9005     *
9006     * @param flags the view flags to convert to a string
9007     * @return a String representing the supplied flags
9008     */
9009    private static String printFlags(int flags) {
9010        String output = "";
9011        int numFlags = 0;
9012        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
9013            output += "TAKES_FOCUS";
9014            numFlags++;
9015        }
9016
9017        switch (flags & VISIBILITY_MASK) {
9018        case INVISIBLE:
9019            if (numFlags > 0) {
9020                output += " ";
9021            }
9022            output += "INVISIBLE";
9023            // USELESS HERE numFlags++;
9024            break;
9025        case GONE:
9026            if (numFlags > 0) {
9027                output += " ";
9028            }
9029            output += "GONE";
9030            // USELESS HERE numFlags++;
9031            break;
9032        default:
9033            break;
9034        }
9035        return output;
9036    }
9037
9038    /**
9039     * Build a human readable string representation of the specified private
9040     * view flags.
9041     *
9042     * @param privateFlags the private view flags to convert to a string
9043     * @return a String representing the supplied flags
9044     */
9045    private static String printPrivateFlags(int privateFlags) {
9046        String output = "";
9047        int numFlags = 0;
9048
9049        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
9050            output += "WANTS_FOCUS";
9051            numFlags++;
9052        }
9053
9054        if ((privateFlags & FOCUSED) == FOCUSED) {
9055            if (numFlags > 0) {
9056                output += " ";
9057            }
9058            output += "FOCUSED";
9059            numFlags++;
9060        }
9061
9062        if ((privateFlags & SELECTED) == SELECTED) {
9063            if (numFlags > 0) {
9064                output += " ";
9065            }
9066            output += "SELECTED";
9067            numFlags++;
9068        }
9069
9070        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
9071            if (numFlags > 0) {
9072                output += " ";
9073            }
9074            output += "IS_ROOT_NAMESPACE";
9075            numFlags++;
9076        }
9077
9078        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
9079            if (numFlags > 0) {
9080                output += " ";
9081            }
9082            output += "HAS_BOUNDS";
9083            numFlags++;
9084        }
9085
9086        if ((privateFlags & DRAWN) == DRAWN) {
9087            if (numFlags > 0) {
9088                output += " ";
9089            }
9090            output += "DRAWN";
9091            // USELESS HERE numFlags++;
9092        }
9093        return output;
9094    }
9095
9096    /**
9097     * <p>Indicates whether or not this view's layout will be requested during
9098     * the next hierarchy layout pass.</p>
9099     *
9100     * @return true if the layout will be forced during next layout pass
9101     */
9102    public boolean isLayoutRequested() {
9103        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
9104    }
9105
9106    /**
9107     * Assign a size and position to a view and all of its
9108     * descendants
9109     *
9110     * <p>This is the second phase of the layout mechanism.
9111     * (The first is measuring). In this phase, each parent calls
9112     * layout on all of its children to position them.
9113     * This is typically done using the child measurements
9114     * that were stored in the measure pass().</p>
9115     *
9116     * <p>Derived classes should not override this method.
9117     * Derived classes with children should override
9118     * onLayout. In that method, they should
9119     * call layout on each of their children.</p>
9120     *
9121     * @param l Left position, relative to parent
9122     * @param t Top position, relative to parent
9123     * @param r Right position, relative to parent
9124     * @param b Bottom position, relative to parent
9125     */
9126    @SuppressWarnings({"unchecked"})
9127    public void layout(int l, int t, int r, int b) {
9128        int oldL = mLeft;
9129        int oldT = mTop;
9130        int oldB = mBottom;
9131        int oldR = mRight;
9132        boolean changed = setFrame(l, t, r, b);
9133        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
9134            if (ViewDebug.TRACE_HIERARCHY) {
9135                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
9136            }
9137
9138            onLayout(changed, l, t, r, b);
9139            mPrivateFlags &= ~LAYOUT_REQUIRED;
9140
9141            if (mOnLayoutChangeListeners != null) {
9142                ArrayList<OnLayoutChangeListener> listenersCopy =
9143                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
9144                int numListeners = listenersCopy.size();
9145                for (int i = 0; i < numListeners; ++i) {
9146                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
9147                }
9148            }
9149        }
9150        mPrivateFlags &= ~FORCE_LAYOUT;
9151    }
9152
9153    /**
9154     * Called from layout when this view should
9155     * assign a size and position to each of its children.
9156     *
9157     * Derived classes with children should override
9158     * this method and call layout on each of
9159     * their children.
9160     * @param changed This is a new size or position for this view
9161     * @param left Left position, relative to parent
9162     * @param top Top position, relative to parent
9163     * @param right Right position, relative to parent
9164     * @param bottom Bottom position, relative to parent
9165     */
9166    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
9167    }
9168
9169    /**
9170     * Assign a size and position to this view.
9171     *
9172     * This is called from layout.
9173     *
9174     * @param left Left position, relative to parent
9175     * @param top Top position, relative to parent
9176     * @param right Right position, relative to parent
9177     * @param bottom Bottom position, relative to parent
9178     * @return true if the new size and position are different than the
9179     *         previous ones
9180     * {@hide}
9181     */
9182    protected boolean setFrame(int left, int top, int right, int bottom) {
9183        boolean changed = false;
9184
9185        if (DBG) {
9186            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
9187                    + right + "," + bottom + ")");
9188        }
9189
9190        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
9191            changed = true;
9192
9193            // Remember our drawn bit
9194            int drawn = mPrivateFlags & DRAWN;
9195
9196            // Invalidate our old position
9197            invalidate();
9198
9199
9200            int oldWidth = mRight - mLeft;
9201            int oldHeight = mBottom - mTop;
9202
9203            mLeft = left;
9204            mTop = top;
9205            mRight = right;
9206            mBottom = bottom;
9207
9208            mPrivateFlags |= HAS_BOUNDS;
9209
9210            int newWidth = right - left;
9211            int newHeight = bottom - top;
9212
9213            if (newWidth != oldWidth || newHeight != oldHeight) {
9214                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
9215                    // A change in dimension means an auto-centered pivot point changes, too
9216                    mMatrixDirty = true;
9217                }
9218                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
9219            }
9220
9221            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
9222                // If we are visible, force the DRAWN bit to on so that
9223                // this invalidate will go through (at least to our parent).
9224                // This is because someone may have invalidated this view
9225                // before this call to setFrame came in, thereby clearing
9226                // the DRAWN bit.
9227                mPrivateFlags |= DRAWN;
9228                invalidate();
9229            }
9230
9231            // Reset drawn bit to original value (invalidate turns it off)
9232            mPrivateFlags |= drawn;
9233
9234            mBackgroundSizeChanged = true;
9235        }
9236        return changed;
9237    }
9238
9239    /**
9240     * Finalize inflating a view from XML.  This is called as the last phase
9241     * of inflation, after all child views have been added.
9242     *
9243     * <p>Even if the subclass overrides onFinishInflate, they should always be
9244     * sure to call the super method, so that we get called.
9245     */
9246    protected void onFinishInflate() {
9247    }
9248
9249    /**
9250     * Returns the resources associated with this view.
9251     *
9252     * @return Resources object.
9253     */
9254    public Resources getResources() {
9255        return mResources;
9256    }
9257
9258    /**
9259     * Invalidates the specified Drawable.
9260     *
9261     * @param drawable the drawable to invalidate
9262     */
9263    public void invalidateDrawable(Drawable drawable) {
9264        if (verifyDrawable(drawable)) {
9265            final Rect dirty = drawable.getBounds();
9266            final int scrollX = mScrollX;
9267            final int scrollY = mScrollY;
9268
9269            invalidate(dirty.left + scrollX, dirty.top + scrollY,
9270                    dirty.right + scrollX, dirty.bottom + scrollY);
9271        }
9272    }
9273
9274    /**
9275     * Schedules an action on a drawable to occur at a specified time.
9276     *
9277     * @param who the recipient of the action
9278     * @param what the action to run on the drawable
9279     * @param when the time at which the action must occur. Uses the
9280     *        {@link SystemClock#uptimeMillis} timebase.
9281     */
9282    public void scheduleDrawable(Drawable who, Runnable what, long when) {
9283        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9284            mAttachInfo.mHandler.postAtTime(what, who, when);
9285        }
9286    }
9287
9288    /**
9289     * Cancels a scheduled action on a drawable.
9290     *
9291     * @param who the recipient of the action
9292     * @param what the action to cancel
9293     */
9294    public void unscheduleDrawable(Drawable who, Runnable what) {
9295        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
9296            mAttachInfo.mHandler.removeCallbacks(what, who);
9297        }
9298    }
9299
9300    /**
9301     * Unschedule any events associated with the given Drawable.  This can be
9302     * used when selecting a new Drawable into a view, so that the previous
9303     * one is completely unscheduled.
9304     *
9305     * @param who The Drawable to unschedule.
9306     *
9307     * @see #drawableStateChanged
9308     */
9309    public void unscheduleDrawable(Drawable who) {
9310        if (mAttachInfo != null) {
9311            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
9312        }
9313    }
9314
9315    /**
9316     * If your view subclass is displaying its own Drawable objects, it should
9317     * override this function and return true for any Drawable it is
9318     * displaying.  This allows animations for those drawables to be
9319     * scheduled.
9320     *
9321     * <p>Be sure to call through to the super class when overriding this
9322     * function.
9323     *
9324     * @param who The Drawable to verify.  Return true if it is one you are
9325     *            displaying, else return the result of calling through to the
9326     *            super class.
9327     *
9328     * @return boolean If true than the Drawable is being displayed in the
9329     *         view; else false and it is not allowed to animate.
9330     *
9331     * @see #unscheduleDrawable
9332     * @see #drawableStateChanged
9333     */
9334    protected boolean verifyDrawable(Drawable who) {
9335        return who == mBGDrawable;
9336    }
9337
9338    /**
9339     * This function is called whenever the state of the view changes in such
9340     * a way that it impacts the state of drawables being shown.
9341     *
9342     * <p>Be sure to call through to the superclass when overriding this
9343     * function.
9344     *
9345     * @see Drawable#setState
9346     */
9347    protected void drawableStateChanged() {
9348        Drawable d = mBGDrawable;
9349        if (d != null && d.isStateful()) {
9350            d.setState(getDrawableState());
9351        }
9352    }
9353
9354    /**
9355     * Call this to force a view to update its drawable state. This will cause
9356     * drawableStateChanged to be called on this view. Views that are interested
9357     * in the new state should call getDrawableState.
9358     *
9359     * @see #drawableStateChanged
9360     * @see #getDrawableState
9361     */
9362    public void refreshDrawableState() {
9363        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9364        drawableStateChanged();
9365
9366        ViewParent parent = mParent;
9367        if (parent != null) {
9368            parent.childDrawableStateChanged(this);
9369        }
9370    }
9371
9372    /**
9373     * Return an array of resource IDs of the drawable states representing the
9374     * current state of the view.
9375     *
9376     * @return The current drawable state
9377     *
9378     * @see Drawable#setState
9379     * @see #drawableStateChanged
9380     * @see #onCreateDrawableState
9381     */
9382    public final int[] getDrawableState() {
9383        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
9384            return mDrawableState;
9385        } else {
9386            mDrawableState = onCreateDrawableState(0);
9387            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
9388            return mDrawableState;
9389        }
9390    }
9391
9392    /**
9393     * Generate the new {@link android.graphics.drawable.Drawable} state for
9394     * this view. This is called by the view
9395     * system when the cached Drawable state is determined to be invalid.  To
9396     * retrieve the current state, you should use {@link #getDrawableState}.
9397     *
9398     * @param extraSpace if non-zero, this is the number of extra entries you
9399     * would like in the returned array in which you can place your own
9400     * states.
9401     *
9402     * @return Returns an array holding the current {@link Drawable} state of
9403     * the view.
9404     *
9405     * @see #mergeDrawableStates
9406     */
9407    protected int[] onCreateDrawableState(int extraSpace) {
9408        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
9409                mParent instanceof View) {
9410            return ((View) mParent).onCreateDrawableState(extraSpace);
9411        }
9412
9413        int[] drawableState;
9414
9415        int privateFlags = mPrivateFlags;
9416
9417        int viewStateIndex = 0;
9418        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
9419        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
9420        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
9421        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
9422        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
9423        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
9424        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested) {
9425            // This is set if HW acceleration is requested, even if the current
9426            // process doesn't allow it.  This is just to allow app preview
9427            // windows to better match their app.
9428            viewStateIndex |= VIEW_STATE_ACCELERATED;
9429        }
9430
9431        drawableState = VIEW_STATE_SETS[viewStateIndex];
9432
9433        //noinspection ConstantIfStatement
9434        if (false) {
9435            Log.i("View", "drawableStateIndex=" + viewStateIndex);
9436            Log.i("View", toString()
9437                    + " pressed=" + ((privateFlags & PRESSED) != 0)
9438                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
9439                    + " fo=" + hasFocus()
9440                    + " sl=" + ((privateFlags & SELECTED) != 0)
9441                    + " wf=" + hasWindowFocus()
9442                    + ": " + Arrays.toString(drawableState));
9443        }
9444
9445        if (extraSpace == 0) {
9446            return drawableState;
9447        }
9448
9449        final int[] fullState;
9450        if (drawableState != null) {
9451            fullState = new int[drawableState.length + extraSpace];
9452            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
9453        } else {
9454            fullState = new int[extraSpace];
9455        }
9456
9457        return fullState;
9458    }
9459
9460    /**
9461     * Merge your own state values in <var>additionalState</var> into the base
9462     * state values <var>baseState</var> that were returned by
9463     * {@link #onCreateDrawableState}.
9464     *
9465     * @param baseState The base state values returned by
9466     * {@link #onCreateDrawableState}, which will be modified to also hold your
9467     * own additional state values.
9468     *
9469     * @param additionalState The additional state values you would like
9470     * added to <var>baseState</var>; this array is not modified.
9471     *
9472     * @return As a convenience, the <var>baseState</var> array you originally
9473     * passed into the function is returned.
9474     *
9475     * @see #onCreateDrawableState
9476     */
9477    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
9478        final int N = baseState.length;
9479        int i = N - 1;
9480        while (i >= 0 && baseState[i] == 0) {
9481            i--;
9482        }
9483        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
9484        return baseState;
9485    }
9486
9487    /**
9488     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
9489     * on all Drawable objects associated with this view.
9490     */
9491    public void jumpDrawablesToCurrentState() {
9492        if (mBGDrawable != null) {
9493            mBGDrawable.jumpToCurrentState();
9494        }
9495    }
9496
9497    /**
9498     * Sets the background color for this view.
9499     * @param color the color of the background
9500     */
9501    @RemotableViewMethod
9502    public void setBackgroundColor(int color) {
9503        if (mBGDrawable instanceof ColorDrawable) {
9504            ((ColorDrawable) mBGDrawable).setColor(color);
9505        } else {
9506            setBackgroundDrawable(new ColorDrawable(color));
9507        }
9508    }
9509
9510    /**
9511     * Set the background to a given resource. The resource should refer to
9512     * a Drawable object or 0 to remove the background.
9513     * @param resid The identifier of the resource.
9514     * @attr ref android.R.styleable#View_background
9515     */
9516    @RemotableViewMethod
9517    public void setBackgroundResource(int resid) {
9518        if (resid != 0 && resid == mBackgroundResource) {
9519            return;
9520        }
9521
9522        Drawable d= null;
9523        if (resid != 0) {
9524            d = mResources.getDrawable(resid);
9525        }
9526        setBackgroundDrawable(d);
9527
9528        mBackgroundResource = resid;
9529    }
9530
9531    /**
9532     * Set the background to a given Drawable, or remove the background. If the
9533     * background has padding, this View's padding is set to the background's
9534     * padding. However, when a background is removed, this View's padding isn't
9535     * touched. If setting the padding is desired, please use
9536     * {@link #setPadding(int, int, int, int)}.
9537     *
9538     * @param d The Drawable to use as the background, or null to remove the
9539     *        background
9540     */
9541    public void setBackgroundDrawable(Drawable d) {
9542        boolean requestLayout = false;
9543
9544        mBackgroundResource = 0;
9545
9546        /*
9547         * Regardless of whether we're setting a new background or not, we want
9548         * to clear the previous drawable.
9549         */
9550        if (mBGDrawable != null) {
9551            mBGDrawable.setCallback(null);
9552            unscheduleDrawable(mBGDrawable);
9553        }
9554
9555        if (d != null) {
9556            Rect padding = sThreadLocal.get();
9557            if (padding == null) {
9558                padding = new Rect();
9559                sThreadLocal.set(padding);
9560            }
9561            if (d.getPadding(padding)) {
9562                setPadding(padding.left, padding.top, padding.right, padding.bottom);
9563            }
9564
9565            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
9566            // if it has a different minimum size, we should layout again
9567            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
9568                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
9569                requestLayout = true;
9570            }
9571
9572            d.setCallback(this);
9573            if (d.isStateful()) {
9574                d.setState(getDrawableState());
9575            }
9576            d.setVisible(getVisibility() == VISIBLE, false);
9577            mBGDrawable = d;
9578
9579            if ((mPrivateFlags & SKIP_DRAW) != 0) {
9580                mPrivateFlags &= ~SKIP_DRAW;
9581                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
9582                requestLayout = true;
9583            }
9584        } else {
9585            /* Remove the background */
9586            mBGDrawable = null;
9587
9588            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
9589                /*
9590                 * This view ONLY drew the background before and we're removing
9591                 * the background, so now it won't draw anything
9592                 * (hence we SKIP_DRAW)
9593                 */
9594                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
9595                mPrivateFlags |= SKIP_DRAW;
9596            }
9597
9598            /*
9599             * When the background is set, we try to apply its padding to this
9600             * View. When the background is removed, we don't touch this View's
9601             * padding. This is noted in the Javadocs. Hence, we don't need to
9602             * requestLayout(), the invalidate() below is sufficient.
9603             */
9604
9605            // The old background's minimum size could have affected this
9606            // View's layout, so let's requestLayout
9607            requestLayout = true;
9608        }
9609
9610        computeOpaqueFlags();
9611
9612        if (requestLayout) {
9613            requestLayout();
9614        }
9615
9616        mBackgroundSizeChanged = true;
9617        invalidate();
9618    }
9619
9620    /**
9621     * Gets the background drawable
9622     * @return The drawable used as the background for this view, if any.
9623     */
9624    public Drawable getBackground() {
9625        return mBGDrawable;
9626    }
9627
9628    /**
9629     * Sets the padding. The view may add on the space required to display
9630     * the scrollbars, depending on the style and visibility of the scrollbars.
9631     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
9632     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
9633     * from the values set in this call.
9634     *
9635     * @attr ref android.R.styleable#View_padding
9636     * @attr ref android.R.styleable#View_paddingBottom
9637     * @attr ref android.R.styleable#View_paddingLeft
9638     * @attr ref android.R.styleable#View_paddingRight
9639     * @attr ref android.R.styleable#View_paddingTop
9640     * @param left the left padding in pixels
9641     * @param top the top padding in pixels
9642     * @param right the right padding in pixels
9643     * @param bottom the bottom padding in pixels
9644     */
9645    public void setPadding(int left, int top, int right, int bottom) {
9646        boolean changed = false;
9647
9648        mUserPaddingLeft = left;
9649        mUserPaddingRight = right;
9650        mUserPaddingBottom = bottom;
9651
9652        final int viewFlags = mViewFlags;
9653
9654        // Common case is there are no scroll bars.
9655        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
9656            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
9657                // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
9658                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
9659                        ? 0 : getVerticalScrollbarWidth();
9660                switch (mVerticalScrollbarPosition) {
9661                    case SCROLLBAR_POSITION_DEFAULT:
9662                    case SCROLLBAR_POSITION_RIGHT:
9663                        right += offset;
9664                        break;
9665                    case SCROLLBAR_POSITION_LEFT:
9666                        left += offset;
9667                        break;
9668                }
9669            }
9670            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
9671                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
9672                        ? 0 : getHorizontalScrollbarHeight();
9673            }
9674        }
9675
9676        if (mPaddingLeft != left) {
9677            changed = true;
9678            mPaddingLeft = left;
9679        }
9680        if (mPaddingTop != top) {
9681            changed = true;
9682            mPaddingTop = top;
9683        }
9684        if (mPaddingRight != right) {
9685            changed = true;
9686            mPaddingRight = right;
9687        }
9688        if (mPaddingBottom != bottom) {
9689            changed = true;
9690            mPaddingBottom = bottom;
9691        }
9692
9693        if (changed) {
9694            requestLayout();
9695        }
9696    }
9697
9698    /**
9699     * Returns the top padding of this view.
9700     *
9701     * @return the top padding in pixels
9702     */
9703    public int getPaddingTop() {
9704        return mPaddingTop;
9705    }
9706
9707    /**
9708     * Returns the bottom padding of this view. If there are inset and enabled
9709     * scrollbars, this value may include the space required to display the
9710     * scrollbars as well.
9711     *
9712     * @return the bottom padding in pixels
9713     */
9714    public int getPaddingBottom() {
9715        return mPaddingBottom;
9716    }
9717
9718    /**
9719     * Returns the left 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 left padding in pixels
9724     */
9725    public int getPaddingLeft() {
9726        return mPaddingLeft;
9727    }
9728
9729    /**
9730     * Returns the right 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 right padding in pixels
9735     */
9736    public int getPaddingRight() {
9737        return mPaddingRight;
9738    }
9739
9740    /**
9741     * Changes the selection state of this view. A view can be selected or not.
9742     * Note that selection is not the same as focus. Views are typically
9743     * selected in the context of an AdapterView like ListView or GridView;
9744     * the selected view is the view that is highlighted.
9745     *
9746     * @param selected true if the view must be selected, false otherwise
9747     */
9748    public void setSelected(boolean selected) {
9749        if (((mPrivateFlags & SELECTED) != 0) != selected) {
9750            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
9751            if (!selected) resetPressedState();
9752            invalidate();
9753            refreshDrawableState();
9754            dispatchSetSelected(selected);
9755        }
9756    }
9757
9758    /**
9759     * Dispatch setSelected to all of this View's children.
9760     *
9761     * @see #setSelected(boolean)
9762     *
9763     * @param selected The new selected state
9764     */
9765    protected void dispatchSetSelected(boolean selected) {
9766    }
9767
9768    /**
9769     * Indicates the selection state of this view.
9770     *
9771     * @return true if the view is selected, false otherwise
9772     */
9773    @ViewDebug.ExportedProperty
9774    public boolean isSelected() {
9775        return (mPrivateFlags & SELECTED) != 0;
9776    }
9777
9778    /**
9779     * Changes the activated state of this view. A view can be activated or not.
9780     * Note that activation is not the same as selection.  Selection is
9781     * a transient property, representing the view (hierarchy) the user is
9782     * currently interacting with.  Activation is a longer-term state that the
9783     * user can move views in and out of.  For example, in a list view with
9784     * single or multiple selection enabled, the views in the current selection
9785     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
9786     * here.)  The activated state is propagated down to children of the view it
9787     * is set on.
9788     *
9789     * @param activated true if the view must be activated, false otherwise
9790     */
9791    public void setActivated(boolean activated) {
9792        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
9793            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
9794            invalidate();
9795            refreshDrawableState();
9796            dispatchSetActivated(activated);
9797        }
9798    }
9799
9800    /**
9801     * Dispatch setActivated to all of this View's children.
9802     *
9803     * @see #setActivated(boolean)
9804     *
9805     * @param activated The new activated state
9806     */
9807    protected void dispatchSetActivated(boolean activated) {
9808    }
9809
9810    /**
9811     * Indicates the activation state of this view.
9812     *
9813     * @return true if the view is activated, false otherwise
9814     */
9815    @ViewDebug.ExportedProperty
9816    public boolean isActivated() {
9817        return (mPrivateFlags & ACTIVATED) != 0;
9818    }
9819
9820    /**
9821     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
9822     * observer can be used to get notifications when global events, like
9823     * layout, happen.
9824     *
9825     * The returned ViewTreeObserver observer is not guaranteed to remain
9826     * valid for the lifetime of this View. If the caller of this method keeps
9827     * a long-lived reference to ViewTreeObserver, it should always check for
9828     * the return value of {@link ViewTreeObserver#isAlive()}.
9829     *
9830     * @return The ViewTreeObserver for this view's hierarchy.
9831     */
9832    public ViewTreeObserver getViewTreeObserver() {
9833        if (mAttachInfo != null) {
9834            return mAttachInfo.mTreeObserver;
9835        }
9836        if (mFloatingTreeObserver == null) {
9837            mFloatingTreeObserver = new ViewTreeObserver();
9838        }
9839        return mFloatingTreeObserver;
9840    }
9841
9842    /**
9843     * <p>Finds the topmost view in the current view hierarchy.</p>
9844     *
9845     * @return the topmost view containing this view
9846     */
9847    public View getRootView() {
9848        if (mAttachInfo != null) {
9849            final View v = mAttachInfo.mRootView;
9850            if (v != null) {
9851                return v;
9852            }
9853        }
9854
9855        View parent = this;
9856
9857        while (parent.mParent != null && parent.mParent instanceof View) {
9858            parent = (View) parent.mParent;
9859        }
9860
9861        return parent;
9862    }
9863
9864    /**
9865     * <p>Computes the coordinates of this view on the screen. The argument
9866     * must be an array of two integers. After the method returns, the array
9867     * contains the x and y location in that order.</p>
9868     *
9869     * @param location an array of two integers in which to hold the coordinates
9870     */
9871    public void getLocationOnScreen(int[] location) {
9872        getLocationInWindow(location);
9873
9874        final AttachInfo info = mAttachInfo;
9875        if (info != null) {
9876            location[0] += info.mWindowLeft;
9877            location[1] += info.mWindowTop;
9878        }
9879    }
9880
9881    /**
9882     * <p>Computes the coordinates of this view in its window. The argument
9883     * must be an array of two integers. After the method returns, the array
9884     * contains the x and y location in that order.</p>
9885     *
9886     * @param location an array of two integers in which to hold the coordinates
9887     */
9888    public void getLocationInWindow(int[] location) {
9889        if (location == null || location.length < 2) {
9890            throw new IllegalArgumentException("location must be an array of "
9891                    + "two integers");
9892        }
9893
9894        location[0] = mLeft + (int) (mTranslationX + 0.5f);
9895        location[1] = mTop + (int) (mTranslationY + 0.5f);
9896
9897        ViewParent viewParent = mParent;
9898        while (viewParent instanceof View) {
9899            final View view = (View)viewParent;
9900            location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
9901            location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
9902            viewParent = view.mParent;
9903        }
9904
9905        if (viewParent instanceof ViewRoot) {
9906            // *cough*
9907            final ViewRoot vr = (ViewRoot)viewParent;
9908            location[1] -= vr.mCurScrollY;
9909        }
9910    }
9911
9912    /**
9913     * {@hide}
9914     * @param id the id of the view to be found
9915     * @return the view of the specified id, null if cannot be found
9916     */
9917    protected View findViewTraversal(int id) {
9918        if (id == mID) {
9919            return this;
9920        }
9921        return null;
9922    }
9923
9924    /**
9925     * {@hide}
9926     * @param tag the tag of the view to be found
9927     * @return the view of specified tag, null if cannot be found
9928     */
9929    protected View findViewWithTagTraversal(Object tag) {
9930        if (tag != null && tag.equals(mTag)) {
9931            return this;
9932        }
9933        return null;
9934    }
9935
9936    /**
9937     * {@hide}
9938     * @param predicate The predicate to evaluate.
9939     * @return The first view that matches the predicate or null.
9940     */
9941    protected View findViewByPredicateTraversal(Predicate<View> predicate) {
9942        if (predicate.apply(this)) {
9943            return this;
9944        }
9945        return null;
9946    }
9947
9948    /**
9949     * Look for a child view with the given id.  If this view has the given
9950     * id, return this view.
9951     *
9952     * @param id The id to search for.
9953     * @return The view that has the given id in the hierarchy or null
9954     */
9955    public final View findViewById(int id) {
9956        if (id < 0) {
9957            return null;
9958        }
9959        return findViewTraversal(id);
9960    }
9961
9962    /**
9963     * Look for a child view with the given tag.  If this view has the given
9964     * tag, return this view.
9965     *
9966     * @param tag The tag to search for, using "tag.equals(getTag())".
9967     * @return The View that has the given tag in the hierarchy or null
9968     */
9969    public final View findViewWithTag(Object tag) {
9970        if (tag == null) {
9971            return null;
9972        }
9973        return findViewWithTagTraversal(tag);
9974    }
9975
9976    /**
9977     * {@hide}
9978     * Look for a child view that matches the specified predicate.
9979     * If this view matches the predicate, return this view.
9980     *
9981     * @param predicate The predicate to evaluate.
9982     * @return The first view that matches the predicate or null.
9983     */
9984    public final View findViewByPredicate(Predicate<View> predicate) {
9985        return findViewByPredicateTraversal(predicate);
9986    }
9987
9988    /**
9989     * Sets the identifier for this view. The identifier does not have to be
9990     * unique in this view's hierarchy. The identifier should be a positive
9991     * number.
9992     *
9993     * @see #NO_ID
9994     * @see #getId
9995     * @see #findViewById
9996     *
9997     * @param id a number used to identify the view
9998     *
9999     * @attr ref android.R.styleable#View_id
10000     */
10001    public void setId(int id) {
10002        mID = id;
10003    }
10004
10005    /**
10006     * {@hide}
10007     *
10008     * @param isRoot true if the view belongs to the root namespace, false
10009     *        otherwise
10010     */
10011    public void setIsRootNamespace(boolean isRoot) {
10012        if (isRoot) {
10013            mPrivateFlags |= IS_ROOT_NAMESPACE;
10014        } else {
10015            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
10016        }
10017    }
10018
10019    /**
10020     * {@hide}
10021     *
10022     * @return true if the view belongs to the root namespace, false otherwise
10023     */
10024    public boolean isRootNamespace() {
10025        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
10026    }
10027
10028    /**
10029     * Returns this view's identifier.
10030     *
10031     * @return a positive integer used to identify the view or {@link #NO_ID}
10032     *         if the view has no ID
10033     *
10034     * @see #setId
10035     * @see #findViewById
10036     * @attr ref android.R.styleable#View_id
10037     */
10038    @ViewDebug.CapturedViewProperty
10039    public int getId() {
10040        return mID;
10041    }
10042
10043    /**
10044     * Returns this view's tag.
10045     *
10046     * @return the Object stored in this view as a tag
10047     *
10048     * @see #setTag(Object)
10049     * @see #getTag(int)
10050     */
10051    @ViewDebug.ExportedProperty
10052    public Object getTag() {
10053        return mTag;
10054    }
10055
10056    /**
10057     * Sets the tag associated with this view. A tag can be used to mark
10058     * a view in its hierarchy and does not have to be unique within the
10059     * hierarchy. Tags can also be used to store data within a view without
10060     * resorting to another data structure.
10061     *
10062     * @param tag an Object to tag the view with
10063     *
10064     * @see #getTag()
10065     * @see #setTag(int, Object)
10066     */
10067    public void setTag(final Object tag) {
10068        mTag = tag;
10069    }
10070
10071    /**
10072     * Returns the tag associated with this view and the specified key.
10073     *
10074     * @param key The key identifying the tag
10075     *
10076     * @return the Object stored in this view as a tag
10077     *
10078     * @see #setTag(int, Object)
10079     * @see #getTag()
10080     */
10081    public Object getTag(int key) {
10082        SparseArray<Object> tags = null;
10083        synchronized (sTagsLock) {
10084            if (sTags != null) {
10085                tags = sTags.get(this);
10086            }
10087        }
10088
10089        if (tags != null) return tags.get(key);
10090        return null;
10091    }
10092
10093    /**
10094     * Sets a tag associated with this view and a key. A tag can be used
10095     * to mark a view in its hierarchy and does not have to be unique within
10096     * the hierarchy. Tags can also be used to store data within a view
10097     * without resorting to another data structure.
10098     *
10099     * The specified key should be an id declared in the resources of the
10100     * application to ensure it is unique (see the <a
10101     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
10102     * Keys identified as belonging to
10103     * the Android framework or not associated with any package will cause
10104     * an {@link IllegalArgumentException} to be thrown.
10105     *
10106     * @param key The key identifying the tag
10107     * @param tag An Object to tag the view with
10108     *
10109     * @throws IllegalArgumentException If they specified key is not valid
10110     *
10111     * @see #setTag(Object)
10112     * @see #getTag(int)
10113     */
10114    public void setTag(int key, final Object tag) {
10115        // If the package id is 0x00 or 0x01, it's either an undefined package
10116        // or a framework id
10117        if ((key >>> 24) < 2) {
10118            throw new IllegalArgumentException("The key must be an application-specific "
10119                    + "resource id.");
10120        }
10121
10122        setTagInternal(this, key, tag);
10123    }
10124
10125    /**
10126     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
10127     * framework id.
10128     *
10129     * @hide
10130     */
10131    public void setTagInternal(int key, Object tag) {
10132        if ((key >>> 24) != 0x1) {
10133            throw new IllegalArgumentException("The key must be a framework-specific "
10134                    + "resource id.");
10135        }
10136
10137        setTagInternal(this, key, tag);
10138    }
10139
10140    private static void setTagInternal(View view, int key, Object tag) {
10141        SparseArray<Object> tags = null;
10142        synchronized (sTagsLock) {
10143            if (sTags == null) {
10144                sTags = new WeakHashMap<View, SparseArray<Object>>();
10145            } else {
10146                tags = sTags.get(view);
10147            }
10148        }
10149
10150        if (tags == null) {
10151            tags = new SparseArray<Object>(2);
10152            synchronized (sTagsLock) {
10153                sTags.put(view, tags);
10154            }
10155        }
10156
10157        tags.put(key, tag);
10158    }
10159
10160    /**
10161     * @param consistency The type of consistency. See ViewDebug for more information.
10162     *
10163     * @hide
10164     */
10165    protected boolean dispatchConsistencyCheck(int consistency) {
10166        return onConsistencyCheck(consistency);
10167    }
10168
10169    /**
10170     * Method that subclasses should implement to check their consistency. The type of
10171     * consistency check is indicated by the bit field passed as a parameter.
10172     *
10173     * @param consistency The type of consistency. See ViewDebug for more information.
10174     *
10175     * @throws IllegalStateException if the view is in an inconsistent state.
10176     *
10177     * @hide
10178     */
10179    protected boolean onConsistencyCheck(int consistency) {
10180        boolean result = true;
10181
10182        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
10183        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
10184
10185        if (checkLayout) {
10186            if (getParent() == null) {
10187                result = false;
10188                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10189                        "View " + this + " does not have a parent.");
10190            }
10191
10192            if (mAttachInfo == null) {
10193                result = false;
10194                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10195                        "View " + this + " is not attached to a window.");
10196            }
10197        }
10198
10199        if (checkDrawing) {
10200            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
10201            // from their draw() method
10202
10203            if ((mPrivateFlags & DRAWN) != DRAWN &&
10204                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
10205                result = false;
10206                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
10207                        "View " + this + " was invalidated but its drawing cache is valid.");
10208            }
10209        }
10210
10211        return result;
10212    }
10213
10214    /**
10215     * Prints information about this view in the log output, with the tag
10216     * {@link #VIEW_LOG_TAG}.
10217     *
10218     * @hide
10219     */
10220    public void debug() {
10221        debug(0);
10222    }
10223
10224    /**
10225     * Prints information about this view in the log output, with the tag
10226     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
10227     * indentation defined by the <code>depth</code>.
10228     *
10229     * @param depth the indentation level
10230     *
10231     * @hide
10232     */
10233    protected void debug(int depth) {
10234        String output = debugIndent(depth - 1);
10235
10236        output += "+ " + this;
10237        int id = getId();
10238        if (id != -1) {
10239            output += " (id=" + id + ")";
10240        }
10241        Object tag = getTag();
10242        if (tag != null) {
10243            output += " (tag=" + tag + ")";
10244        }
10245        Log.d(VIEW_LOG_TAG, output);
10246
10247        if ((mPrivateFlags & FOCUSED) != 0) {
10248            output = debugIndent(depth) + " FOCUSED";
10249            Log.d(VIEW_LOG_TAG, output);
10250        }
10251
10252        output = debugIndent(depth);
10253        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
10254                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
10255                + "} ";
10256        Log.d(VIEW_LOG_TAG, output);
10257
10258        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
10259                || mPaddingBottom != 0) {
10260            output = debugIndent(depth);
10261            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
10262                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
10263            Log.d(VIEW_LOG_TAG, output);
10264        }
10265
10266        output = debugIndent(depth);
10267        output += "mMeasureWidth=" + mMeasuredWidth +
10268                " mMeasureHeight=" + mMeasuredHeight;
10269        Log.d(VIEW_LOG_TAG, output);
10270
10271        output = debugIndent(depth);
10272        if (mLayoutParams == null) {
10273            output += "BAD! no layout params";
10274        } else {
10275            output = mLayoutParams.debug(output);
10276        }
10277        Log.d(VIEW_LOG_TAG, output);
10278
10279        output = debugIndent(depth);
10280        output += "flags={";
10281        output += View.printFlags(mViewFlags);
10282        output += "}";
10283        Log.d(VIEW_LOG_TAG, output);
10284
10285        output = debugIndent(depth);
10286        output += "privateFlags={";
10287        output += View.printPrivateFlags(mPrivateFlags);
10288        output += "}";
10289        Log.d(VIEW_LOG_TAG, output);
10290    }
10291
10292    /**
10293     * Creates an string of whitespaces used for indentation.
10294     *
10295     * @param depth the indentation level
10296     * @return a String containing (depth * 2 + 3) * 2 white spaces
10297     *
10298     * @hide
10299     */
10300    protected static String debugIndent(int depth) {
10301        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
10302        for (int i = 0; i < (depth * 2) + 3; i++) {
10303            spaces.append(' ').append(' ');
10304        }
10305        return spaces.toString();
10306    }
10307
10308    /**
10309     * <p>Return the offset of the widget's text baseline from the widget's top
10310     * boundary. If this widget does not support baseline alignment, this
10311     * method returns -1. </p>
10312     *
10313     * @return the offset of the baseline within the widget's bounds or -1
10314     *         if baseline alignment is not supported
10315     */
10316    @ViewDebug.ExportedProperty(category = "layout")
10317    public int getBaseline() {
10318        return -1;
10319    }
10320
10321    /**
10322     * Call this when something has changed which has invalidated the
10323     * layout of this view. This will schedule a layout pass of the view
10324     * tree.
10325     */
10326    public void requestLayout() {
10327        if (ViewDebug.TRACE_HIERARCHY) {
10328            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
10329        }
10330
10331        mPrivateFlags |= FORCE_LAYOUT;
10332
10333        if (mParent != null && !mParent.isLayoutRequested()) {
10334            mParent.requestLayout();
10335        }
10336    }
10337
10338    /**
10339     * Forces this view to be laid out during the next layout pass.
10340     * This method does not call requestLayout() or forceLayout()
10341     * on the parent.
10342     */
10343    public void forceLayout() {
10344        mPrivateFlags |= FORCE_LAYOUT;
10345    }
10346
10347    /**
10348     * <p>
10349     * This is called to find out how big a view should be. The parent
10350     * supplies constraint information in the width and height parameters.
10351     * </p>
10352     *
10353     * <p>
10354     * The actual mesurement work of a view is performed in
10355     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
10356     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
10357     * </p>
10358     *
10359     *
10360     * @param widthMeasureSpec Horizontal space requirements as imposed by the
10361     *        parent
10362     * @param heightMeasureSpec Vertical space requirements as imposed by the
10363     *        parent
10364     *
10365     * @see #onMeasure(int, int)
10366     */
10367    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
10368        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
10369                widthMeasureSpec != mOldWidthMeasureSpec ||
10370                heightMeasureSpec != mOldHeightMeasureSpec) {
10371
10372            // first clears the measured dimension flag
10373            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
10374
10375            if (ViewDebug.TRACE_HIERARCHY) {
10376                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
10377            }
10378
10379            // measure ourselves, this should set the measured dimension flag back
10380            onMeasure(widthMeasureSpec, heightMeasureSpec);
10381
10382            // flag not set, setMeasuredDimension() was not invoked, we raise
10383            // an exception to warn the developer
10384            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
10385                throw new IllegalStateException("onMeasure() did not set the"
10386                        + " measured dimension by calling"
10387                        + " setMeasuredDimension()");
10388            }
10389
10390            mPrivateFlags |= LAYOUT_REQUIRED;
10391        }
10392
10393        mOldWidthMeasureSpec = widthMeasureSpec;
10394        mOldHeightMeasureSpec = heightMeasureSpec;
10395    }
10396
10397    /**
10398     * <p>
10399     * Measure the view and its content to determine the measured width and the
10400     * measured height. This method is invoked by {@link #measure(int, int)} and
10401     * should be overriden by subclasses to provide accurate and efficient
10402     * measurement of their contents.
10403     * </p>
10404     *
10405     * <p>
10406     * <strong>CONTRACT:</strong> When overriding this method, you
10407     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
10408     * measured width and height of this view. Failure to do so will trigger an
10409     * <code>IllegalStateException</code>, thrown by
10410     * {@link #measure(int, int)}. Calling the superclass'
10411     * {@link #onMeasure(int, int)} is a valid use.
10412     * </p>
10413     *
10414     * <p>
10415     * The base class implementation of measure defaults to the background size,
10416     * unless a larger size is allowed by the MeasureSpec. Subclasses should
10417     * override {@link #onMeasure(int, int)} to provide better measurements of
10418     * their content.
10419     * </p>
10420     *
10421     * <p>
10422     * If this method is overridden, it is the subclass's responsibility to make
10423     * sure the measured height and width are at least the view's minimum height
10424     * and width ({@link #getSuggestedMinimumHeight()} and
10425     * {@link #getSuggestedMinimumWidth()}).
10426     * </p>
10427     *
10428     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
10429     *                         The requirements are encoded with
10430     *                         {@link android.view.View.MeasureSpec}.
10431     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
10432     *                         The requirements are encoded with
10433     *                         {@link android.view.View.MeasureSpec}.
10434     *
10435     * @see #getMeasuredWidth()
10436     * @see #getMeasuredHeight()
10437     * @see #setMeasuredDimension(int, int)
10438     * @see #getSuggestedMinimumHeight()
10439     * @see #getSuggestedMinimumWidth()
10440     * @see android.view.View.MeasureSpec#getMode(int)
10441     * @see android.view.View.MeasureSpec#getSize(int)
10442     */
10443    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
10444        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
10445                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
10446    }
10447
10448    /**
10449     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
10450     * measured width and measured height. Failing to do so will trigger an
10451     * exception at measurement time.</p>
10452     *
10453     * @param measuredWidth The measured width of this view.  May be a complex
10454     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10455     * {@link #MEASURED_STATE_TOO_SMALL}.
10456     * @param measuredHeight The measured height of this view.  May be a complex
10457     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
10458     * {@link #MEASURED_STATE_TOO_SMALL}.
10459     */
10460    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
10461        mMeasuredWidth = measuredWidth;
10462        mMeasuredHeight = measuredHeight;
10463
10464        mPrivateFlags |= MEASURED_DIMENSION_SET;
10465    }
10466
10467    /**
10468     * Merge two states as returned by {@link #getMeasuredState()}.
10469     * @param curState The current state as returned from a view or the result
10470     * of combining multiple views.
10471     * @param newState The new view state to combine.
10472     * @return Returns a new integer reflecting the combination of the two
10473     * states.
10474     */
10475    public static int combineMeasuredStates(int curState, int newState) {
10476        return curState | newState;
10477    }
10478
10479    /**
10480     * Version of {@link #resolveSizeAndState(int, int, int)}
10481     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
10482     */
10483    public static int resolveSize(int size, int measureSpec) {
10484        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
10485    }
10486
10487    /**
10488     * Utility to reconcile a desired size and state, with constraints imposed
10489     * by a MeasureSpec.  Will take the desired size, unless a different size
10490     * is imposed by the constraints.  The returned value is a compound integer,
10491     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
10492     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
10493     * size is smaller than the size the view wants to be.
10494     *
10495     * @param size How big the view wants to be
10496     * @param measureSpec Constraints imposed by the parent
10497     * @return Size information bit mask as defined by
10498     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
10499     */
10500    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
10501        int result = size;
10502        int specMode = MeasureSpec.getMode(measureSpec);
10503        int specSize =  MeasureSpec.getSize(measureSpec);
10504        switch (specMode) {
10505        case MeasureSpec.UNSPECIFIED:
10506            result = size;
10507            break;
10508        case MeasureSpec.AT_MOST:
10509            if (specSize < size) {
10510                result = specSize | MEASURED_STATE_TOO_SMALL;
10511            } else {
10512                result = size;
10513            }
10514            break;
10515        case MeasureSpec.EXACTLY:
10516            result = specSize;
10517            break;
10518        }
10519        return result | (childMeasuredState&MEASURED_STATE_MASK);
10520    }
10521
10522    /**
10523     * Utility to return a default size. Uses the supplied size if the
10524     * MeasureSpec imposed no contraints. Will get larger if allowed
10525     * by the MeasureSpec.
10526     *
10527     * @param size Default size for this view
10528     * @param measureSpec Constraints imposed by the parent
10529     * @return The size this view should be.
10530     */
10531    public static int getDefaultSize(int size, int measureSpec) {
10532        int result = size;
10533        int specMode = MeasureSpec.getMode(measureSpec);
10534        int specSize =  MeasureSpec.getSize(measureSpec);
10535
10536        switch (specMode) {
10537        case MeasureSpec.UNSPECIFIED:
10538            result = size;
10539            break;
10540        case MeasureSpec.AT_MOST:
10541        case MeasureSpec.EXACTLY:
10542            result = specSize;
10543            break;
10544        }
10545        return result;
10546    }
10547
10548    /**
10549     * Returns the suggested minimum height that the view should use. This
10550     * returns the maximum of the view's minimum height
10551     * and the background's minimum height
10552     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
10553     * <p>
10554     * When being used in {@link #onMeasure(int, int)}, the caller should still
10555     * ensure the returned height is within the requirements of the parent.
10556     *
10557     * @return The suggested minimum height of the view.
10558     */
10559    protected int getSuggestedMinimumHeight() {
10560        int suggestedMinHeight = mMinHeight;
10561
10562        if (mBGDrawable != null) {
10563            final int bgMinHeight = mBGDrawable.getMinimumHeight();
10564            if (suggestedMinHeight < bgMinHeight) {
10565                suggestedMinHeight = bgMinHeight;
10566            }
10567        }
10568
10569        return suggestedMinHeight;
10570    }
10571
10572    /**
10573     * Returns the suggested minimum width that the view should use. This
10574     * returns the maximum of the view's minimum width)
10575     * and the background's minimum width
10576     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
10577     * <p>
10578     * When being used in {@link #onMeasure(int, int)}, the caller should still
10579     * ensure the returned width is within the requirements of the parent.
10580     *
10581     * @return The suggested minimum width of the view.
10582     */
10583    protected int getSuggestedMinimumWidth() {
10584        int suggestedMinWidth = mMinWidth;
10585
10586        if (mBGDrawable != null) {
10587            final int bgMinWidth = mBGDrawable.getMinimumWidth();
10588            if (suggestedMinWidth < bgMinWidth) {
10589                suggestedMinWidth = bgMinWidth;
10590            }
10591        }
10592
10593        return suggestedMinWidth;
10594    }
10595
10596    /**
10597     * Sets the minimum height of the view. It is not guaranteed the view will
10598     * be able to achieve this minimum height (for example, if its parent layout
10599     * constrains it with less available height).
10600     *
10601     * @param minHeight The minimum height the view will try to be.
10602     */
10603    public void setMinimumHeight(int minHeight) {
10604        mMinHeight = minHeight;
10605    }
10606
10607    /**
10608     * Sets the minimum width of the view. It is not guaranteed the view will
10609     * be able to achieve this minimum width (for example, if its parent layout
10610     * constrains it with less available width).
10611     *
10612     * @param minWidth The minimum width the view will try to be.
10613     */
10614    public void setMinimumWidth(int minWidth) {
10615        mMinWidth = minWidth;
10616    }
10617
10618    /**
10619     * Get the animation currently associated with this view.
10620     *
10621     * @return The animation that is currently playing or
10622     *         scheduled to play for this view.
10623     */
10624    public Animation getAnimation() {
10625        return mCurrentAnimation;
10626    }
10627
10628    /**
10629     * Start the specified animation now.
10630     *
10631     * @param animation the animation to start now
10632     */
10633    public void startAnimation(Animation animation) {
10634        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
10635        setAnimation(animation);
10636        invalidate();
10637        invalidateParentIfAccelerated();
10638    }
10639
10640    /**
10641     * Cancels any animations for this view.
10642     */
10643    public void clearAnimation() {
10644        if (mCurrentAnimation != null) {
10645            mCurrentAnimation.detach();
10646        }
10647        mCurrentAnimation = null;
10648        invalidateParentIfAccelerated();
10649    }
10650
10651    /**
10652     * Sets the next animation to play for this view.
10653     * If you want the animation to play immediately, use
10654     * startAnimation. This method provides allows fine-grained
10655     * control over the start time and invalidation, but you
10656     * must make sure that 1) the animation has a start time set, and
10657     * 2) the view will be invalidated when the animation is supposed to
10658     * start.
10659     *
10660     * @param animation The next animation, or null.
10661     */
10662    public void setAnimation(Animation animation) {
10663        mCurrentAnimation = animation;
10664        if (animation != null) {
10665            animation.reset();
10666        }
10667    }
10668
10669    /**
10670     * Invoked by a parent ViewGroup to notify the start of the animation
10671     * currently associated with this view. If you override this method,
10672     * always call super.onAnimationStart();
10673     *
10674     * @see #setAnimation(android.view.animation.Animation)
10675     * @see #getAnimation()
10676     */
10677    protected void onAnimationStart() {
10678        mPrivateFlags |= ANIMATION_STARTED;
10679    }
10680
10681    /**
10682     * Invoked by a parent ViewGroup to notify the end of the animation
10683     * currently associated with this view. If you override this method,
10684     * always call super.onAnimationEnd();
10685     *
10686     * @see #setAnimation(android.view.animation.Animation)
10687     * @see #getAnimation()
10688     */
10689    protected void onAnimationEnd() {
10690        mPrivateFlags &= ~ANIMATION_STARTED;
10691    }
10692
10693    /**
10694     * Invoked if there is a Transform that involves alpha. Subclass that can
10695     * draw themselves with the specified alpha should return true, and then
10696     * respect that alpha when their onDraw() is called. If this returns false
10697     * then the view may be redirected to draw into an offscreen buffer to
10698     * fulfill the request, which will look fine, but may be slower than if the
10699     * subclass handles it internally. The default implementation returns false.
10700     *
10701     * @param alpha The alpha (0..255) to apply to the view's drawing
10702     * @return true if the view can draw with the specified alpha.
10703     */
10704    protected boolean onSetAlpha(int alpha) {
10705        return false;
10706    }
10707
10708    /**
10709     * This is used by the RootView to perform an optimization when
10710     * the view hierarchy contains one or several SurfaceView.
10711     * SurfaceView is always considered transparent, but its children are not,
10712     * therefore all View objects remove themselves from the global transparent
10713     * region (passed as a parameter to this function).
10714     *
10715     * @param region The transparent region for this ViewRoot (window).
10716     *
10717     * @return Returns true if the effective visibility of the view at this
10718     * point is opaque, regardless of the transparent region; returns false
10719     * if it is possible for underlying windows to be seen behind the view.
10720     *
10721     * {@hide}
10722     */
10723    public boolean gatherTransparentRegion(Region region) {
10724        final AttachInfo attachInfo = mAttachInfo;
10725        if (region != null && attachInfo != null) {
10726            final int pflags = mPrivateFlags;
10727            if ((pflags & SKIP_DRAW) == 0) {
10728                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
10729                // remove it from the transparent region.
10730                final int[] location = attachInfo.mTransparentLocation;
10731                getLocationInWindow(location);
10732                region.op(location[0], location[1], location[0] + mRight - mLeft,
10733                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
10734            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
10735                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
10736                // exists, so we remove the background drawable's non-transparent
10737                // parts from this transparent region.
10738                applyDrawableToTransparentRegion(mBGDrawable, region);
10739            }
10740        }
10741        return true;
10742    }
10743
10744    /**
10745     * Play a sound effect for this view.
10746     *
10747     * <p>The framework will play sound effects for some built in actions, such as
10748     * clicking, but you may wish to play these effects in your widget,
10749     * for instance, for internal navigation.
10750     *
10751     * <p>The sound effect will only be played if sound effects are enabled by the user, and
10752     * {@link #isSoundEffectsEnabled()} is true.
10753     *
10754     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
10755     */
10756    public void playSoundEffect(int soundConstant) {
10757        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
10758            return;
10759        }
10760        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
10761    }
10762
10763    /**
10764     * BZZZTT!!1!
10765     *
10766     * <p>Provide haptic feedback to the user for this view.
10767     *
10768     * <p>The framework will provide haptic feedback for some built in actions,
10769     * such as long presses, but you may wish to provide feedback for your
10770     * own widget.
10771     *
10772     * <p>The feedback will only be performed if
10773     * {@link #isHapticFeedbackEnabled()} is true.
10774     *
10775     * @param feedbackConstant One of the constants defined in
10776     * {@link HapticFeedbackConstants}
10777     */
10778    public boolean performHapticFeedback(int feedbackConstant) {
10779        return performHapticFeedback(feedbackConstant, 0);
10780    }
10781
10782    /**
10783     * BZZZTT!!1!
10784     *
10785     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
10786     *
10787     * @param feedbackConstant One of the constants defined in
10788     * {@link HapticFeedbackConstants}
10789     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
10790     */
10791    public boolean performHapticFeedback(int feedbackConstant, int flags) {
10792        if (mAttachInfo == null) {
10793            return false;
10794        }
10795        //noinspection SimplifiableIfStatement
10796        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
10797                && !isHapticFeedbackEnabled()) {
10798            return false;
10799        }
10800        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
10801                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
10802    }
10803
10804    /**
10805     * Request that the visibility of the status bar be changed.
10806     */
10807    public void setSystemUiVisibility(int visibility) {
10808        if (visibility != mSystemUiVisibility) {
10809            mSystemUiVisibility = visibility;
10810            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10811                mParent.recomputeViewAttributes(this);
10812            }
10813        }
10814    }
10815
10816    /**
10817     * Returns the status bar visibility that this view has requested.
10818     */
10819    public int getSystemUiVisibility() {
10820        return mSystemUiVisibility;
10821    }
10822
10823    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
10824        mOnSystemUiVisibilityChangeListener = l;
10825        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
10826            mParent.recomputeViewAttributes(this);
10827        }
10828    }
10829
10830    /**
10831     */
10832    public void dispatchSystemUiVisibilityChanged(int visibility) {
10833        if (mOnSystemUiVisibilityChangeListener != null) {
10834            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(visibility);
10835        }
10836    }
10837
10838    /**
10839     * !!! TODO: real docs
10840     *
10841     * The base class implementation makes the shadow the same size and appearance
10842     * as the view itself, and positions it with its center at the touch point.
10843     */
10844    public static class DragShadowBuilder {
10845        private final WeakReference<View> mView;
10846
10847        /**
10848         * Construct a shadow builder object for use with the given View object.  The
10849         * default implementation will construct a drag shadow the same size and
10850         * appearance as the supplied View.
10851         *
10852         * @param view A view within the application's layout whose appearance
10853         *        should be replicated as the drag shadow.
10854         */
10855        public DragShadowBuilder(View view) {
10856            mView = new WeakReference<View>(view);
10857        }
10858
10859        /**
10860         * Construct a shadow builder object with no associated View.  This
10861         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
10862         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
10863         * to supply the drag shadow's dimensions and appearance without
10864         * reference to any View object.
10865         */
10866        public DragShadowBuilder() {
10867            mView = new WeakReference<View>(null);
10868        }
10869
10870        /**
10871         * Returns the View object that had been passed to the
10872         * {@link #View.DragShadowBuilder(View)}
10873         * constructor.  If that View parameter was {@code null} or if the
10874         * {@link #View.DragShadowBuilder()}
10875         * constructor was used to instantiate the builder object, this method will return
10876         * null.
10877         *
10878         * @return The View object associate with this builder object.
10879         */
10880        final public View getView() {
10881            return mView.get();
10882        }
10883
10884        /**
10885         * Provide the draggable-shadow metrics for the operation: the dimensions of
10886         * the shadow image itself, and the point within that shadow that should
10887         * be centered under the touch location while dragging.
10888         * <p>
10889         * The default implementation sets the dimensions of the shadow to be the
10890         * same as the dimensions of the View object that had been supplied to the
10891         * {@link #View.DragShadowBuilder(View)} constructor
10892         * when the builder object was instantiated, and centers the shadow under the touch
10893         * point.
10894         *
10895         * @param shadowSize The application should set the {@code x} member of this
10896         *        parameter to the desired shadow width, and the {@code y} member to
10897         *        the desired height.
10898         * @param shadowTouchPoint The application should set this point to be the
10899         *        location within the shadow that should track directly underneath
10900         *        the touch point on the screen during a drag.
10901         */
10902        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
10903            final View view = mView.get();
10904            if (view != null) {
10905                shadowSize.set(view.getWidth(), view.getHeight());
10906                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
10907            } else {
10908                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
10909            }
10910        }
10911
10912        /**
10913         * Draw the shadow image for the upcoming drag.  The shadow canvas was
10914         * created with the dimensions supplied by the
10915         * {@link #onProvideShadowMetrics(Point, Point)} callback.
10916         * <p>
10917         * The default implementation replicates the appearance of the View object
10918         * that had been supplied to the
10919         * {@link #View.DragShadowBuilder(View)}
10920         * constructor when the builder object was instantiated.
10921         *
10922         * @param canvas
10923         */
10924        public void onDrawShadow(Canvas canvas) {
10925            final View view = mView.get();
10926            if (view != null) {
10927                view.draw(canvas);
10928            } else {
10929                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
10930            }
10931        }
10932    }
10933
10934    /**
10935     * Drag and drop.  App calls startDrag(), then callbacks to the shadow builder's
10936     * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
10937     * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
10938     * operation is handed over to the OS.
10939     * !!! TODO: real docs
10940     *
10941     * @param data !!! TODO
10942     * @param shadowBuilder !!! TODO
10943     * @param myLocalState An arbitrary object that will be passed as part of every DragEvent
10944     *     delivered to the calling application during the course of the current drag operation.
10945     *     This object is private to the application that called startDrag(), and is not
10946     *     visible to other applications. It provides a lightweight way for the application to
10947     *     propagate information from the initiator to the recipient of a drag within its own
10948     *     application; for example, to help disambiguate between 'copy' and 'move' semantics.
10949     * @param flags Flags affecting the drag operation.  At present no flags are defined;
10950     *     pass 0 for this parameter.
10951     * @return {@code true} if the drag operation was initiated successfully; {@code false} if
10952     *     an error prevented the drag from taking place.
10953     */
10954    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
10955            Object myLocalState, int flags) {
10956        if (ViewDebug.DEBUG_DRAG) {
10957            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
10958        }
10959        boolean okay = false;
10960
10961        Point shadowSize = new Point();
10962        Point shadowTouchPoint = new Point();
10963        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
10964
10965        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
10966                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
10967            throw new IllegalStateException("Drag shadow dimensions must not be negative");
10968        }
10969
10970        if (ViewDebug.DEBUG_DRAG) {
10971            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
10972                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
10973        }
10974        Surface surface = new Surface();
10975        try {
10976            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
10977                    flags, shadowSize.x, shadowSize.y, surface);
10978            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
10979                    + " surface=" + surface);
10980            if (token != null) {
10981                Canvas canvas = surface.lockCanvas(null);
10982                try {
10983                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
10984                    shadowBuilder.onDrawShadow(canvas);
10985                } finally {
10986                    surface.unlockCanvasAndPost(canvas);
10987                }
10988
10989                final ViewRoot root = getViewRoot();
10990
10991                // Cache the local state object for delivery with DragEvents
10992                root.setLocalDragState(myLocalState);
10993
10994                // repurpose 'shadowSize' for the last touch point
10995                root.getLastTouchPoint(shadowSize);
10996
10997                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
10998                        shadowSize.x, shadowSize.y,
10999                        shadowTouchPoint.x, shadowTouchPoint.y, data);
11000                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
11001            }
11002        } catch (Exception e) {
11003            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
11004            surface.destroy();
11005        }
11006
11007        return okay;
11008    }
11009
11010    /**
11011     * Drag-and-drop event dispatch.  The event.getAction() verb is one of the DragEvent
11012     * constants DRAG_STARTED_EVENT, DRAG_EVENT, DROP_EVENT, and DRAG_ENDED_EVENT.
11013     *
11014     * For DRAG_STARTED_EVENT, event.getClipDescription() describes the content
11015     * being dragged.  onDragEvent() should return 'true' if the view can handle
11016     * a drop of that content.  A view that returns 'false' here will receive no
11017     * further calls to onDragEvent() about the drag/drop operation.
11018     *
11019     * For DRAG_ENTERED, event.getClipDescription() describes the content being
11020     * dragged.  This will be the same content description passed in the
11021     * DRAG_STARTED_EVENT invocation.
11022     *
11023     * For DRAG_EXITED, event.getClipDescription() describes the content being
11024     * dragged.  This will be the same content description passed in the
11025     * DRAG_STARTED_EVENT invocation.  The view should return to its approriate
11026     * drag-acceptance visual state.
11027     *
11028     * For DRAG_LOCATION_EVENT, event.getX() and event.getY() give the location in View
11029     * coordinates of the current drag point.  The view must return 'true' if it
11030     * can accept a drop of the current drag content, false otherwise.
11031     *
11032     * For DROP_EVENT, event.getX() and event.getY() give the location of the drop
11033     * within the view; also, event.getClipData() returns the full data payload
11034     * being dropped.  The view should return 'true' if it consumed the dropped
11035     * content, 'false' if it did not.
11036     *
11037     * For DRAG_ENDED_EVENT, the 'event' argument may be null.  The view should return
11038     * to its normal visual state.
11039     */
11040    public boolean onDragEvent(DragEvent event) {
11041        return false;
11042    }
11043
11044    /**
11045     * Views typically don't need to override dispatchDragEvent(); it just calls
11046     * onDragEvent(event) and passes the result up appropriately.
11047     */
11048    public boolean dispatchDragEvent(DragEvent event) {
11049        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
11050                && mOnDragListener.onDrag(this, event)) {
11051            return true;
11052        }
11053        return onDragEvent(event);
11054    }
11055
11056    /**
11057     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
11058     * it is ever exposed at all.
11059     * @hide
11060     */
11061    public void onCloseSystemDialogs(String reason) {
11062    }
11063
11064    /**
11065     * Given a Drawable whose bounds have been set to draw into this view,
11066     * update a Region being computed for {@link #gatherTransparentRegion} so
11067     * that any non-transparent parts of the Drawable are removed from the
11068     * given transparent region.
11069     *
11070     * @param dr The Drawable whose transparency is to be applied to the region.
11071     * @param region A Region holding the current transparency information,
11072     * where any parts of the region that are set are considered to be
11073     * transparent.  On return, this region will be modified to have the
11074     * transparency information reduced by the corresponding parts of the
11075     * Drawable that are not transparent.
11076     * {@hide}
11077     */
11078    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
11079        if (DBG) {
11080            Log.i("View", "Getting transparent region for: " + this);
11081        }
11082        final Region r = dr.getTransparentRegion();
11083        final Rect db = dr.getBounds();
11084        final AttachInfo attachInfo = mAttachInfo;
11085        if (r != null && attachInfo != null) {
11086            final int w = getRight()-getLeft();
11087            final int h = getBottom()-getTop();
11088            if (db.left > 0) {
11089                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
11090                r.op(0, 0, db.left, h, Region.Op.UNION);
11091            }
11092            if (db.right < w) {
11093                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
11094                r.op(db.right, 0, w, h, Region.Op.UNION);
11095            }
11096            if (db.top > 0) {
11097                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
11098                r.op(0, 0, w, db.top, Region.Op.UNION);
11099            }
11100            if (db.bottom < h) {
11101                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
11102                r.op(0, db.bottom, w, h, Region.Op.UNION);
11103            }
11104            final int[] location = attachInfo.mTransparentLocation;
11105            getLocationInWindow(location);
11106            r.translate(location[0], location[1]);
11107            region.op(r, Region.Op.INTERSECT);
11108        } else {
11109            region.op(db, Region.Op.DIFFERENCE);
11110        }
11111    }
11112
11113    private void postCheckForLongClick(int delayOffset) {
11114        mHasPerformedLongPress = false;
11115
11116        if (mPendingCheckForLongPress == null) {
11117            mPendingCheckForLongPress = new CheckForLongPress();
11118        }
11119        mPendingCheckForLongPress.rememberWindowAttachCount();
11120        postDelayed(mPendingCheckForLongPress,
11121                ViewConfiguration.getLongPressTimeout() - delayOffset);
11122    }
11123
11124    /**
11125     * Inflate a view from an XML resource.  This convenience method wraps the {@link
11126     * LayoutInflater} class, which provides a full range of options for view inflation.
11127     *
11128     * @param context The Context object for your activity or application.
11129     * @param resource The resource ID to inflate
11130     * @param root A view group that will be the parent.  Used to properly inflate the
11131     * layout_* parameters.
11132     * @see LayoutInflater
11133     */
11134    public static View inflate(Context context, int resource, ViewGroup root) {
11135        LayoutInflater factory = LayoutInflater.from(context);
11136        return factory.inflate(resource, root);
11137    }
11138
11139    /**
11140     * Scroll the view with standard behavior for scrolling beyond the normal
11141     * content boundaries. Views that call this method should override
11142     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
11143     * results of an over-scroll operation.
11144     *
11145     * Views can use this method to handle any touch or fling-based scrolling.
11146     *
11147     * @param deltaX Change in X in pixels
11148     * @param deltaY Change in Y in pixels
11149     * @param scrollX Current X scroll value in pixels before applying deltaX
11150     * @param scrollY Current Y scroll value in pixels before applying deltaY
11151     * @param scrollRangeX Maximum content scroll range along the X axis
11152     * @param scrollRangeY Maximum content scroll range along the Y axis
11153     * @param maxOverScrollX Number of pixels to overscroll by in either direction
11154     *          along the X axis.
11155     * @param maxOverScrollY Number of pixels to overscroll by in either direction
11156     *          along the Y axis.
11157     * @param isTouchEvent true if this scroll operation is the result of a touch event.
11158     * @return true if scrolling was clamped to an over-scroll boundary along either
11159     *          axis, false otherwise.
11160     */
11161    protected boolean overScrollBy(int deltaX, int deltaY,
11162            int scrollX, int scrollY,
11163            int scrollRangeX, int scrollRangeY,
11164            int maxOverScrollX, int maxOverScrollY,
11165            boolean isTouchEvent) {
11166        final int overScrollMode = mOverScrollMode;
11167        final boolean canScrollHorizontal =
11168                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
11169        final boolean canScrollVertical =
11170                computeVerticalScrollRange() > computeVerticalScrollExtent();
11171        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
11172                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
11173        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
11174                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
11175
11176        int newScrollX = scrollX + deltaX;
11177        if (!overScrollHorizontal) {
11178            maxOverScrollX = 0;
11179        }
11180
11181        int newScrollY = scrollY + deltaY;
11182        if (!overScrollVertical) {
11183            maxOverScrollY = 0;
11184        }
11185
11186        // Clamp values if at the limits and record
11187        final int left = -maxOverScrollX;
11188        final int right = maxOverScrollX + scrollRangeX;
11189        final int top = -maxOverScrollY;
11190        final int bottom = maxOverScrollY + scrollRangeY;
11191
11192        boolean clampedX = false;
11193        if (newScrollX > right) {
11194            newScrollX = right;
11195            clampedX = true;
11196        } else if (newScrollX < left) {
11197            newScrollX = left;
11198            clampedX = true;
11199        }
11200
11201        boolean clampedY = false;
11202        if (newScrollY > bottom) {
11203            newScrollY = bottom;
11204            clampedY = true;
11205        } else if (newScrollY < top) {
11206            newScrollY = top;
11207            clampedY = true;
11208        }
11209
11210        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
11211
11212        return clampedX || clampedY;
11213    }
11214
11215    /**
11216     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
11217     * respond to the results of an over-scroll operation.
11218     *
11219     * @param scrollX New X scroll value in pixels
11220     * @param scrollY New Y scroll value in pixels
11221     * @param clampedX True if scrollX was clamped to an over-scroll boundary
11222     * @param clampedY True if scrollY was clamped to an over-scroll boundary
11223     */
11224    protected void onOverScrolled(int scrollX, int scrollY,
11225            boolean clampedX, boolean clampedY) {
11226        // Intentionally empty.
11227    }
11228
11229    /**
11230     * Returns the over-scroll mode for this view. The result will be
11231     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11232     * (allow over-scrolling only if the view content is larger than the container),
11233     * or {@link #OVER_SCROLL_NEVER}.
11234     *
11235     * @return This view's over-scroll mode.
11236     */
11237    public int getOverScrollMode() {
11238        return mOverScrollMode;
11239    }
11240
11241    /**
11242     * Set the over-scroll mode for this view. Valid over-scroll modes are
11243     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
11244     * (allow over-scrolling only if the view content is larger than the container),
11245     * or {@link #OVER_SCROLL_NEVER}.
11246     *
11247     * Setting the over-scroll mode of a view will have an effect only if the
11248     * view is capable of scrolling.
11249     *
11250     * @param overScrollMode The new over-scroll mode for this view.
11251     */
11252    public void setOverScrollMode(int overScrollMode) {
11253        if (overScrollMode != OVER_SCROLL_ALWAYS &&
11254                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
11255                overScrollMode != OVER_SCROLL_NEVER) {
11256            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
11257        }
11258        mOverScrollMode = overScrollMode;
11259    }
11260
11261    /**
11262     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
11263     * Each MeasureSpec represents a requirement for either the width or the height.
11264     * A MeasureSpec is comprised of a size and a mode. There are three possible
11265     * modes:
11266     * <dl>
11267     * <dt>UNSPECIFIED</dt>
11268     * <dd>
11269     * The parent has not imposed any constraint on the child. It can be whatever size
11270     * it wants.
11271     * </dd>
11272     *
11273     * <dt>EXACTLY</dt>
11274     * <dd>
11275     * The parent has determined an exact size for the child. The child is going to be
11276     * given those bounds regardless of how big it wants to be.
11277     * </dd>
11278     *
11279     * <dt>AT_MOST</dt>
11280     * <dd>
11281     * The child can be as large as it wants up to the specified size.
11282     * </dd>
11283     * </dl>
11284     *
11285     * MeasureSpecs are implemented as ints to reduce object allocation. This class
11286     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
11287     */
11288    public static class MeasureSpec {
11289        private static final int MODE_SHIFT = 30;
11290        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
11291
11292        /**
11293         * Measure specification mode: The parent has not imposed any constraint
11294         * on the child. It can be whatever size it wants.
11295         */
11296        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
11297
11298        /**
11299         * Measure specification mode: The parent has determined an exact size
11300         * for the child. The child is going to be given those bounds regardless
11301         * of how big it wants to be.
11302         */
11303        public static final int EXACTLY     = 1 << MODE_SHIFT;
11304
11305        /**
11306         * Measure specification mode: The child can be as large as it wants up
11307         * to the specified size.
11308         */
11309        public static final int AT_MOST     = 2 << MODE_SHIFT;
11310
11311        /**
11312         * Creates a measure specification based on the supplied size and mode.
11313         *
11314         * The mode must always be one of the following:
11315         * <ul>
11316         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
11317         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
11318         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
11319         * </ul>
11320         *
11321         * @param size the size of the measure specification
11322         * @param mode the mode of the measure specification
11323         * @return the measure specification based on size and mode
11324         */
11325        public static int makeMeasureSpec(int size, int mode) {
11326            return size + mode;
11327        }
11328
11329        /**
11330         * Extracts the mode from the supplied measure specification.
11331         *
11332         * @param measureSpec the measure specification to extract the mode from
11333         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
11334         *         {@link android.view.View.MeasureSpec#AT_MOST} or
11335         *         {@link android.view.View.MeasureSpec#EXACTLY}
11336         */
11337        public static int getMode(int measureSpec) {
11338            return (measureSpec & MODE_MASK);
11339        }
11340
11341        /**
11342         * Extracts the size from the supplied measure specification.
11343         *
11344         * @param measureSpec the measure specification to extract the size from
11345         * @return the size in pixels defined in the supplied measure specification
11346         */
11347        public static int getSize(int measureSpec) {
11348            return (measureSpec & ~MODE_MASK);
11349        }
11350
11351        /**
11352         * Returns a String representation of the specified measure
11353         * specification.
11354         *
11355         * @param measureSpec the measure specification to convert to a String
11356         * @return a String with the following format: "MeasureSpec: MODE SIZE"
11357         */
11358        public static String toString(int measureSpec) {
11359            int mode = getMode(measureSpec);
11360            int size = getSize(measureSpec);
11361
11362            StringBuilder sb = new StringBuilder("MeasureSpec: ");
11363
11364            if (mode == UNSPECIFIED)
11365                sb.append("UNSPECIFIED ");
11366            else if (mode == EXACTLY)
11367                sb.append("EXACTLY ");
11368            else if (mode == AT_MOST)
11369                sb.append("AT_MOST ");
11370            else
11371                sb.append(mode).append(" ");
11372
11373            sb.append(size);
11374            return sb.toString();
11375        }
11376    }
11377
11378    class CheckForLongPress implements Runnable {
11379
11380        private int mOriginalWindowAttachCount;
11381
11382        public void run() {
11383            if (isPressed() && (mParent != null)
11384                    && mOriginalWindowAttachCount == mWindowAttachCount) {
11385                if (performLongClick()) {
11386                    mHasPerformedLongPress = true;
11387                }
11388            }
11389        }
11390
11391        public void rememberWindowAttachCount() {
11392            mOriginalWindowAttachCount = mWindowAttachCount;
11393        }
11394    }
11395
11396    private final class CheckForTap implements Runnable {
11397        public void run() {
11398            mPrivateFlags &= ~PREPRESSED;
11399            mPrivateFlags |= PRESSED;
11400            refreshDrawableState();
11401            if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
11402                postCheckForLongClick(ViewConfiguration.getTapTimeout());
11403            }
11404        }
11405    }
11406
11407    private final class PerformClick implements Runnable {
11408        public void run() {
11409            performClick();
11410        }
11411    }
11412
11413    /**
11414     * Interface definition for a callback to be invoked when a key event is
11415     * dispatched to this view. The callback will be invoked before the key
11416     * event is given to the view.
11417     */
11418    public interface OnKeyListener {
11419        /**
11420         * Called when a key is dispatched to a view. This allows listeners to
11421         * get a chance to respond before the target view.
11422         *
11423         * @param v The view the key has been dispatched to.
11424         * @param keyCode The code for the physical key that was pressed
11425         * @param event The KeyEvent object containing full information about
11426         *        the event.
11427         * @return True if the listener has consumed the event, false otherwise.
11428         */
11429        boolean onKey(View v, int keyCode, KeyEvent event);
11430    }
11431
11432    /**
11433     * Interface definition for a callback to be invoked when a touch event is
11434     * dispatched to this view. The callback will be invoked before the touch
11435     * event is given to the view.
11436     */
11437    public interface OnTouchListener {
11438        /**
11439         * Called when a touch event is dispatched to a view. This allows listeners to
11440         * get a chance to respond before the target view.
11441         *
11442         * @param v The view the touch event has been dispatched to.
11443         * @param event The MotionEvent object containing full information about
11444         *        the event.
11445         * @return True if the listener has consumed the event, false otherwise.
11446         */
11447        boolean onTouch(View v, MotionEvent event);
11448    }
11449
11450    /**
11451     * Interface definition for a callback to be invoked when a view has been clicked and held.
11452     */
11453    public interface OnLongClickListener {
11454        /**
11455         * Called when a view has been clicked and held.
11456         *
11457         * @param v The view that was clicked and held.
11458         *
11459         * @return true if the callback consumed the long click, false otherwise.
11460         */
11461        boolean onLongClick(View v);
11462    }
11463
11464    /**
11465     * Interface definition for a callback to be invoked when a drag is being dispatched
11466     * to this view.  The callback will be invoked before the hosting view's own
11467     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
11468     * onDrag(event) behavior, it should return 'false' from this callback.
11469     */
11470    public interface OnDragListener {
11471        /**
11472         * Called when a drag event is dispatched to a view. This allows listeners
11473         * to get a chance to override base View behavior.
11474         *
11475         * @param v The view the drag has been dispatched to.
11476         * @param event The DragEvent object containing full information
11477         *        about the event.
11478         * @return true if the listener consumed the DragEvent, false in order to fall
11479         *         back to the view's default handling.
11480         */
11481        boolean onDrag(View v, DragEvent event);
11482    }
11483
11484    /**
11485     * Interface definition for a callback to be invoked when the focus state of
11486     * a view changed.
11487     */
11488    public interface OnFocusChangeListener {
11489        /**
11490         * Called when the focus state of a view has changed.
11491         *
11492         * @param v The view whose state has changed.
11493         * @param hasFocus The new focus state of v.
11494         */
11495        void onFocusChange(View v, boolean hasFocus);
11496    }
11497
11498    /**
11499     * Interface definition for a callback to be invoked when a view is clicked.
11500     */
11501    public interface OnClickListener {
11502        /**
11503         * Called when a view has been clicked.
11504         *
11505         * @param v The view that was clicked.
11506         */
11507        void onClick(View v);
11508    }
11509
11510    /**
11511     * Interface definition for a callback to be invoked when the context menu
11512     * for this view is being built.
11513     */
11514    public interface OnCreateContextMenuListener {
11515        /**
11516         * Called when the context menu for this view is being built. It is not
11517         * safe to hold onto the menu after this method returns.
11518         *
11519         * @param menu The context menu that is being built
11520         * @param v The view for which the context menu is being built
11521         * @param menuInfo Extra information about the item for which the
11522         *            context menu should be shown. This information will vary
11523         *            depending on the class of v.
11524         */
11525        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
11526    }
11527
11528    /**
11529     * Interface definition for a callback to be invoked when the status bar changes
11530     * visibility.
11531     *
11532     * @see #setOnSystemUiVisibilityChangeListener
11533     */
11534    public interface OnSystemUiVisibilityChangeListener {
11535        /**
11536         * Called when the status bar changes visibility because of a call to
11537         * {@link #setSystemUiVisibility}.
11538         *
11539         * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
11540         */
11541        public void onSystemUiVisibilityChange(int visibility);
11542    }
11543
11544    private final class UnsetPressedState implements Runnable {
11545        public void run() {
11546            setPressed(false);
11547        }
11548    }
11549
11550    /**
11551     * Base class for derived classes that want to save and restore their own
11552     * state in {@link android.view.View#onSaveInstanceState()}.
11553     */
11554    public static class BaseSavedState extends AbsSavedState {
11555        /**
11556         * Constructor used when reading from a parcel. Reads the state of the superclass.
11557         *
11558         * @param source
11559         */
11560        public BaseSavedState(Parcel source) {
11561            super(source);
11562        }
11563
11564        /**
11565         * Constructor called by derived classes when creating their SavedState objects
11566         *
11567         * @param superState The state of the superclass of this view
11568         */
11569        public BaseSavedState(Parcelable superState) {
11570            super(superState);
11571        }
11572
11573        public static final Parcelable.Creator<BaseSavedState> CREATOR =
11574                new Parcelable.Creator<BaseSavedState>() {
11575            public BaseSavedState createFromParcel(Parcel in) {
11576                return new BaseSavedState(in);
11577            }
11578
11579            public BaseSavedState[] newArray(int size) {
11580                return new BaseSavedState[size];
11581            }
11582        };
11583    }
11584
11585    /**
11586     * A set of information given to a view when it is attached to its parent
11587     * window.
11588     */
11589    static class AttachInfo {
11590        interface Callbacks {
11591            void playSoundEffect(int effectId);
11592            boolean performHapticFeedback(int effectId, boolean always);
11593        }
11594
11595        /**
11596         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
11597         * to a Handler. This class contains the target (View) to invalidate and
11598         * the coordinates of the dirty rectangle.
11599         *
11600         * For performance purposes, this class also implements a pool of up to
11601         * POOL_LIMIT objects that get reused. This reduces memory allocations
11602         * whenever possible.
11603         */
11604        static class InvalidateInfo implements Poolable<InvalidateInfo> {
11605            private static final int POOL_LIMIT = 10;
11606            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
11607                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
11608                        public InvalidateInfo newInstance() {
11609                            return new InvalidateInfo();
11610                        }
11611
11612                        public void onAcquired(InvalidateInfo element) {
11613                        }
11614
11615                        public void onReleased(InvalidateInfo element) {
11616                        }
11617                    }, POOL_LIMIT)
11618            );
11619
11620            private InvalidateInfo mNext;
11621
11622            View target;
11623
11624            int left;
11625            int top;
11626            int right;
11627            int bottom;
11628
11629            public void setNextPoolable(InvalidateInfo element) {
11630                mNext = element;
11631            }
11632
11633            public InvalidateInfo getNextPoolable() {
11634                return mNext;
11635            }
11636
11637            static InvalidateInfo acquire() {
11638                return sPool.acquire();
11639            }
11640
11641            void release() {
11642                sPool.release(this);
11643            }
11644        }
11645
11646        final IWindowSession mSession;
11647
11648        final IWindow mWindow;
11649
11650        final IBinder mWindowToken;
11651
11652        final Callbacks mRootCallbacks;
11653
11654        Canvas mHardwareCanvas;
11655
11656        /**
11657         * The top view of the hierarchy.
11658         */
11659        View mRootView;
11660
11661        IBinder mPanelParentWindowToken;
11662        Surface mSurface;
11663
11664        boolean mHardwareAccelerated;
11665        boolean mHardwareAccelerationRequested;
11666        HardwareRenderer mHardwareRenderer;
11667
11668        /**
11669         * Scale factor used by the compatibility mode
11670         */
11671        float mApplicationScale;
11672
11673        /**
11674         * Indicates whether the application is in compatibility mode
11675         */
11676        boolean mScalingRequired;
11677
11678        /**
11679         * Left position of this view's window
11680         */
11681        int mWindowLeft;
11682
11683        /**
11684         * Top position of this view's window
11685         */
11686        int mWindowTop;
11687
11688        /**
11689         * Indicates whether views need to use 32-bit drawing caches
11690         */
11691        boolean mUse32BitDrawingCache;
11692
11693        /**
11694         * For windows that are full-screen but using insets to layout inside
11695         * of the screen decorations, these are the current insets for the
11696         * content of the window.
11697         */
11698        final Rect mContentInsets = new Rect();
11699
11700        /**
11701         * For windows that are full-screen but using insets to layout inside
11702         * of the screen decorations, these are the current insets for the
11703         * actual visible parts of the window.
11704         */
11705        final Rect mVisibleInsets = new Rect();
11706
11707        /**
11708         * The internal insets given by this window.  This value is
11709         * supplied by the client (through
11710         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
11711         * be given to the window manager when changed to be used in laying
11712         * out windows behind it.
11713         */
11714        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
11715                = new ViewTreeObserver.InternalInsetsInfo();
11716
11717        /**
11718         * All views in the window's hierarchy that serve as scroll containers,
11719         * used to determine if the window can be resized or must be panned
11720         * to adjust for a soft input area.
11721         */
11722        final ArrayList<View> mScrollContainers = new ArrayList<View>();
11723
11724        final KeyEvent.DispatcherState mKeyDispatchState
11725                = new KeyEvent.DispatcherState();
11726
11727        /**
11728         * Indicates whether the view's window currently has the focus.
11729         */
11730        boolean mHasWindowFocus;
11731
11732        /**
11733         * The current visibility of the window.
11734         */
11735        int mWindowVisibility;
11736
11737        /**
11738         * Indicates the time at which drawing started to occur.
11739         */
11740        long mDrawingTime;
11741
11742        /**
11743         * Indicates whether or not ignoring the DIRTY_MASK flags.
11744         */
11745        boolean mIgnoreDirtyState;
11746
11747        /**
11748         * Indicates whether the view's window is currently in touch mode.
11749         */
11750        boolean mInTouchMode;
11751
11752        /**
11753         * Indicates that ViewRoot should trigger a global layout change
11754         * the next time it performs a traversal
11755         */
11756        boolean mRecomputeGlobalAttributes;
11757
11758        /**
11759         * Set during a traveral if any views want to keep the screen on.
11760         */
11761        boolean mKeepScreenOn;
11762
11763        /**
11764         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
11765         */
11766        int mSystemUiVisibility;
11767
11768        /**
11769         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
11770         * attached.
11771         */
11772        boolean mHasSystemUiListeners;
11773
11774        /**
11775         * Set if the visibility of any views has changed.
11776         */
11777        boolean mViewVisibilityChanged;
11778
11779        /**
11780         * Set to true if a view has been scrolled.
11781         */
11782        boolean mViewScrollChanged;
11783
11784        /**
11785         * Global to the view hierarchy used as a temporary for dealing with
11786         * x/y points in the transparent region computations.
11787         */
11788        final int[] mTransparentLocation = new int[2];
11789
11790        /**
11791         * Global to the view hierarchy used as a temporary for dealing with
11792         * x/y points in the ViewGroup.invalidateChild implementation.
11793         */
11794        final int[] mInvalidateChildLocation = new int[2];
11795
11796
11797        /**
11798         * Global to the view hierarchy used as a temporary for dealing with
11799         * x/y location when view is transformed.
11800         */
11801        final float[] mTmpTransformLocation = new float[2];
11802
11803        /**
11804         * The view tree observer used to dispatch global events like
11805         * layout, pre-draw, touch mode change, etc.
11806         */
11807        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
11808
11809        /**
11810         * A Canvas used by the view hierarchy to perform bitmap caching.
11811         */
11812        Canvas mCanvas;
11813
11814        /**
11815         * A Handler supplied by a view's {@link android.view.ViewRoot}. This
11816         * handler can be used to pump events in the UI events queue.
11817         */
11818        final Handler mHandler;
11819
11820        /**
11821         * Identifier for messages requesting the view to be invalidated.
11822         * Such messages should be sent to {@link #mHandler}.
11823         */
11824        static final int INVALIDATE_MSG = 0x1;
11825
11826        /**
11827         * Identifier for messages requesting the view to invalidate a region.
11828         * Such messages should be sent to {@link #mHandler}.
11829         */
11830        static final int INVALIDATE_RECT_MSG = 0x2;
11831
11832        /**
11833         * Temporary for use in computing invalidate rectangles while
11834         * calling up the hierarchy.
11835         */
11836        final Rect mTmpInvalRect = new Rect();
11837
11838        /**
11839         * Temporary for use in computing hit areas with transformed views
11840         */
11841        final RectF mTmpTransformRect = new RectF();
11842
11843        /**
11844         * Temporary list for use in collecting focusable descendents of a view.
11845         */
11846        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
11847
11848        /**
11849         * Creates a new set of attachment information with the specified
11850         * events handler and thread.
11851         *
11852         * @param handler the events handler the view must use
11853         */
11854        AttachInfo(IWindowSession session, IWindow window,
11855                Handler handler, Callbacks effectPlayer) {
11856            mSession = session;
11857            mWindow = window;
11858            mWindowToken = window.asBinder();
11859            mHandler = handler;
11860            mRootCallbacks = effectPlayer;
11861        }
11862    }
11863
11864    /**
11865     * <p>ScrollabilityCache holds various fields used by a View when scrolling
11866     * is supported. This avoids keeping too many unused fields in most
11867     * instances of View.</p>
11868     */
11869    private static class ScrollabilityCache implements Runnable {
11870
11871        /**
11872         * Scrollbars are not visible
11873         */
11874        public static final int OFF = 0;
11875
11876        /**
11877         * Scrollbars are visible
11878         */
11879        public static final int ON = 1;
11880
11881        /**
11882         * Scrollbars are fading away
11883         */
11884        public static final int FADING = 2;
11885
11886        public boolean fadeScrollBars;
11887
11888        public int fadingEdgeLength;
11889        public int scrollBarDefaultDelayBeforeFade;
11890        public int scrollBarFadeDuration;
11891
11892        public int scrollBarSize;
11893        public ScrollBarDrawable scrollBar;
11894        public float[] interpolatorValues;
11895        public View host;
11896
11897        public final Paint paint;
11898        public final Matrix matrix;
11899        public Shader shader;
11900
11901        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
11902
11903        private static final float[] OPAQUE = { 255 };
11904        private static final float[] TRANSPARENT = { 0.0f };
11905
11906        /**
11907         * When fading should start. This time moves into the future every time
11908         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
11909         */
11910        public long fadeStartTime;
11911
11912
11913        /**
11914         * The current state of the scrollbars: ON, OFF, or FADING
11915         */
11916        public int state = OFF;
11917
11918        private int mLastColor;
11919
11920        public ScrollabilityCache(ViewConfiguration configuration, View host) {
11921            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
11922            scrollBarSize = configuration.getScaledScrollBarSize();
11923            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
11924            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
11925
11926            paint = new Paint();
11927            matrix = new Matrix();
11928            // use use a height of 1, and then wack the matrix each time we
11929            // actually use it.
11930            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
11931
11932            paint.setShader(shader);
11933            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
11934            this.host = host;
11935        }
11936
11937        public void setFadeColor(int color) {
11938            if (color != 0 && color != mLastColor) {
11939                mLastColor = color;
11940                color |= 0xFF000000;
11941
11942                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
11943                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
11944
11945                paint.setShader(shader);
11946                // Restore the default transfer mode (src_over)
11947                paint.setXfermode(null);
11948            }
11949        }
11950
11951        public void run() {
11952            long now = AnimationUtils.currentAnimationTimeMillis();
11953            if (now >= fadeStartTime) {
11954
11955                // the animation fades the scrollbars out by changing
11956                // the opacity (alpha) from fully opaque to fully
11957                // transparent
11958                int nextFrame = (int) now;
11959                int framesCount = 0;
11960
11961                Interpolator interpolator = scrollBarInterpolator;
11962
11963                // Start opaque
11964                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
11965
11966                // End transparent
11967                nextFrame += scrollBarFadeDuration;
11968                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
11969
11970                state = FADING;
11971
11972                // Kick off the fade animation
11973                host.invalidate();
11974            }
11975        }
11976
11977    }
11978}
11979