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