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