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