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