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