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