View.java revision c46f7ffa9079f3ae8a5204e7519ed7a1250116d0
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.util.AttributeSet;
53import android.util.Log;
54import android.util.Pool;
55import android.util.Poolable;
56import android.util.PoolableManager;
57import android.util.Pools;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
64import android.view.accessibility.AccessibilityNodeInfo;
65import android.view.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.inputmethod.EditorInfo;
68import android.view.inputmethod.InputConnection;
69import android.view.inputmethod.InputMethodManager;
70import android.widget.ScrollBarDrawable;
71
72import java.lang.ref.WeakReference;
73import java.lang.reflect.InvocationTargetException;
74import java.lang.reflect.Method;
75import java.util.ArrayList;
76import java.util.Arrays;
77import java.util.WeakHashMap;
78import java.util.concurrent.CopyOnWriteArrayList;
79
80/**
81 * <p>
82 * This class represents the basic building block for user interface components. A View
83 * occupies a rectangular area on the screen and is responsible for drawing and
84 * event handling. View is the base class for <em>widgets</em>, which are
85 * used to create interactive UI components (buttons, text fields, etc.). The
86 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
87 * are invisible containers that hold other Views (or other ViewGroups) and define
88 * their layout properties.
89 * </p>
90 *
91 * <div class="special">
92 * <p>For an introduction to using this class to develop your
93 * application's user interface, read the Developer Guide documentation on
94 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
95 * include:
96 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
97 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
98 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
99 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
100 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
104 * </p>
105 * </div>
106 *
107 * <a name="Using"></a>
108 * <h3>Using Views</h3>
109 * <p>
110 * All of the views in a window are arranged in a single tree. You can add views
111 * either from code or by specifying a tree of views in one or more XML layout
112 * files. There are many specialized subclasses of views that act as controls or
113 * are capable of displaying text, images, or other content.
114 * </p>
115 * <p>
116 * Once you have created a tree of views, there are typically a few types of
117 * common operations you may wish to perform:
118 * <ul>
119 * <li><strong>Set properties:</strong> for example setting the text of a
120 * {@link android.widget.TextView}. The available properties and the methods
121 * that set them will vary among the different subclasses of views. Note that
122 * properties that are known at build time can be set in the XML layout
123 * files.</li>
124 * <li><strong>Set focus:</strong> The framework will handled moving focus in
125 * response to user input. To force focus to a specific view, call
126 * {@link #requestFocus}.</li>
127 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
128 * that will be notified when something interesting happens to the view. For
129 * example, all views will let you set a listener to be notified when the view
130 * gains or loses focus. You can register such a listener using
131 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
132 * Other view subclasses offer more specialized listeners. For example, a Button
133 * exposes a listener to notify clients when the button is clicked.</li>
134 * <li><strong>Set visibility:</strong> You can hide or show views using
135 * {@link #setVisibility(int)}.</li>
136 * </ul>
137 * </p>
138 * <p><em>
139 * Note: The Android framework is responsible for measuring, laying out and
140 * drawing views. You should not call methods that perform these actions on
141 * views yourself unless you are actually implementing a
142 * {@link android.view.ViewGroup}.
143 * </em></p>
144 *
145 * <a name="Lifecycle"></a>
146 * <h3>Implementing a Custom View</h3>
147 *
148 * <p>
149 * To implement a custom view, you will usually begin by providing overrides for
150 * some of the standard methods that the framework calls on all views. You do
151 * not need to override all of these methods. In fact, you can start by just
152 * overriding {@link #onDraw(android.graphics.Canvas)}.
153 * <table border="2" width="85%" align="center" cellpadding="5">
154 *     <thead>
155 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
156 *     </thead>
157 *
158 *     <tbody>
159 *     <tr>
160 *         <td rowspan="2">Creation</td>
161 *         <td>Constructors</td>
162 *         <td>There is a form of the constructor that are called when the view
163 *         is created from code and a form that is called when the view is
164 *         inflated from a layout file. The second form should parse and apply
165 *         any attributes defined in the layout file.
166 *         </td>
167 *     </tr>
168 *     <tr>
169 *         <td><code>{@link #onFinishInflate()}</code></td>
170 *         <td>Called after a view and all of its children has been inflated
171 *         from XML.</td>
172 *     </tr>
173 *
174 *     <tr>
175 *         <td rowspan="3">Layout</td>
176 *         <td><code>{@link #onMeasure(int, int)}</code></td>
177 *         <td>Called to determine the size requirements for this view and all
178 *         of its children.
179 *         </td>
180 *     </tr>
181 *     <tr>
182 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
183 *         <td>Called when this view should assign a size and position to all
184 *         of its children.
185 *         </td>
186 *     </tr>
187 *     <tr>
188 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
189 *         <td>Called when the size of this view has changed.
190 *         </td>
191 *     </tr>
192 *
193 *     <tr>
194 *         <td>Drawing</td>
195 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
196 *         <td>Called when the view should render its content.
197 *         </td>
198 *     </tr>
199 *
200 *     <tr>
201 *         <td rowspan="4">Event processing</td>
202 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
203 *         <td>Called when a new key event occurs.
204 *         </td>
205 *     </tr>
206 *     <tr>
207 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
208 *         <td>Called when a key up event occurs.
209 *         </td>
210 *     </tr>
211 *     <tr>
212 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
213 *         <td>Called when a trackball motion event occurs.
214 *         </td>
215 *     </tr>
216 *     <tr>
217 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
218 *         <td>Called when a touch screen motion event occurs.
219 *         </td>
220 *     </tr>
221 *
222 *     <tr>
223 *         <td rowspan="2">Focus</td>
224 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
225 *         <td>Called when the view gains or loses focus.
226 *         </td>
227 *     </tr>
228 *
229 *     <tr>
230 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
231 *         <td>Called when the window containing the view gains or loses focus.
232 *         </td>
233 *     </tr>
234 *
235 *     <tr>
236 *         <td rowspan="3">Attaching</td>
237 *         <td><code>{@link #onAttachedToWindow()}</code></td>
238 *         <td>Called when the view is attached to a window.
239 *         </td>
240 *     </tr>
241 *
242 *     <tr>
243 *         <td><code>{@link #onDetachedFromWindow}</code></td>
244 *         <td>Called when the view is detached from its window.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
250 *         <td>Called when the visibility of the window containing the view
251 *         has changed.
252 *         </td>
253 *     </tr>
254 *     </tbody>
255 *
256 * </table>
257 * </p>
258 *
259 * <a name="IDs"></a>
260 * <h3>IDs</h3>
261 * Views may have an integer id associated with them. These ids are typically
262 * assigned in the layout XML files, and are used to find specific views within
263 * the view tree. A common pattern is to:
264 * <ul>
265 * <li>Define a Button in the layout file and assign it a unique ID.
266 * <pre>
267 * &lt;Button
268 *     android:id="@+id/my_button"
269 *     android:layout_width="wrap_content"
270 *     android:layout_height="wrap_content"
271 *     android:text="@string/my_button_text"/&gt;
272 * </pre></li>
273 * <li>From the onCreate method of an Activity, find the Button
274 * <pre class="prettyprint">
275 *      Button myButton = (Button) findViewById(R.id.my_button);
276 * </pre></li>
277 * </ul>
278 * <p>
279 * View IDs need not be unique throughout the tree, but it is good practice to
280 * ensure that they are at least unique within the part of the tree you are
281 * searching.
282 * </p>
283 *
284 * <a name="Position"></a>
285 * <h3>Position</h3>
286 * <p>
287 * The geometry of a view is that of a rectangle. A view has a location,
288 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
289 * two dimensions, expressed as a width and a height. The unit for location
290 * and dimensions is the pixel.
291 * </p>
292 *
293 * <p>
294 * It is possible to retrieve the location of a view by invoking the methods
295 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
296 * coordinate of the rectangle representing the view. The latter returns the
297 * top, or Y, coordinate of the rectangle representing the view. These methods
298 * both return the location of the view relative to its parent. For instance,
299 * when getLeft() returns 20, that means the view is located 20 pixels to the
300 * right of the left edge of its direct parent.
301 * </p>
302 *
303 * <p>
304 * In addition, several convenience methods are offered to avoid unnecessary
305 * computations, namely {@link #getRight()} and {@link #getBottom()}.
306 * These methods return the coordinates of the right and bottom edges of the
307 * rectangle representing the view. For instance, calling {@link #getRight()}
308 * is similar to the following computation: <code>getLeft() + getWidth()</code>
309 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
310 * </p>
311 *
312 * <a name="SizePaddingMargins"></a>
313 * <h3>Size, padding and margins</h3>
314 * <p>
315 * The size of a view is expressed with a width and a height. A view actually
316 * possess two pairs of width and height values.
317 * </p>
318 *
319 * <p>
320 * The first pair is known as <em>measured width</em> and
321 * <em>measured height</em>. These dimensions define how big a view wants to be
322 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
323 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
324 * and {@link #getMeasuredHeight()}.
325 * </p>
326 *
327 * <p>
328 * The second pair is simply known as <em>width</em> and <em>height</em>, or
329 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
330 * dimensions define the actual size of the view on screen, at drawing time and
331 * after layout. These values may, but do not have to, be different from the
332 * measured width and height. The width and height can be obtained by calling
333 * {@link #getWidth()} and {@link #getHeight()}.
334 * </p>
335 *
336 * <p>
337 * To measure its dimensions, a view takes into account its padding. The padding
338 * is expressed in pixels for the left, top, right and bottom parts of the view.
339 * Padding can be used to offset the content of the view by a specific amount of
340 * pixels. For instance, a left padding of 2 will push the view's content by
341 * 2 pixels to the right of the left edge. Padding can be set using the
342 * {@link #setPadding(int, int, int, int)} method and queried by calling
343 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
344 * {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
345 * </p>
346 *
347 * <p>
348 * Even though a view can define a padding, it does not provide any support for
349 * margins. However, view groups provide such a support. Refer to
350 * {@link android.view.ViewGroup} and
351 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
352 * </p>
353 *
354 * <a name="Layout"></a>
355 * <h3>Layout</h3>
356 * <p>
357 * Layout is a two pass process: a measure pass and a layout pass. The measuring
358 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
359 * of the view tree. Each view pushes dimension specifications down the tree
360 * during the recursion. At the end of the measure pass, every view has stored
361 * its measurements. The second pass happens in
362 * {@link #layout(int,int,int,int)} and is also top-down. During
363 * this pass each parent is responsible for positioning all of its children
364 * using the sizes computed in the measure pass.
365 * </p>
366 *
367 * <p>
368 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
369 * {@link #getMeasuredHeight()} values must be set, along with those for all of
370 * that view's descendants. A view's measured width and measured height values
371 * must respect the constraints imposed by the view's parents. This guarantees
372 * that at the end of the measure pass, all parents accept all of their
373 * children's measurements. A parent view may call measure() more than once on
374 * its children. For example, the parent may measure each child once with
375 * unspecified dimensions to find out how big they want to be, then call
376 * measure() on them again with actual numbers if the sum of all the children's
377 * unconstrained sizes is too big or too small.
378 * </p>
379 *
380 * <p>
381 * The measure pass uses two classes to communicate dimensions. The
382 * {@link MeasureSpec} class is used by views to tell their parents how they
383 * want to be measured and positioned. The base LayoutParams class just
384 * describes how big the view wants to be for both width and height. For each
385 * dimension, it can specify one of:
386 * <ul>
387 * <li> an exact number
388 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
389 * (minus padding)
390 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
391 * enclose its content (plus padding).
392 * </ul>
393 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
394 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
395 * an X and Y value.
396 * </p>
397 *
398 * <p>
399 * MeasureSpecs are used to push requirements down the tree from parent to
400 * child. A MeasureSpec can be in one of three modes:
401 * <ul>
402 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
403 * of a child view. For example, a LinearLayout may call measure() on its child
404 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
405 * tall the child view wants to be given a width of 240 pixels.
406 * <li>EXACTLY: This is used by the parent to impose an exact size on the
407 * child. The child must use this size, and guarantee that all of its
408 * descendants will fit within this size.
409 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
410 * child. The child must gurantee that it and all of its descendants will fit
411 * within this size.
412 * </ul>
413 * </p>
414 *
415 * <p>
416 * To intiate a layout, call {@link #requestLayout}. This method is typically
417 * called by a view on itself when it believes that is can no longer fit within
418 * its current bounds.
419 * </p>
420 *
421 * <a name="Drawing"></a>
422 * <h3>Drawing</h3>
423 * <p>
424 * Drawing is handled by walking the tree and rendering each view that
425 * intersects the the invalid region. Because the tree is traversed in-order,
426 * this means that parents will draw before (i.e., behind) their children, with
427 * siblings drawn in the order they appear in the tree.
428 * If you set a background drawable for a View, then the View will draw it for you
429 * before calling back to its <code>onDraw()</code> method.
430 * </p>
431 *
432 * <p>
433 * Note that the framework will not draw views that are not in the invalid region.
434 * </p>
435 *
436 * <p>
437 * To force a view to draw, call {@link #invalidate()}.
438 * </p>
439 *
440 * <a name="EventHandlingThreading"></a>
441 * <h3>Event Handling and Threading</h3>
442 * <p>
443 * The basic cycle of a view is as follows:
444 * <ol>
445 * <li>An event comes in and is dispatched to the appropriate view. The view
446 * handles the event and notifies any listeners.</li>
447 * <li>If in the course of processing the event, the view's bounds may need
448 * to be changed, the view will call {@link #requestLayout()}.</li>
449 * <li>Similarly, if in the course of processing the event the view's appearance
450 * may need to be changed, the view will call {@link #invalidate()}.</li>
451 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
452 * the framework will take care of measuring, laying out, and drawing the tree
453 * as appropriate.</li>
454 * </ol>
455 * </p>
456 *
457 * <p><em>Note: The entire view tree is single threaded. You must always be on
458 * the UI thread when calling any method on any view.</em>
459 * If you are doing work on other threads and want to update the state of a view
460 * from that thread, you should use a {@link Handler}.
461 * </p>
462 *
463 * <a name="FocusHandling"></a>
464 * <h3>Focus Handling</h3>
465 * <p>
466 * The framework will handle routine focus movement in response to user input.
467 * This includes changing the focus as views are removed or hidden, or as new
468 * views become available. Views indicate their willingness to take focus
469 * through the {@link #isFocusable} method. To change whether a view can take
470 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
471 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
472 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
473 * </p>
474 * <p>
475 * Focus movement is based on an algorithm which finds the nearest neighbor in a
476 * given direction. In rare cases, the default algorithm may not match the
477 * intended behavior of the developer. In these situations, you can provide
478 * explicit overrides by using these XML attributes in the layout file:
479 * <pre>
480 * nextFocusDown
481 * nextFocusLeft
482 * nextFocusRight
483 * nextFocusUp
484 * </pre>
485 * </p>
486 *
487 *
488 * <p>
489 * To get a particular view to take focus, call {@link #requestFocus()}.
490 * </p>
491 *
492 * <a name="TouchMode"></a>
493 * <h3>Touch Mode</h3>
494 * <p>
495 * When a user is navigating a user interface via directional keys such as a D-pad, it is
496 * necessary to give focus to actionable items such as buttons so the user can see
497 * what will take input.  If the device has touch capabilities, however, and the user
498 * begins interacting with the interface by touching it, it is no longer necessary to
499 * always highlight, or give focus to, a particular view.  This motivates a mode
500 * for interaction named 'touch mode'.
501 * </p>
502 * <p>
503 * For a touch capable device, once the user touches the screen, the device
504 * will enter touch mode.  From this point onward, only views for which
505 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
506 * Other views that are touchable, like buttons, will not take focus when touched; they will
507 * only fire the on click listeners.
508 * </p>
509 * <p>
510 * Any time a user hits a directional key, such as a D-pad direction, the view device will
511 * exit touch mode, and find a view to take focus, so that the user may resume interacting
512 * with the user interface without touching the screen again.
513 * </p>
514 * <p>
515 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
516 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
517 * </p>
518 *
519 * <a name="Scrolling"></a>
520 * <h3>Scrolling</h3>
521 * <p>
522 * The framework provides basic support for views that wish to internally
523 * scroll their content. This includes keeping track of the X and Y scroll
524 * offset as well as mechanisms for drawing scrollbars. See
525 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
526 * {@link #awakenScrollBars()} for more details.
527 * </p>
528 *
529 * <a name="Tags"></a>
530 * <h3>Tags</h3>
531 * <p>
532 * Unlike IDs, tags are not used to identify views. Tags are essentially an
533 * extra piece of information that can be associated with a view. They are most
534 * often used as a convenience to store data related to views in the views
535 * themselves rather than by putting them in a separate structure.
536 * </p>
537 *
538 * <a name="Animation"></a>
539 * <h3>Animation</h3>
540 * <p>
541 * You can attach an {@link Animation} object to a view using
542 * {@link #setAnimation(Animation)} or
543 * {@link #startAnimation(Animation)}. The animation can alter the scale,
544 * rotation, translation and alpha of a view over time. If the animation is
545 * attached to a view that has children, the animation will affect the entire
546 * subtree rooted by that node. When an animation is started, the framework will
547 * take care of redrawing the appropriate views until the animation completes.
548 * </p>
549 * <p>
550 * Starting with Android 3.0, the preferred way of animating views is to use the
551 * {@link android.animation} package APIs.
552 * </p>
553 *
554 * <a name="Security"></a>
555 * <h3>Security</h3>
556 * <p>
557 * Sometimes it is essential that an application be able to verify that an action
558 * is being performed with the full knowledge and consent of the user, such as
559 * granting a permission request, making a purchase or clicking on an advertisement.
560 * Unfortunately, a malicious application could try to spoof the user into
561 * performing these actions, unaware, by concealing the intended purpose of the view.
562 * As a remedy, the framework offers a touch filtering mechanism that can be used to
563 * improve the security of views that provide access to sensitive functionality.
564 * </p><p>
565 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
566 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
567 * will discard touches that are received whenever the view's window is obscured by
568 * another visible window.  As a result, the view will not receive touches whenever a
569 * toast, dialog or other window appears above the view's window.
570 * </p><p>
571 * For more fine-grained control over security, consider overriding the
572 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
573 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
574 * </p>
575 *
576 * @attr ref android.R.styleable#View_alpha
577 * @attr ref android.R.styleable#View_background
578 * @attr ref android.R.styleable#View_clickable
579 * @attr ref android.R.styleable#View_contentDescription
580 * @attr ref android.R.styleable#View_drawingCacheQuality
581 * @attr ref android.R.styleable#View_duplicateParentState
582 * @attr ref android.R.styleable#View_id
583 * @attr ref android.R.styleable#View_fadingEdge
584 * @attr ref android.R.styleable#View_fadingEdgeLength
585 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
586 * @attr ref android.R.styleable#View_fitsSystemWindows
587 * @attr ref android.R.styleable#View_isScrollContainer
588 * @attr ref android.R.styleable#View_focusable
589 * @attr ref android.R.styleable#View_focusableInTouchMode
590 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
591 * @attr ref android.R.styleable#View_keepScreenOn
592 * @attr ref android.R.styleable#View_layerType
593 * @attr ref android.R.styleable#View_longClickable
594 * @attr ref android.R.styleable#View_minHeight
595 * @attr ref android.R.styleable#View_minWidth
596 * @attr ref android.R.styleable#View_nextFocusDown
597 * @attr ref android.R.styleable#View_nextFocusLeft
598 * @attr ref android.R.styleable#View_nextFocusRight
599 * @attr ref android.R.styleable#View_nextFocusUp
600 * @attr ref android.R.styleable#View_onClick
601 * @attr ref android.R.styleable#View_padding
602 * @attr ref android.R.styleable#View_paddingBottom
603 * @attr ref android.R.styleable#View_paddingLeft
604 * @attr ref android.R.styleable#View_paddingRight
605 * @attr ref android.R.styleable#View_paddingTop
606 * @attr ref android.R.styleable#View_saveEnabled
607 * @attr ref android.R.styleable#View_rotation
608 * @attr ref android.R.styleable#View_rotationX
609 * @attr ref android.R.styleable#View_rotationY
610 * @attr ref android.R.styleable#View_scaleX
611 * @attr ref android.R.styleable#View_scaleY
612 * @attr ref android.R.styleable#View_scrollX
613 * @attr ref android.R.styleable#View_scrollY
614 * @attr ref android.R.styleable#View_scrollbarSize
615 * @attr ref android.R.styleable#View_scrollbarStyle
616 * @attr ref android.R.styleable#View_scrollbars
617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
618 * @attr ref android.R.styleable#View_scrollbarFadeDuration
619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
621 * @attr ref android.R.styleable#View_scrollbarThumbVertical
622 * @attr ref android.R.styleable#View_scrollbarTrackVertical
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
625 * @attr ref android.R.styleable#View_soundEffectsEnabled
626 * @attr ref android.R.styleable#View_tag
627 * @attr ref android.R.styleable#View_transformPivotX
628 * @attr ref android.R.styleable#View_transformPivotY
629 * @attr ref android.R.styleable#View_translationX
630 * @attr ref android.R.styleable#View_translationY
631 * @attr ref android.R.styleable#View_visibility
632 *
633 * @see android.view.ViewGroup
634 */
635public class View implements Drawable.Callback2, KeyEvent.Callback, AccessibilityEventSource {
636    private static final boolean DBG = false;
637
638    /**
639     * The logging tag used by this class with android.util.Log.
640     */
641    protected static final String VIEW_LOG_TAG = "View";
642
643    /**
644     * Used to mark a View that has no ID.
645     */
646    public static final int NO_ID = -1;
647
648    /**
649     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
650     * calling setFlags.
651     */
652    private static final int NOT_FOCUSABLE = 0x00000000;
653
654    /**
655     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
656     * setFlags.
657     */
658    private static final int FOCUSABLE = 0x00000001;
659
660    /**
661     * Mask for use with setFlags indicating bits used for focus.
662     */
663    private static final int FOCUSABLE_MASK = 0x00000001;
664
665    /**
666     * This view will adjust its padding to fit sytem windows (e.g. status bar)
667     */
668    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
669
670    /**
671     * This view is visible.  Use with {@link #setVisibility(int)}.
672     */
673    public static final int VISIBLE = 0x00000000;
674
675    /**
676     * This view is invisible, but it still takes up space for layout purposes.
677     * Use with {@link #setVisibility(int)}.
678     */
679    public static final int INVISIBLE = 0x00000004;
680
681    /**
682     * This view is invisible, and it doesn't take any space for layout
683     * purposes. Use with {@link #setVisibility(int)}.
684     */
685    public static final int GONE = 0x00000008;
686
687    /**
688     * Mask for use with setFlags indicating bits used for visibility.
689     * {@hide}
690     */
691    static final int VISIBILITY_MASK = 0x0000000C;
692
693    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
694
695    /**
696     * This view is enabled. Intrepretation varies by subclass.
697     * Use with ENABLED_MASK when calling setFlags.
698     * {@hide}
699     */
700    static final int ENABLED = 0x00000000;
701
702    /**
703     * This view is disabled. Intrepretation varies by subclass.
704     * Use with ENABLED_MASK when calling setFlags.
705     * {@hide}
706     */
707    static final int DISABLED = 0x00000020;
708
709   /**
710    * Mask for use with setFlags indicating bits used for indicating whether
711    * this view is enabled
712    * {@hide}
713    */
714    static final int ENABLED_MASK = 0x00000020;
715
716    /**
717     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
718     * called and further optimizations will be performed. It is okay to have
719     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
720     * {@hide}
721     */
722    static final int WILL_NOT_DRAW = 0x00000080;
723
724    /**
725     * Mask for use with setFlags indicating bits used for indicating whether
726     * this view is will draw
727     * {@hide}
728     */
729    static final int DRAW_MASK = 0x00000080;
730
731    /**
732     * <p>This view doesn't show scrollbars.</p>
733     * {@hide}
734     */
735    static final int SCROLLBARS_NONE = 0x00000000;
736
737    /**
738     * <p>This view shows horizontal scrollbars.</p>
739     * {@hide}
740     */
741    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
742
743    /**
744     * <p>This view shows vertical scrollbars.</p>
745     * {@hide}
746     */
747    static final int SCROLLBARS_VERTICAL = 0x00000200;
748
749    /**
750     * <p>Mask for use with setFlags indicating bits used for indicating which
751     * scrollbars are enabled.</p>
752     * {@hide}
753     */
754    static final int SCROLLBARS_MASK = 0x00000300;
755
756    /**
757     * Indicates that the view should filter touches when its window is obscured.
758     * Refer to the class comments for more information about this security feature.
759     * {@hide}
760     */
761    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
762
763    // note flag value 0x00000800 is now available for next flags...
764
765    /**
766     * <p>This view doesn't show fading edges.</p>
767     * {@hide}
768     */
769    static final int FADING_EDGE_NONE = 0x00000000;
770
771    /**
772     * <p>This view shows horizontal fading edges.</p>
773     * {@hide}
774     */
775    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
776
777    /**
778     * <p>This view shows vertical fading edges.</p>
779     * {@hide}
780     */
781    static final int FADING_EDGE_VERTICAL = 0x00002000;
782
783    /**
784     * <p>Mask for use with setFlags indicating bits used for indicating which
785     * fading edges are enabled.</p>
786     * {@hide}
787     */
788    static final int FADING_EDGE_MASK = 0x00003000;
789
790    /**
791     * <p>Indicates this view can be clicked. When clickable, a View reacts
792     * to clicks by notifying the OnClickListener.<p>
793     * {@hide}
794     */
795    static final int CLICKABLE = 0x00004000;
796
797    /**
798     * <p>Indicates this view is caching its drawing into a bitmap.</p>
799     * {@hide}
800     */
801    static final int DRAWING_CACHE_ENABLED = 0x00008000;
802
803    /**
804     * <p>Indicates that no icicle should be saved for this view.<p>
805     * {@hide}
806     */
807    static final int SAVE_DISABLED = 0x000010000;
808
809    /**
810     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
811     * property.</p>
812     * {@hide}
813     */
814    static final int SAVE_DISABLED_MASK = 0x000010000;
815
816    /**
817     * <p>Indicates that no drawing cache should ever be created for this view.<p>
818     * {@hide}
819     */
820    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
821
822    /**
823     * <p>Indicates this view can take / keep focus when int touch mode.</p>
824     * {@hide}
825     */
826    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
827
828    /**
829     * <p>Enables low quality mode for the drawing cache.</p>
830     */
831    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
832
833    /**
834     * <p>Enables high quality mode for the drawing cache.</p>
835     */
836    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
837
838    /**
839     * <p>Enables automatic quality mode for the drawing cache.</p>
840     */
841    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
842
843    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
844            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
845    };
846
847    /**
848     * <p>Mask for use with setFlags indicating bits used for the cache
849     * quality property.</p>
850     * {@hide}
851     */
852    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
853
854    /**
855     * <p>
856     * Indicates this view can be long clicked. When long clickable, a View
857     * reacts to long clicks by notifying the OnLongClickListener or showing a
858     * context menu.
859     * </p>
860     * {@hide}
861     */
862    static final int LONG_CLICKABLE = 0x00200000;
863
864    /**
865     * <p>Indicates that this view gets its drawable states from its direct parent
866     * and ignores its original internal states.</p>
867     *
868     * @hide
869     */
870    static final int DUPLICATE_PARENT_STATE = 0x00400000;
871
872    /**
873     * The scrollbar style to display the scrollbars inside the content area,
874     * without increasing the padding. The scrollbars will be overlaid with
875     * translucency on the view's content.
876     */
877    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
878
879    /**
880     * The scrollbar style to display the scrollbars inside the padded area,
881     * increasing the padding of the view. The scrollbars will not overlap the
882     * content area of the view.
883     */
884    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
885
886    /**
887     * The scrollbar style to display the scrollbars at the edge of the view,
888     * without increasing the padding. The scrollbars will be overlaid with
889     * translucency.
890     */
891    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
892
893    /**
894     * The scrollbar style to display the scrollbars at the edge of the view,
895     * increasing the padding of the view. The scrollbars will only overlap the
896     * background, if any.
897     */
898    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
899
900    /**
901     * Mask to check if the scrollbar style is overlay or inset.
902     * {@hide}
903     */
904    static final int SCROLLBARS_INSET_MASK = 0x01000000;
905
906    /**
907     * Mask to check if the scrollbar style is inside or outside.
908     * {@hide}
909     */
910    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
911
912    /**
913     * Mask for scrollbar style.
914     * {@hide}
915     */
916    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
917
918    /**
919     * View flag indicating that the screen should remain on while the
920     * window containing this view is visible to the user.  This effectively
921     * takes care of automatically setting the WindowManager's
922     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
923     */
924    public static final int KEEP_SCREEN_ON = 0x04000000;
925
926    /**
927     * View flag indicating whether this view should have sound effects enabled
928     * for events such as clicking and touching.
929     */
930    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
931
932    /**
933     * View flag indicating whether this view should have haptic feedback
934     * enabled for events such as long presses.
935     */
936    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
937
938    /**
939     * <p>Indicates that the view hierarchy should stop saving state when
940     * it reaches this view.  If state saving is initiated immediately at
941     * the view, it will be allowed.
942     * {@hide}
943     */
944    static final int PARENT_SAVE_DISABLED = 0x20000000;
945
946    /**
947     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
948     * {@hide}
949     */
950    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
951
952    /**
953     * Horizontal direction of this view is from Left to Right.
954     * Use with {@link #setLayoutDirection}.
955     * {@hide}
956     */
957    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
958
959    /**
960     * Horizontal direction of this view is from Right to Left.
961     * Use with {@link #setLayoutDirection}.
962     * {@hide}
963     */
964    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
965
966    /**
967     * Horizontal direction of this view is inherited from its parent.
968     * Use with {@link #setLayoutDirection}.
969     * {@hide}
970     */
971    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
972
973    /**
974     * Horizontal direction of this view is from deduced from the default language
975     * script for the locale. Use with {@link #setLayoutDirection}.
976     * {@hide}
977     */
978    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
979
980    /**
981     * Mask for use with setFlags indicating bits used for horizontalDirection.
982     * {@hide}
983     */
984    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
985
986    /*
987     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
988     * flag value.
989     * {@hide}
990     */
991    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
992        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
993
994    /**
995     * Default horizontalDirection.
996     * {@hide}
997     */
998    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
999
1000    /**
1001     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1002     * should add all focusable Views regardless if they are focusable in touch mode.
1003     */
1004    public static final int FOCUSABLES_ALL = 0x00000000;
1005
1006    /**
1007     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1008     * should add only Views focusable in touch mode.
1009     */
1010    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1011
1012    /**
1013     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1014     * item.
1015     */
1016    public static final int FOCUS_BACKWARD = 0x00000001;
1017
1018    /**
1019     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1020     * item.
1021     */
1022    public static final int FOCUS_FORWARD = 0x00000002;
1023
1024    /**
1025     * Use with {@link #focusSearch(int)}. Move focus to the left.
1026     */
1027    public static final int FOCUS_LEFT = 0x00000011;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus up.
1031     */
1032    public static final int FOCUS_UP = 0x00000021;
1033
1034    /**
1035     * Use with {@link #focusSearch(int)}. Move focus to the right.
1036     */
1037    public static final int FOCUS_RIGHT = 0x00000042;
1038
1039    /**
1040     * Use with {@link #focusSearch(int)}. Move focus down.
1041     */
1042    public static final int FOCUS_DOWN = 0x00000082;
1043
1044    /**
1045     * Bits of {@link #getMeasuredWidthAndState()} and
1046     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1047     */
1048    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1049
1050    /**
1051     * Bits of {@link #getMeasuredWidthAndState()} and
1052     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1053     */
1054    public static final int MEASURED_STATE_MASK = 0xff000000;
1055
1056    /**
1057     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1058     * for functions that combine both width and height into a single int,
1059     * such as {@link #getMeasuredState()} and the childState argument of
1060     * {@link #resolveSizeAndState(int, int, int)}.
1061     */
1062    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1063
1064    /**
1065     * Bit of {@link #getMeasuredWidthAndState()} and
1066     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1067     * is smaller that the space the view would like to have.
1068     */
1069    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1070
1071    /**
1072     * Base View state sets
1073     */
1074    // Singles
1075    /**
1076     * Indicates the view has no states set. 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[] EMPTY_STATE_SET;
1084    /**
1085     * Indicates the view is enabled. States are used with
1086     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1087     * view depending on its state.
1088     *
1089     * @see android.graphics.drawable.Drawable
1090     * @see #getDrawableState()
1091     */
1092    protected static final int[] ENABLED_STATE_SET;
1093    /**
1094     * Indicates the view is focused. States are used with
1095     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1096     * view depending on its state.
1097     *
1098     * @see android.graphics.drawable.Drawable
1099     * @see #getDrawableState()
1100     */
1101    protected static final int[] FOCUSED_STATE_SET;
1102    /**
1103     * Indicates the view is selected. States are used with
1104     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1105     * view depending on its state.
1106     *
1107     * @see android.graphics.drawable.Drawable
1108     * @see #getDrawableState()
1109     */
1110    protected static final int[] SELECTED_STATE_SET;
1111    /**
1112     * Indicates the view is pressed. States are used with
1113     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1114     * view depending on its state.
1115     *
1116     * @see android.graphics.drawable.Drawable
1117     * @see #getDrawableState()
1118     * @hide
1119     */
1120    protected static final int[] PRESSED_STATE_SET;
1121    /**
1122     * Indicates the view's window has focus. States are used with
1123     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1124     * view depending on its state.
1125     *
1126     * @see android.graphics.drawable.Drawable
1127     * @see #getDrawableState()
1128     */
1129    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1130    // Doubles
1131    /**
1132     * Indicates the view is enabled and has the focus.
1133     *
1134     * @see #ENABLED_STATE_SET
1135     * @see #FOCUSED_STATE_SET
1136     */
1137    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1138    /**
1139     * Indicates the view is enabled and selected.
1140     *
1141     * @see #ENABLED_STATE_SET
1142     * @see #SELECTED_STATE_SET
1143     */
1144    protected static final int[] ENABLED_SELECTED_STATE_SET;
1145    /**
1146     * Indicates the view is enabled and that its window has focus.
1147     *
1148     * @see #ENABLED_STATE_SET
1149     * @see #WINDOW_FOCUSED_STATE_SET
1150     */
1151    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1152    /**
1153     * Indicates the view is focused and selected.
1154     *
1155     * @see #FOCUSED_STATE_SET
1156     * @see #SELECTED_STATE_SET
1157     */
1158    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1159    /**
1160     * Indicates the view has the focus and that its window has the focus.
1161     *
1162     * @see #FOCUSED_STATE_SET
1163     * @see #WINDOW_FOCUSED_STATE_SET
1164     */
1165    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1166    /**
1167     * Indicates the view is selected and that its window has the focus.
1168     *
1169     * @see #SELECTED_STATE_SET
1170     * @see #WINDOW_FOCUSED_STATE_SET
1171     */
1172    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1173    // Triples
1174    /**
1175     * Indicates the view is enabled, focused and selected.
1176     *
1177     * @see #ENABLED_STATE_SET
1178     * @see #FOCUSED_STATE_SET
1179     * @see #SELECTED_STATE_SET
1180     */
1181    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1182    /**
1183     * Indicates the view is enabled, focused and its window has the focus.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #WINDOW_FOCUSED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, selected and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #SELECTED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is focused, selected and its window has the focus.
1200     *
1201     * @see #FOCUSED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is enabled, focused, selected and its window
1208     * has the focus.
1209     *
1210     * @see #ENABLED_STATE_SET
1211     * @see #FOCUSED_STATE_SET
1212     * @see #SELECTED_STATE_SET
1213     * @see #WINDOW_FOCUSED_STATE_SET
1214     */
1215    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1216    /**
1217     * Indicates the view is pressed and its window has the focus.
1218     *
1219     * @see #PRESSED_STATE_SET
1220     * @see #WINDOW_FOCUSED_STATE_SET
1221     */
1222    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1223    /**
1224     * Indicates the view is pressed and selected.
1225     *
1226     * @see #PRESSED_STATE_SET
1227     * @see #SELECTED_STATE_SET
1228     */
1229    protected static final int[] PRESSED_SELECTED_STATE_SET;
1230    /**
1231     * Indicates the view is pressed, selected and its window has the focus.
1232     *
1233     * @see #PRESSED_STATE_SET
1234     * @see #SELECTED_STATE_SET
1235     * @see #WINDOW_FOCUSED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed and focused.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #FOCUSED_STATE_SET
1243     */
1244    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1245    /**
1246     * Indicates the view is pressed, focused and its window has the focus.
1247     *
1248     * @see #PRESSED_STATE_SET
1249     * @see #FOCUSED_STATE_SET
1250     * @see #WINDOW_FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and selected.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #SELECTED_STATE_SET
1258     * @see #FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused, selected and its window has the focus.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #FOCUSED_STATE_SET
1266     * @see #SELECTED_STATE_SET
1267     * @see #WINDOW_FOCUSED_STATE_SET
1268     */
1269    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1270    /**
1271     * Indicates the view is pressed and enabled.
1272     *
1273     * @see #PRESSED_STATE_SET
1274     * @see #ENABLED_STATE_SET
1275     */
1276    protected static final int[] PRESSED_ENABLED_STATE_SET;
1277    /**
1278     * Indicates the view is pressed, enabled and its window has the focus.
1279     *
1280     * @see #PRESSED_STATE_SET
1281     * @see #ENABLED_STATE_SET
1282     * @see #WINDOW_FOCUSED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and selected.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #SELECTED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled, selected and its window has the
1295     * focus.
1296     *
1297     * @see #PRESSED_STATE_SET
1298     * @see #ENABLED_STATE_SET
1299     * @see #SELECTED_STATE_SET
1300     * @see #WINDOW_FOCUSED_STATE_SET
1301     */
1302    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1303    /**
1304     * Indicates the view is pressed, enabled and focused.
1305     *
1306     * @see #PRESSED_STATE_SET
1307     * @see #ENABLED_STATE_SET
1308     * @see #FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled, focused and its window has the
1313     * focus.
1314     *
1315     * @see #PRESSED_STATE_SET
1316     * @see #ENABLED_STATE_SET
1317     * @see #FOCUSED_STATE_SET
1318     * @see #WINDOW_FOCUSED_STATE_SET
1319     */
1320    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1321    /**
1322     * Indicates the view is pressed, enabled, focused and selected.
1323     *
1324     * @see #PRESSED_STATE_SET
1325     * @see #ENABLED_STATE_SET
1326     * @see #SELECTED_STATE_SET
1327     * @see #FOCUSED_STATE_SET
1328     */
1329    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1330    /**
1331     * Indicates the view is pressed, enabled, focused, selected and its window
1332     * has the focus.
1333     *
1334     * @see #PRESSED_STATE_SET
1335     * @see #ENABLED_STATE_SET
1336     * @see #SELECTED_STATE_SET
1337     * @see #FOCUSED_STATE_SET
1338     * @see #WINDOW_FOCUSED_STATE_SET
1339     */
1340    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1341
1342    /**
1343     * The order here is very important to {@link #getDrawableState()}
1344     */
1345    private static final int[][] VIEW_STATE_SETS;
1346
1347    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1348    static final int VIEW_STATE_SELECTED = 1 << 1;
1349    static final int VIEW_STATE_FOCUSED = 1 << 2;
1350    static final int VIEW_STATE_ENABLED = 1 << 3;
1351    static final int VIEW_STATE_PRESSED = 1 << 4;
1352    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1353    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1354    static final int VIEW_STATE_HOVERED = 1 << 7;
1355    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1356    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1357
1358    static final int[] VIEW_STATE_IDS = new int[] {
1359        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1360        R.attr.state_selected,          VIEW_STATE_SELECTED,
1361        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1362        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1363        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1364        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1365        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1366        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1367        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1368        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1369    };
1370
1371    static {
1372        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1373            throw new IllegalStateException(
1374                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1375        }
1376        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1377        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1378            int viewState = R.styleable.ViewDrawableStates[i];
1379            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1380                if (VIEW_STATE_IDS[j] == viewState) {
1381                    orderedIds[i * 2] = viewState;
1382                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1383                }
1384            }
1385        }
1386        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1387        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1388        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1389            int numBits = Integer.bitCount(i);
1390            int[] set = new int[numBits];
1391            int pos = 0;
1392            for (int j = 0; j < orderedIds.length; j += 2) {
1393                if ((i & orderedIds[j+1]) != 0) {
1394                    set[pos++] = orderedIds[j];
1395                }
1396            }
1397            VIEW_STATE_SETS[i] = set;
1398        }
1399
1400        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1401        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1402        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1403        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1404                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1405        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1406        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1408        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1409                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1410        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1411                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1412                | VIEW_STATE_FOCUSED];
1413        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1414        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1416        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1418        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_ENABLED];
1421        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1423        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1424                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1425                | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1431                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1432
1433        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1434        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1436        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1437                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1438        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1439                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1440                | VIEW_STATE_PRESSED];
1441        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1443        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1444                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1445                | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1451                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1452        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1454        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1459                | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1462                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1465                | VIEW_STATE_PRESSED];
1466        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1468                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1469        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1472        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1474                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1475                | VIEW_STATE_PRESSED];
1476    }
1477
1478    /**
1479     * Temporary Rect currently for use in setBackground().  This will probably
1480     * be extended in the future to hold our own class with more than just
1481     * a Rect. :)
1482     */
1483    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1484
1485    /**
1486     * Map used to store views' tags.
1487     */
1488    private static WeakHashMap<View, SparseArray<Object>> sTags;
1489
1490    /**
1491     * Lock used to access sTags.
1492     */
1493    private static final Object sTagsLock = new Object();
1494
1495    /**
1496     * The next available accessiiblity id.
1497     */
1498    private static int sNextAccessibilityViewId;
1499
1500    /**
1501     * The animation currently associated with this view.
1502     * @hide
1503     */
1504    protected Animation mCurrentAnimation = null;
1505
1506    /**
1507     * Width as measured during measure pass.
1508     * {@hide}
1509     */
1510    @ViewDebug.ExportedProperty(category = "measurement")
1511    int mMeasuredWidth;
1512
1513    /**
1514     * Height as measured during measure pass.
1515     * {@hide}
1516     */
1517    @ViewDebug.ExportedProperty(category = "measurement")
1518    int mMeasuredHeight;
1519
1520    /**
1521     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1522     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1523     * its display list. This flag, used only when hw accelerated, allows us to clear the
1524     * flag while retaining this information until it's needed (at getDisplayList() time and
1525     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1526     *
1527     * {@hide}
1528     */
1529    boolean mRecreateDisplayList = false;
1530
1531    /**
1532     * The view's identifier.
1533     * {@hide}
1534     *
1535     * @see #setId(int)
1536     * @see #getId()
1537     */
1538    @ViewDebug.ExportedProperty(resolveId = true)
1539    int mID = NO_ID;
1540
1541    /**
1542     * The stable ID of this view for accessibility porposes.
1543     */
1544    int mAccessibilityViewId = NO_ID;
1545
1546    /**
1547     * The view's tag.
1548     * {@hide}
1549     *
1550     * @see #setTag(Object)
1551     * @see #getTag()
1552     */
1553    protected Object mTag;
1554
1555    // for mPrivateFlags:
1556    /** {@hide} */
1557    static final int WANTS_FOCUS                    = 0x00000001;
1558    /** {@hide} */
1559    static final int FOCUSED                        = 0x00000002;
1560    /** {@hide} */
1561    static final int SELECTED                       = 0x00000004;
1562    /** {@hide} */
1563    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1564    /** {@hide} */
1565    static final int HAS_BOUNDS                     = 0x00000010;
1566    /** {@hide} */
1567    static final int DRAWN                          = 0x00000020;
1568    /**
1569     * When this flag is set, this view is running an animation on behalf of its
1570     * children and should therefore not cancel invalidate requests, even if they
1571     * lie outside of this view's bounds.
1572     *
1573     * {@hide}
1574     */
1575    static final int DRAW_ANIMATION                 = 0x00000040;
1576    /** {@hide} */
1577    static final int SKIP_DRAW                      = 0x00000080;
1578    /** {@hide} */
1579    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1580    /** {@hide} */
1581    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1582    /** {@hide} */
1583    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1584    /** {@hide} */
1585    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1586    /** {@hide} */
1587    static final int FORCE_LAYOUT                   = 0x00001000;
1588    /** {@hide} */
1589    static final int LAYOUT_REQUIRED                = 0x00002000;
1590
1591    private static final int PRESSED                = 0x00004000;
1592
1593    /** {@hide} */
1594    static final int DRAWING_CACHE_VALID            = 0x00008000;
1595    /**
1596     * Flag used to indicate that this view should be drawn once more (and only once
1597     * more) after its animation has completed.
1598     * {@hide}
1599     */
1600    static final int ANIMATION_STARTED              = 0x00010000;
1601
1602    private static final int SAVE_STATE_CALLED      = 0x00020000;
1603
1604    /**
1605     * Indicates that the View returned true when onSetAlpha() was called and that
1606     * the alpha must be restored.
1607     * {@hide}
1608     */
1609    static final int ALPHA_SET                      = 0x00040000;
1610
1611    /**
1612     * Set by {@link #setScrollContainer(boolean)}.
1613     */
1614    static final int SCROLL_CONTAINER               = 0x00080000;
1615
1616    /**
1617     * Set by {@link #setScrollContainer(boolean)}.
1618     */
1619    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1620
1621    /**
1622     * View flag indicating whether this view was invalidated (fully or partially.)
1623     *
1624     * @hide
1625     */
1626    static final int DIRTY                          = 0x00200000;
1627
1628    /**
1629     * View flag indicating whether this view was invalidated by an opaque
1630     * invalidate request.
1631     *
1632     * @hide
1633     */
1634    static final int DIRTY_OPAQUE                   = 0x00400000;
1635
1636    /**
1637     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1638     *
1639     * @hide
1640     */
1641    static final int DIRTY_MASK                     = 0x00600000;
1642
1643    /**
1644     * Indicates whether the background is opaque.
1645     *
1646     * @hide
1647     */
1648    static final int OPAQUE_BACKGROUND              = 0x00800000;
1649
1650    /**
1651     * Indicates whether the scrollbars are opaque.
1652     *
1653     * @hide
1654     */
1655    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1656
1657    /**
1658     * Indicates whether the view is opaque.
1659     *
1660     * @hide
1661     */
1662    static final int OPAQUE_MASK                    = 0x01800000;
1663
1664    /**
1665     * Indicates a prepressed state;
1666     * the short time between ACTION_DOWN and recognizing
1667     * a 'real' press. Prepressed is used to recognize quick taps
1668     * even when they are shorter than ViewConfiguration.getTapTimeout().
1669     *
1670     * @hide
1671     */
1672    private static final int PREPRESSED             = 0x02000000;
1673
1674    /**
1675     * Indicates whether the view is temporarily detached.
1676     *
1677     * @hide
1678     */
1679    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1680
1681    /**
1682     * Indicates that we should awaken scroll bars once attached
1683     *
1684     * @hide
1685     */
1686    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1687
1688    /**
1689     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1690     * @hide
1691     */
1692    private static final int HOVERED              = 0x10000000;
1693
1694    /**
1695     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1696     * for transform operations
1697     *
1698     * @hide
1699     */
1700    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1701
1702    /** {@hide} */
1703    static final int ACTIVATED                    = 0x40000000;
1704
1705    /**
1706     * Indicates that this view was specifically invalidated, not just dirtied because some
1707     * child view was invalidated. The flag is used to determine when we need to recreate
1708     * a view's display list (as opposed to just returning a reference to its existing
1709     * display list).
1710     *
1711     * @hide
1712     */
1713    static final int INVALIDATED                  = 0x80000000;
1714
1715    /* Masks for mPrivateFlags2 */
1716
1717    /**
1718     * Indicates that this view has reported that it can accept the current drag's content.
1719     * Cleared when the drag operation concludes.
1720     * @hide
1721     */
1722    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1723
1724    /**
1725     * Indicates that this view is currently directly under the drag location in a
1726     * drag-and-drop operation involving content that it can accept.  Cleared when
1727     * the drag exits the view, or when the drag operation concludes.
1728     * @hide
1729     */
1730    static final int DRAG_HOVERED                 = 0x00000002;
1731
1732    /**
1733     * Indicates whether the view is drawn in right-to-left direction.
1734     *
1735     * @hide
1736     */
1737    static final int RESOLVED_LAYOUT_RTL          = 0x00000004;
1738
1739    /* End of masks for mPrivateFlags2 */
1740
1741    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1742
1743    /**
1744     * Always allow a user to over-scroll this view, provided it is a
1745     * view that can scroll.
1746     *
1747     * @see #getOverScrollMode()
1748     * @see #setOverScrollMode(int)
1749     */
1750    public static final int OVER_SCROLL_ALWAYS = 0;
1751
1752    /**
1753     * Allow a user to over-scroll this view only if the content is large
1754     * enough to meaningfully scroll, provided it is a view that can scroll.
1755     *
1756     * @see #getOverScrollMode()
1757     * @see #setOverScrollMode(int)
1758     */
1759    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1760
1761    /**
1762     * Never allow a user to over-scroll this view.
1763     *
1764     * @see #getOverScrollMode()
1765     * @see #setOverScrollMode(int)
1766     */
1767    public static final int OVER_SCROLL_NEVER = 2;
1768
1769    /**
1770     * View has requested the status bar to be visible (the default).
1771     *
1772     * @see #setSystemUiVisibility(int)
1773     */
1774    public static final int STATUS_BAR_VISIBLE = 0;
1775
1776    /**
1777     * View has requested the status bar to be hidden.
1778     *
1779     * @see #setSystemUiVisibility(int)
1780     */
1781    public static final int STATUS_BAR_HIDDEN = 0x00000001;
1782
1783    /**
1784     * @hide
1785     *
1786     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1787     * out of the public fields to keep the undefined bits out of the developer's way.
1788     *
1789     * Flag to make the status bar not expandable.  Unless you also
1790     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1791     */
1792    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1793
1794    /**
1795     * @hide
1796     *
1797     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1798     * out of the public fields to keep the undefined bits out of the developer's way.
1799     *
1800     * Flag to hide notification icons and scrolling ticker text.
1801     */
1802    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1803
1804    /**
1805     * @hide
1806     *
1807     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1808     * out of the public fields to keep the undefined bits out of the developer's way.
1809     *
1810     * Flag to disable incoming notification alerts.  This will not block
1811     * icons, but it will block sound, vibrating and other visual or aural notifications.
1812     */
1813    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1814
1815    /**
1816     * @hide
1817     *
1818     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1819     * out of the public fields to keep the undefined bits out of the developer's way.
1820     *
1821     * Flag to hide only the scrolling ticker.  Note that
1822     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1823     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1824     */
1825    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1826
1827    /**
1828     * @hide
1829     *
1830     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1831     * out of the public fields to keep the undefined bits out of the developer's way.
1832     *
1833     * Flag to hide the center system info area.
1834     */
1835    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1836
1837    /**
1838     * @hide
1839     *
1840     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1841     * out of the public fields to keep the undefined bits out of the developer's way.
1842     *
1843     * Flag to hide only the navigation buttons.  Don't use this
1844     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1845     *
1846     * THIS DOES NOT DISABLE THE BACK BUTTON
1847     */
1848    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1849
1850    /**
1851     * @hide
1852     *
1853     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1854     * out of the public fields to keep the undefined bits out of the developer's way.
1855     *
1856     * Flag to hide only the back button.  Don't use this
1857     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1858     */
1859    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1860
1861    /**
1862     * @hide
1863     *
1864     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1865     * out of the public fields to keep the undefined bits out of the developer's way.
1866     *
1867     * Flag to hide only the clock.  You might use this if your activity has
1868     * its own clock making the status bar's clock redundant.
1869     */
1870    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1871
1872    /**
1873     * @hide
1874     */
1875    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = STATUS_BAR_HIDDEN;
1876
1877    /**
1878     * Controls the over-scroll mode for this view.
1879     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1880     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1881     * and {@link #OVER_SCROLL_NEVER}.
1882     */
1883    private int mOverScrollMode;
1884
1885    /**
1886     * The parent this view is attached to.
1887     * {@hide}
1888     *
1889     * @see #getParent()
1890     */
1891    protected ViewParent mParent;
1892
1893    /**
1894     * {@hide}
1895     */
1896    AttachInfo mAttachInfo;
1897
1898    /**
1899     * {@hide}
1900     */
1901    @ViewDebug.ExportedProperty(flagMapping = {
1902        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1903                name = "FORCE_LAYOUT"),
1904        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1905                name = "LAYOUT_REQUIRED"),
1906        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1907            name = "DRAWING_CACHE_INVALID", outputIf = false),
1908        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1909        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1910        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1911        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1912    })
1913    int mPrivateFlags;
1914    int mPrivateFlags2;
1915
1916    /**
1917     * This view's request for the visibility of the status bar.
1918     * @hide
1919     */
1920    @ViewDebug.ExportedProperty()
1921    int mSystemUiVisibility;
1922
1923    /**
1924     * Count of how many windows this view has been attached to.
1925     */
1926    int mWindowAttachCount;
1927
1928    /**
1929     * The layout parameters associated with this view and used by the parent
1930     * {@link android.view.ViewGroup} to determine how this view should be
1931     * laid out.
1932     * {@hide}
1933     */
1934    protected ViewGroup.LayoutParams mLayoutParams;
1935
1936    /**
1937     * The view flags hold various views states.
1938     * {@hide}
1939     */
1940    @ViewDebug.ExportedProperty
1941    int mViewFlags;
1942
1943    /**
1944     * The transform matrix for the View. This transform is calculated internally
1945     * based on the rotation, scaleX, and scaleY properties. The identity matrix
1946     * is used by default. Do *not* use this variable directly; instead call
1947     * getMatrix(), which will automatically recalculate the matrix if necessary
1948     * to get the correct matrix based on the latest rotation and scale properties.
1949     */
1950    private final Matrix mMatrix = new Matrix();
1951
1952    /**
1953     * The transform matrix for the View. This transform is calculated internally
1954     * based on the rotation, scaleX, and scaleY properties. The identity matrix
1955     * is used by default. Do *not* use this variable directly; instead call
1956     * getInverseMatrix(), which will automatically recalculate the matrix if necessary
1957     * to get the correct matrix based on the latest rotation and scale properties.
1958     */
1959    private Matrix mInverseMatrix;
1960
1961    /**
1962     * An internal variable that tracks whether we need to recalculate the
1963     * transform matrix, based on whether the rotation or scaleX/Y properties
1964     * have changed since the matrix was last calculated.
1965     */
1966    boolean mMatrixDirty = false;
1967
1968    /**
1969     * An internal variable that tracks whether we need to recalculate the
1970     * transform matrix, based on whether the rotation or scaleX/Y properties
1971     * have changed since the matrix was last calculated.
1972     */
1973    private boolean mInverseMatrixDirty = true;
1974
1975    /**
1976     * A variable that tracks whether we need to recalculate the
1977     * transform matrix, based on whether the rotation or scaleX/Y properties
1978     * have changed since the matrix was last calculated. This variable
1979     * is only valid after a call to updateMatrix() or to a function that
1980     * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
1981     */
1982    private boolean mMatrixIsIdentity = true;
1983
1984    /**
1985     * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
1986     */
1987    private Camera mCamera = null;
1988
1989    /**
1990     * This matrix is used when computing the matrix for 3D rotations.
1991     */
1992    private Matrix matrix3D = null;
1993
1994    /**
1995     * These prev values are used to recalculate a centered pivot point when necessary. The
1996     * pivot point is only used in matrix operations (when rotation, scale, or translation are
1997     * set), so thes values are only used then as well.
1998     */
1999    private int mPrevWidth = -1;
2000    private int mPrevHeight = -1;
2001
2002    private boolean mLastIsOpaque;
2003
2004    /**
2005     * Convenience value to check for float values that are close enough to zero to be considered
2006     * zero.
2007     */
2008    private static final float NONZERO_EPSILON = .001f;
2009
2010    /**
2011     * The degrees rotation around the vertical axis through the pivot point.
2012     */
2013    @ViewDebug.ExportedProperty
2014    float mRotationY = 0f;
2015
2016    /**
2017     * The degrees rotation around the horizontal axis through the pivot point.
2018     */
2019    @ViewDebug.ExportedProperty
2020    float mRotationX = 0f;
2021
2022    /**
2023     * The degrees rotation around the pivot point.
2024     */
2025    @ViewDebug.ExportedProperty
2026    float mRotation = 0f;
2027
2028    /**
2029     * The amount of translation of the object away from its left property (post-layout).
2030     */
2031    @ViewDebug.ExportedProperty
2032    float mTranslationX = 0f;
2033
2034    /**
2035     * The amount of translation of the object away from its top property (post-layout).
2036     */
2037    @ViewDebug.ExportedProperty
2038    float mTranslationY = 0f;
2039
2040    /**
2041     * The amount of scale in the x direction around the pivot point. A
2042     * value of 1 means no scaling is applied.
2043     */
2044    @ViewDebug.ExportedProperty
2045    float mScaleX = 1f;
2046
2047    /**
2048     * The amount of scale in the y direction around the pivot point. A
2049     * value of 1 means no scaling is applied.
2050     */
2051    @ViewDebug.ExportedProperty
2052    float mScaleY = 1f;
2053
2054    /**
2055     * The amount of scale in the x direction around the pivot point. A
2056     * value of 1 means no scaling is applied.
2057     */
2058    @ViewDebug.ExportedProperty
2059    float mPivotX = 0f;
2060
2061    /**
2062     * The amount of scale in the y direction around the pivot point. A
2063     * value of 1 means no scaling is applied.
2064     */
2065    @ViewDebug.ExportedProperty
2066    float mPivotY = 0f;
2067
2068    /**
2069     * The opacity of the View. This is a value from 0 to 1, where 0 means
2070     * completely transparent and 1 means completely opaque.
2071     */
2072    @ViewDebug.ExportedProperty
2073    float mAlpha = 1f;
2074
2075    /**
2076     * The distance in pixels from the left edge of this view's parent
2077     * to the left edge of this view.
2078     * {@hide}
2079     */
2080    @ViewDebug.ExportedProperty(category = "layout")
2081    protected int mLeft;
2082    /**
2083     * The distance in pixels from the left edge of this view's parent
2084     * to the right edge of this view.
2085     * {@hide}
2086     */
2087    @ViewDebug.ExportedProperty(category = "layout")
2088    protected int mRight;
2089    /**
2090     * The distance in pixels from the top edge of this view's parent
2091     * to the top edge of this view.
2092     * {@hide}
2093     */
2094    @ViewDebug.ExportedProperty(category = "layout")
2095    protected int mTop;
2096    /**
2097     * The distance in pixels from the top edge of this view's parent
2098     * to the bottom edge of this view.
2099     * {@hide}
2100     */
2101    @ViewDebug.ExportedProperty(category = "layout")
2102    protected int mBottom;
2103
2104    /**
2105     * The offset, in pixels, by which the content of this view is scrolled
2106     * horizontally.
2107     * {@hide}
2108     */
2109    @ViewDebug.ExportedProperty(category = "scrolling")
2110    protected int mScrollX;
2111    /**
2112     * The offset, in pixels, by which the content of this view is scrolled
2113     * vertically.
2114     * {@hide}
2115     */
2116    @ViewDebug.ExportedProperty(category = "scrolling")
2117    protected int mScrollY;
2118
2119    /**
2120     * The left padding in pixels, that is the distance in pixels between the
2121     * left edge of this view and the left edge of its content.
2122     * {@hide}
2123     */
2124    @ViewDebug.ExportedProperty(category = "padding")
2125    protected int mPaddingLeft;
2126    /**
2127     * The right padding in pixels, that is the distance in pixels between the
2128     * right edge of this view and the right edge of its content.
2129     * {@hide}
2130     */
2131    @ViewDebug.ExportedProperty(category = "padding")
2132    protected int mPaddingRight;
2133    /**
2134     * The top padding in pixels, that is the distance in pixels between the
2135     * top edge of this view and the top edge of its content.
2136     * {@hide}
2137     */
2138    @ViewDebug.ExportedProperty(category = "padding")
2139    protected int mPaddingTop;
2140    /**
2141     * The bottom padding in pixels, that is the distance in pixels between the
2142     * bottom edge of this view and the bottom edge of its content.
2143     * {@hide}
2144     */
2145    @ViewDebug.ExportedProperty(category = "padding")
2146    protected int mPaddingBottom;
2147
2148    /**
2149     * Briefly describes the view and is primarily used for accessibility support.
2150     */
2151    private CharSequence mContentDescription;
2152
2153    /**
2154     * Cache the paddingRight set by the user to append to the scrollbar's size.
2155     */
2156    @ViewDebug.ExportedProperty(category = "padding")
2157    int mUserPaddingRight;
2158
2159    /**
2160     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2161     */
2162    @ViewDebug.ExportedProperty(category = "padding")
2163    int mUserPaddingBottom;
2164
2165    /**
2166     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2167     */
2168    @ViewDebug.ExportedProperty(category = "padding")
2169    int mUserPaddingLeft;
2170
2171    /**
2172     * @hide
2173     */
2174    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2175    /**
2176     * @hide
2177     */
2178    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2179
2180    private Resources mResources = null;
2181
2182    private Drawable mBGDrawable;
2183
2184    private int mBackgroundResource;
2185    private boolean mBackgroundSizeChanged;
2186
2187    /**
2188     * Listener used to dispatch focus change events.
2189     * This field should be made private, so it is hidden from the SDK.
2190     * {@hide}
2191     */
2192    protected OnFocusChangeListener mOnFocusChangeListener;
2193
2194    /**
2195     * Listeners for layout change events.
2196     */
2197    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2198
2199    /**
2200     * Listeners for attach events.
2201     */
2202    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2203
2204    /**
2205     * Listener used to dispatch click events.
2206     * This field should be made private, so it is hidden from the SDK.
2207     * {@hide}
2208     */
2209    protected OnClickListener mOnClickListener;
2210
2211    /**
2212     * Listener used to dispatch long click events.
2213     * This field should be made private, so it is hidden from the SDK.
2214     * {@hide}
2215     */
2216    protected OnLongClickListener mOnLongClickListener;
2217
2218    /**
2219     * Listener used to build the context menu.
2220     * This field should be made private, so it is hidden from the SDK.
2221     * {@hide}
2222     */
2223    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2224
2225    private OnKeyListener mOnKeyListener;
2226
2227    private OnTouchListener mOnTouchListener;
2228
2229    private OnGenericMotionListener mOnGenericMotionListener;
2230
2231    private OnDragListener mOnDragListener;
2232
2233    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2234
2235    /**
2236     * The application environment this view lives in.
2237     * This field should be made private, so it is hidden from the SDK.
2238     * {@hide}
2239     */
2240    protected Context mContext;
2241
2242    private ScrollabilityCache mScrollCache;
2243
2244    private int[] mDrawableState = null;
2245
2246    /**
2247     * Set to true when drawing cache is enabled and cannot be created.
2248     *
2249     * @hide
2250     */
2251    public boolean mCachingFailed;
2252
2253    private Bitmap mDrawingCache;
2254    private Bitmap mUnscaledDrawingCache;
2255    private DisplayList mDisplayList;
2256    private HardwareLayer mHardwareLayer;
2257
2258    /**
2259     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2260     * the user may specify which view to go to next.
2261     */
2262    private int mNextFocusLeftId = View.NO_ID;
2263
2264    /**
2265     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2266     * the user may specify which view to go to next.
2267     */
2268    private int mNextFocusRightId = View.NO_ID;
2269
2270    /**
2271     * When this view has focus and the next focus is {@link #FOCUS_UP},
2272     * the user may specify which view to go to next.
2273     */
2274    private int mNextFocusUpId = View.NO_ID;
2275
2276    /**
2277     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2278     * the user may specify which view to go to next.
2279     */
2280    private int mNextFocusDownId = View.NO_ID;
2281
2282    /**
2283     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2284     * the user may specify which view to go to next.
2285     */
2286    int mNextFocusForwardId = View.NO_ID;
2287
2288    private CheckForLongPress mPendingCheckForLongPress;
2289    private CheckForTap mPendingCheckForTap = null;
2290    private PerformClick mPerformClick;
2291
2292    private UnsetPressedState mUnsetPressedState;
2293
2294    /**
2295     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2296     * up event while a long press is invoked as soon as the long press duration is reached, so
2297     * a long press could be performed before the tap is checked, in which case the tap's action
2298     * should not be invoked.
2299     */
2300    private boolean mHasPerformedLongPress;
2301
2302    /**
2303     * The minimum height of the view. We'll try our best to have the height
2304     * of this view to at least this amount.
2305     */
2306    @ViewDebug.ExportedProperty(category = "measurement")
2307    private int mMinHeight;
2308
2309    /**
2310     * The minimum width of the view. We'll try our best to have the width
2311     * of this view to at least this amount.
2312     */
2313    @ViewDebug.ExportedProperty(category = "measurement")
2314    private int mMinWidth;
2315
2316    /**
2317     * The delegate to handle touch events that are physically in this view
2318     * but should be handled by another view.
2319     */
2320    private TouchDelegate mTouchDelegate = null;
2321
2322    /**
2323     * Solid color to use as a background when creating the drawing cache. Enables
2324     * the cache to use 16 bit bitmaps instead of 32 bit.
2325     */
2326    private int mDrawingCacheBackgroundColor = 0;
2327
2328    /**
2329     * Special tree observer used when mAttachInfo is null.
2330     */
2331    private ViewTreeObserver mFloatingTreeObserver;
2332
2333    /**
2334     * Cache the touch slop from the context that created the view.
2335     */
2336    private int mTouchSlop;
2337
2338    /**
2339     * Object that handles automatic animation of view properties.
2340     */
2341    private ViewPropertyAnimator mAnimator = null;
2342
2343    /**
2344     * Flag indicating that a drag can cross window boundaries.  When
2345     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2346     * with this flag set, all visible applications will be able to participate
2347     * in the drag operation and receive the dragged content.
2348     *
2349     * @hide
2350     */
2351    public static final int DRAG_FLAG_GLOBAL = 1;
2352
2353    /**
2354     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2355     */
2356    private float mVerticalScrollFactor;
2357
2358    /**
2359     * Position of the vertical scroll bar.
2360     */
2361    private int mVerticalScrollbarPosition;
2362
2363    /**
2364     * Position the scroll bar at the default position as determined by the system.
2365     */
2366    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2367
2368    /**
2369     * Position the scroll bar along the left edge.
2370     */
2371    public static final int SCROLLBAR_POSITION_LEFT = 1;
2372
2373    /**
2374     * Position the scroll bar along the right edge.
2375     */
2376    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2377
2378    /**
2379     * Indicates that the view does not have a layer.
2380     *
2381     * @see #getLayerType()
2382     * @see #setLayerType(int, android.graphics.Paint)
2383     * @see #LAYER_TYPE_SOFTWARE
2384     * @see #LAYER_TYPE_HARDWARE
2385     */
2386    public static final int LAYER_TYPE_NONE = 0;
2387
2388    /**
2389     * <p>Indicates that the view has a software layer. A software layer is backed
2390     * by a bitmap and causes the view to be rendered using Android's software
2391     * rendering pipeline, even if hardware acceleration is enabled.</p>
2392     *
2393     * <p>Software layers have various usages:</p>
2394     * <p>When the application is not using hardware acceleration, a software layer
2395     * is useful to apply a specific color filter and/or blending mode and/or
2396     * translucency to a view and all its children.</p>
2397     * <p>When the application is using hardware acceleration, a software layer
2398     * is useful to render drawing primitives not supported by the hardware
2399     * accelerated pipeline. It can also be used to cache a complex view tree
2400     * into a texture and reduce the complexity of drawing operations. For instance,
2401     * when animating a complex view tree with a translation, a software layer can
2402     * be used to render the view tree only once.</p>
2403     * <p>Software layers should be avoided when the affected view tree updates
2404     * often. Every update will require to re-render the software layer, which can
2405     * potentially be slow (particularly when hardware acceleration is turned on
2406     * since the layer will have to be uploaded into a hardware texture after every
2407     * update.)</p>
2408     *
2409     * @see #getLayerType()
2410     * @see #setLayerType(int, android.graphics.Paint)
2411     * @see #LAYER_TYPE_NONE
2412     * @see #LAYER_TYPE_HARDWARE
2413     */
2414    public static final int LAYER_TYPE_SOFTWARE = 1;
2415
2416    /**
2417     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2418     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2419     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2420     * rendering pipeline, but only if hardware acceleration is turned on for the
2421     * view hierarchy. When hardware acceleration is turned off, hardware layers
2422     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2423     *
2424     * <p>A hardware layer is useful to apply a specific color filter and/or
2425     * blending mode and/or translucency to a view and all its children.</p>
2426     * <p>A hardware layer can be used to cache a complex view tree into a
2427     * texture and reduce the complexity of drawing operations. For instance,
2428     * when animating a complex view tree with a translation, a hardware layer can
2429     * be used to render the view tree only once.</p>
2430     * <p>A hardware layer can also be used to increase the rendering quality when
2431     * rotation transformations are applied on a view. It can also be used to
2432     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2433     *
2434     * @see #getLayerType()
2435     * @see #setLayerType(int, android.graphics.Paint)
2436     * @see #LAYER_TYPE_NONE
2437     * @see #LAYER_TYPE_SOFTWARE
2438     */
2439    public static final int LAYER_TYPE_HARDWARE = 2;
2440
2441    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2442            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2443            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2444            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2445    })
2446    int mLayerType = LAYER_TYPE_NONE;
2447    Paint mLayerPaint;
2448    Rect mLocalDirtyRect;
2449
2450    /**
2451     * Consistency verifier for debugging purposes.
2452     * @hide
2453     */
2454    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2455            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2456                    new InputEventConsistencyVerifier(this, 0) : null;
2457
2458    /**
2459     * Simple constructor to use when creating a view from code.
2460     *
2461     * @param context The Context the view is running in, through which it can
2462     *        access the current theme, resources, etc.
2463     */
2464    public View(Context context) {
2465        mContext = context;
2466        mResources = context != null ? context.getResources() : null;
2467        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2468        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2469        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2470    }
2471
2472    /**
2473     * Constructor that is called when inflating a view from XML. This is called
2474     * when a view is being constructed from an XML file, supplying attributes
2475     * that were specified in the XML file. This version uses a default style of
2476     * 0, so the only attribute values applied are those in the Context's Theme
2477     * and the given AttributeSet.
2478     *
2479     * <p>
2480     * The method onFinishInflate() will be called after all children have been
2481     * added.
2482     *
2483     * @param context The Context the view is running in, through which it can
2484     *        access the current theme, resources, etc.
2485     * @param attrs The attributes of the XML tag that is inflating the view.
2486     * @see #View(Context, AttributeSet, int)
2487     */
2488    public View(Context context, AttributeSet attrs) {
2489        this(context, attrs, 0);
2490    }
2491
2492    /**
2493     * Perform inflation from XML and apply a class-specific base style. This
2494     * constructor of View allows subclasses to use their own base style when
2495     * they are inflating. For example, a Button class's constructor would call
2496     * this version of the super class constructor and supply
2497     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2498     * the theme's button style to modify all of the base view attributes (in
2499     * particular its background) as well as the Button class's attributes.
2500     *
2501     * @param context The Context the view is running in, through which it can
2502     *        access the current theme, resources, etc.
2503     * @param attrs The attributes of the XML tag that is inflating the view.
2504     * @param defStyle The default style to apply to this view. If 0, no style
2505     *        will be applied (beyond what is included in the theme). This may
2506     *        either be an attribute resource, whose value will be retrieved
2507     *        from the current theme, or an explicit style resource.
2508     * @see #View(Context, AttributeSet)
2509     */
2510    public View(Context context, AttributeSet attrs, int defStyle) {
2511        this(context);
2512
2513        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2514                defStyle, 0);
2515
2516        Drawable background = null;
2517
2518        int leftPadding = -1;
2519        int topPadding = -1;
2520        int rightPadding = -1;
2521        int bottomPadding = -1;
2522
2523        int padding = -1;
2524
2525        int viewFlagValues = 0;
2526        int viewFlagMasks = 0;
2527
2528        boolean setScrollContainer = false;
2529
2530        int x = 0;
2531        int y = 0;
2532
2533        float tx = 0;
2534        float ty = 0;
2535        float rotation = 0;
2536        float rotationX = 0;
2537        float rotationY = 0;
2538        float sx = 1f;
2539        float sy = 1f;
2540        boolean transformSet = false;
2541
2542        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2543
2544        int overScrollMode = mOverScrollMode;
2545        final int N = a.getIndexCount();
2546        for (int i = 0; i < N; i++) {
2547            int attr = a.getIndex(i);
2548            switch (attr) {
2549                case com.android.internal.R.styleable.View_background:
2550                    background = a.getDrawable(attr);
2551                    break;
2552                case com.android.internal.R.styleable.View_padding:
2553                    padding = a.getDimensionPixelSize(attr, -1);
2554                    break;
2555                 case com.android.internal.R.styleable.View_paddingLeft:
2556                    leftPadding = a.getDimensionPixelSize(attr, -1);
2557                    break;
2558                case com.android.internal.R.styleable.View_paddingTop:
2559                    topPadding = a.getDimensionPixelSize(attr, -1);
2560                    break;
2561                case com.android.internal.R.styleable.View_paddingRight:
2562                    rightPadding = a.getDimensionPixelSize(attr, -1);
2563                    break;
2564                case com.android.internal.R.styleable.View_paddingBottom:
2565                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2566                    break;
2567                case com.android.internal.R.styleable.View_scrollX:
2568                    x = a.getDimensionPixelOffset(attr, 0);
2569                    break;
2570                case com.android.internal.R.styleable.View_scrollY:
2571                    y = a.getDimensionPixelOffset(attr, 0);
2572                    break;
2573                case com.android.internal.R.styleable.View_alpha:
2574                    setAlpha(a.getFloat(attr, 1f));
2575                    break;
2576                case com.android.internal.R.styleable.View_transformPivotX:
2577                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2578                    break;
2579                case com.android.internal.R.styleable.View_transformPivotY:
2580                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2581                    break;
2582                case com.android.internal.R.styleable.View_translationX:
2583                    tx = a.getDimensionPixelOffset(attr, 0);
2584                    transformSet = true;
2585                    break;
2586                case com.android.internal.R.styleable.View_translationY:
2587                    ty = a.getDimensionPixelOffset(attr, 0);
2588                    transformSet = true;
2589                    break;
2590                case com.android.internal.R.styleable.View_rotation:
2591                    rotation = a.getFloat(attr, 0);
2592                    transformSet = true;
2593                    break;
2594                case com.android.internal.R.styleable.View_rotationX:
2595                    rotationX = a.getFloat(attr, 0);
2596                    transformSet = true;
2597                    break;
2598                case com.android.internal.R.styleable.View_rotationY:
2599                    rotationY = a.getFloat(attr, 0);
2600                    transformSet = true;
2601                    break;
2602                case com.android.internal.R.styleable.View_scaleX:
2603                    sx = a.getFloat(attr, 1f);
2604                    transformSet = true;
2605                    break;
2606                case com.android.internal.R.styleable.View_scaleY:
2607                    sy = a.getFloat(attr, 1f);
2608                    transformSet = true;
2609                    break;
2610                case com.android.internal.R.styleable.View_id:
2611                    mID = a.getResourceId(attr, NO_ID);
2612                    break;
2613                case com.android.internal.R.styleable.View_tag:
2614                    mTag = a.getText(attr);
2615                    break;
2616                case com.android.internal.R.styleable.View_fitsSystemWindows:
2617                    if (a.getBoolean(attr, false)) {
2618                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2619                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2620                    }
2621                    break;
2622                case com.android.internal.R.styleable.View_focusable:
2623                    if (a.getBoolean(attr, false)) {
2624                        viewFlagValues |= FOCUSABLE;
2625                        viewFlagMasks |= FOCUSABLE_MASK;
2626                    }
2627                    break;
2628                case com.android.internal.R.styleable.View_focusableInTouchMode:
2629                    if (a.getBoolean(attr, false)) {
2630                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2631                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2632                    }
2633                    break;
2634                case com.android.internal.R.styleable.View_clickable:
2635                    if (a.getBoolean(attr, false)) {
2636                        viewFlagValues |= CLICKABLE;
2637                        viewFlagMasks |= CLICKABLE;
2638                    }
2639                    break;
2640                case com.android.internal.R.styleable.View_longClickable:
2641                    if (a.getBoolean(attr, false)) {
2642                        viewFlagValues |= LONG_CLICKABLE;
2643                        viewFlagMasks |= LONG_CLICKABLE;
2644                    }
2645                    break;
2646                case com.android.internal.R.styleable.View_saveEnabled:
2647                    if (!a.getBoolean(attr, true)) {
2648                        viewFlagValues |= SAVE_DISABLED;
2649                        viewFlagMasks |= SAVE_DISABLED_MASK;
2650                    }
2651                    break;
2652                case com.android.internal.R.styleable.View_duplicateParentState:
2653                    if (a.getBoolean(attr, false)) {
2654                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2655                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2656                    }
2657                    break;
2658                case com.android.internal.R.styleable.View_visibility:
2659                    final int visibility = a.getInt(attr, 0);
2660                    if (visibility != 0) {
2661                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2662                        viewFlagMasks |= VISIBILITY_MASK;
2663                    }
2664                    break;
2665                case com.android.internal.R.styleable.View_layoutDirection:
2666                    // Clear any HORIZONTAL_DIRECTION flag already set
2667                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2668                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2669                    final int layoutDirection = a.getInt(attr, -1);
2670                    if (layoutDirection != -1) {
2671                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2672                    } else {
2673                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2674                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2675                    }
2676                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2677                    break;
2678                case com.android.internal.R.styleable.View_drawingCacheQuality:
2679                    final int cacheQuality = a.getInt(attr, 0);
2680                    if (cacheQuality != 0) {
2681                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2682                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2683                    }
2684                    break;
2685                case com.android.internal.R.styleable.View_contentDescription:
2686                    mContentDescription = a.getString(attr);
2687                    break;
2688                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2689                    if (!a.getBoolean(attr, true)) {
2690                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2691                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2692                    }
2693                    break;
2694                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2695                    if (!a.getBoolean(attr, true)) {
2696                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2697                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2698                    }
2699                    break;
2700                case R.styleable.View_scrollbars:
2701                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2702                    if (scrollbars != SCROLLBARS_NONE) {
2703                        viewFlagValues |= scrollbars;
2704                        viewFlagMasks |= SCROLLBARS_MASK;
2705                        initializeScrollbars(a);
2706                    }
2707                    break;
2708                case R.styleable.View_fadingEdge:
2709                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2710                    if (fadingEdge != FADING_EDGE_NONE) {
2711                        viewFlagValues |= fadingEdge;
2712                        viewFlagMasks |= FADING_EDGE_MASK;
2713                        initializeFadingEdge(a);
2714                    }
2715                    break;
2716                case R.styleable.View_scrollbarStyle:
2717                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2718                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2719                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2720                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2721                    }
2722                    break;
2723                case R.styleable.View_isScrollContainer:
2724                    setScrollContainer = true;
2725                    if (a.getBoolean(attr, false)) {
2726                        setScrollContainer(true);
2727                    }
2728                    break;
2729                case com.android.internal.R.styleable.View_keepScreenOn:
2730                    if (a.getBoolean(attr, false)) {
2731                        viewFlagValues |= KEEP_SCREEN_ON;
2732                        viewFlagMasks |= KEEP_SCREEN_ON;
2733                    }
2734                    break;
2735                case R.styleable.View_filterTouchesWhenObscured:
2736                    if (a.getBoolean(attr, false)) {
2737                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2738                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2739                    }
2740                    break;
2741                case R.styleable.View_nextFocusLeft:
2742                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2743                    break;
2744                case R.styleable.View_nextFocusRight:
2745                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2746                    break;
2747                case R.styleable.View_nextFocusUp:
2748                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2749                    break;
2750                case R.styleable.View_nextFocusDown:
2751                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2752                    break;
2753                case R.styleable.View_nextFocusForward:
2754                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2755                    break;
2756                case R.styleable.View_minWidth:
2757                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2758                    break;
2759                case R.styleable.View_minHeight:
2760                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2761                    break;
2762                case R.styleable.View_onClick:
2763                    if (context.isRestricted()) {
2764                        throw new IllegalStateException("The android:onClick attribute cannot "
2765                                + "be used within a restricted context");
2766                    }
2767
2768                    final String handlerName = a.getString(attr);
2769                    if (handlerName != null) {
2770                        setOnClickListener(new OnClickListener() {
2771                            private Method mHandler;
2772
2773                            public void onClick(View v) {
2774                                if (mHandler == null) {
2775                                    try {
2776                                        mHandler = getContext().getClass().getMethod(handlerName,
2777                                                View.class);
2778                                    } catch (NoSuchMethodException e) {
2779                                        int id = getId();
2780                                        String idText = id == NO_ID ? "" : " with id '"
2781                                                + getContext().getResources().getResourceEntryName(
2782                                                    id) + "'";
2783                                        throw new IllegalStateException("Could not find a method " +
2784                                                handlerName + "(View) in the activity "
2785                                                + getContext().getClass() + " for onClick handler"
2786                                                + " on view " + View.this.getClass() + idText, e);
2787                                    }
2788                                }
2789
2790                                try {
2791                                    mHandler.invoke(getContext(), View.this);
2792                                } catch (IllegalAccessException e) {
2793                                    throw new IllegalStateException("Could not execute non "
2794                                            + "public method of the activity", e);
2795                                } catch (InvocationTargetException e) {
2796                                    throw new IllegalStateException("Could not execute "
2797                                            + "method of the activity", e);
2798                                }
2799                            }
2800                        });
2801                    }
2802                    break;
2803                case R.styleable.View_overScrollMode:
2804                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
2805                    break;
2806                case R.styleable.View_verticalScrollbarPosition:
2807                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
2808                    break;
2809                case R.styleable.View_layerType:
2810                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
2811                    break;
2812            }
2813        }
2814
2815        setOverScrollMode(overScrollMode);
2816
2817        if (background != null) {
2818            setBackgroundDrawable(background);
2819        }
2820
2821        if (padding >= 0) {
2822            leftPadding = padding;
2823            topPadding = padding;
2824            rightPadding = padding;
2825            bottomPadding = padding;
2826        }
2827
2828        // If the user specified the padding (either with android:padding or
2829        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
2830        // use the default padding or the padding from the background drawable
2831        // (stored at this point in mPadding*)
2832        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
2833                topPadding >= 0 ? topPadding : mPaddingTop,
2834                rightPadding >= 0 ? rightPadding : mPaddingRight,
2835                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
2836
2837        if (viewFlagMasks != 0) {
2838            setFlags(viewFlagValues, viewFlagMasks);
2839        }
2840
2841        // Needs to be called after mViewFlags is set
2842        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2843            recomputePadding();
2844        }
2845
2846        if (x != 0 || y != 0) {
2847            scrollTo(x, y);
2848        }
2849
2850        if (transformSet) {
2851            setTranslationX(tx);
2852            setTranslationY(ty);
2853            setRotation(rotation);
2854            setRotationX(rotationX);
2855            setRotationY(rotationY);
2856            setScaleX(sx);
2857            setScaleY(sy);
2858        }
2859
2860        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
2861            setScrollContainer(true);
2862        }
2863
2864        computeOpaqueFlags();
2865
2866        a.recycle();
2867    }
2868
2869    /**
2870     * Non-public constructor for use in testing
2871     */
2872    View() {
2873    }
2874
2875    /**
2876     * <p>
2877     * Initializes the fading edges from a given set of styled attributes. This
2878     * method should be called by subclasses that need fading edges and when an
2879     * instance of these subclasses is created programmatically rather than
2880     * being inflated from XML. This method is automatically called when the XML
2881     * is inflated.
2882     * </p>
2883     *
2884     * @param a the styled attributes set to initialize the fading edges from
2885     */
2886    protected void initializeFadingEdge(TypedArray a) {
2887        initScrollCache();
2888
2889        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
2890                R.styleable.View_fadingEdgeLength,
2891                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
2892    }
2893
2894    /**
2895     * Returns the size of the vertical faded edges used to indicate that more
2896     * content in this view is visible.
2897     *
2898     * @return The size in pixels of the vertical faded edge or 0 if vertical
2899     *         faded edges are not enabled for this view.
2900     * @attr ref android.R.styleable#View_fadingEdgeLength
2901     */
2902    public int getVerticalFadingEdgeLength() {
2903        if (isVerticalFadingEdgeEnabled()) {
2904            ScrollabilityCache cache = mScrollCache;
2905            if (cache != null) {
2906                return cache.fadingEdgeLength;
2907            }
2908        }
2909        return 0;
2910    }
2911
2912    /**
2913     * Set the size of the faded edge used to indicate that more content in this
2914     * view is available.  Will not change whether the fading edge is enabled; use
2915     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
2916     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
2917     * for the vertical or horizontal fading edges.
2918     *
2919     * @param length The size in pixels of the faded edge used to indicate that more
2920     *        content in this view is visible.
2921     */
2922    public void setFadingEdgeLength(int length) {
2923        initScrollCache();
2924        mScrollCache.fadingEdgeLength = length;
2925    }
2926
2927    /**
2928     * Returns the size of the horizontal faded edges used to indicate that more
2929     * content in this view is visible.
2930     *
2931     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
2932     *         faded edges are not enabled for this view.
2933     * @attr ref android.R.styleable#View_fadingEdgeLength
2934     */
2935    public int getHorizontalFadingEdgeLength() {
2936        if (isHorizontalFadingEdgeEnabled()) {
2937            ScrollabilityCache cache = mScrollCache;
2938            if (cache != null) {
2939                return cache.fadingEdgeLength;
2940            }
2941        }
2942        return 0;
2943    }
2944
2945    /**
2946     * Returns the width of the vertical scrollbar.
2947     *
2948     * @return The width in pixels of the vertical scrollbar or 0 if there
2949     *         is no vertical scrollbar.
2950     */
2951    public int getVerticalScrollbarWidth() {
2952        ScrollabilityCache cache = mScrollCache;
2953        if (cache != null) {
2954            ScrollBarDrawable scrollBar = cache.scrollBar;
2955            if (scrollBar != null) {
2956                int size = scrollBar.getSize(true);
2957                if (size <= 0) {
2958                    size = cache.scrollBarSize;
2959                }
2960                return size;
2961            }
2962            return 0;
2963        }
2964        return 0;
2965    }
2966
2967    /**
2968     * Returns the height of the horizontal scrollbar.
2969     *
2970     * @return The height in pixels of the horizontal scrollbar or 0 if
2971     *         there is no horizontal scrollbar.
2972     */
2973    protected int getHorizontalScrollbarHeight() {
2974        ScrollabilityCache cache = mScrollCache;
2975        if (cache != null) {
2976            ScrollBarDrawable scrollBar = cache.scrollBar;
2977            if (scrollBar != null) {
2978                int size = scrollBar.getSize(false);
2979                if (size <= 0) {
2980                    size = cache.scrollBarSize;
2981                }
2982                return size;
2983            }
2984            return 0;
2985        }
2986        return 0;
2987    }
2988
2989    /**
2990     * <p>
2991     * Initializes the scrollbars from a given set of styled attributes. This
2992     * method should be called by subclasses that need scrollbars and when an
2993     * instance of these subclasses is created programmatically rather than
2994     * being inflated from XML. This method is automatically called when the XML
2995     * is inflated.
2996     * </p>
2997     *
2998     * @param a the styled attributes set to initialize the scrollbars from
2999     */
3000    protected void initializeScrollbars(TypedArray a) {
3001        initScrollCache();
3002
3003        final ScrollabilityCache scrollabilityCache = mScrollCache;
3004
3005        if (scrollabilityCache.scrollBar == null) {
3006            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3007        }
3008
3009        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3010
3011        if (!fadeScrollbars) {
3012            scrollabilityCache.state = ScrollabilityCache.ON;
3013        }
3014        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3015
3016
3017        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3018                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3019                        .getScrollBarFadeDuration());
3020        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3021                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3022                ViewConfiguration.getScrollDefaultDelay());
3023
3024
3025        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3026                com.android.internal.R.styleable.View_scrollbarSize,
3027                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3028
3029        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3030        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3031
3032        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3033        if (thumb != null) {
3034            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3035        }
3036
3037        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3038                false);
3039        if (alwaysDraw) {
3040            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3041        }
3042
3043        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3044        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3045
3046        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3047        if (thumb != null) {
3048            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3049        }
3050
3051        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3052                false);
3053        if (alwaysDraw) {
3054            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3055        }
3056
3057        // Re-apply user/background padding so that scrollbar(s) get added
3058        recomputePadding();
3059    }
3060
3061    /**
3062     * <p>
3063     * Initalizes the scrollability cache if necessary.
3064     * </p>
3065     */
3066    private void initScrollCache() {
3067        if (mScrollCache == null) {
3068            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3069        }
3070    }
3071
3072    /**
3073     * Set the position of the vertical scroll bar. Should be one of
3074     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3075     * {@link #SCROLLBAR_POSITION_RIGHT}.
3076     *
3077     * @param position Where the vertical scroll bar should be positioned.
3078     */
3079    public void setVerticalScrollbarPosition(int position) {
3080        if (mVerticalScrollbarPosition != position) {
3081            mVerticalScrollbarPosition = position;
3082            computeOpaqueFlags();
3083            recomputePadding();
3084        }
3085    }
3086
3087    /**
3088     * @return The position where the vertical scroll bar will show, if applicable.
3089     * @see #setVerticalScrollbarPosition(int)
3090     */
3091    public int getVerticalScrollbarPosition() {
3092        return mVerticalScrollbarPosition;
3093    }
3094
3095    /**
3096     * Register a callback to be invoked when focus of this view changed.
3097     *
3098     * @param l The callback that will run.
3099     */
3100    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3101        mOnFocusChangeListener = l;
3102    }
3103
3104    /**
3105     * Add a listener that will be called when the bounds of the view change due to
3106     * layout processing.
3107     *
3108     * @param listener The listener that will be called when layout bounds change.
3109     */
3110    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3111        if (mOnLayoutChangeListeners == null) {
3112            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3113        }
3114        mOnLayoutChangeListeners.add(listener);
3115    }
3116
3117    /**
3118     * Remove a listener for layout changes.
3119     *
3120     * @param listener The listener for layout bounds change.
3121     */
3122    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3123        if (mOnLayoutChangeListeners == null) {
3124            return;
3125        }
3126        mOnLayoutChangeListeners.remove(listener);
3127    }
3128
3129    /**
3130     * Add a listener for attach state changes.
3131     *
3132     * This listener will be called whenever this view is attached or detached
3133     * from a window. Remove the listener using
3134     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3135     *
3136     * @param listener Listener to attach
3137     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3138     */
3139    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3140        if (mOnAttachStateChangeListeners == null) {
3141            mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3142        }
3143        mOnAttachStateChangeListeners.add(listener);
3144    }
3145
3146    /**
3147     * Remove a listener for attach state changes. The listener will receive no further
3148     * notification of window attach/detach events.
3149     *
3150     * @param listener Listener to remove
3151     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3152     */
3153    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3154        if (mOnAttachStateChangeListeners == null) {
3155            return;
3156        }
3157        mOnAttachStateChangeListeners.remove(listener);
3158    }
3159
3160    /**
3161     * Returns the focus-change callback registered for this view.
3162     *
3163     * @return The callback, or null if one is not registered.
3164     */
3165    public OnFocusChangeListener getOnFocusChangeListener() {
3166        return mOnFocusChangeListener;
3167    }
3168
3169    /**
3170     * Register a callback to be invoked when this view is clicked. If this view is not
3171     * clickable, it becomes clickable.
3172     *
3173     * @param l The callback that will run
3174     *
3175     * @see #setClickable(boolean)
3176     */
3177    public void setOnClickListener(OnClickListener l) {
3178        if (!isClickable()) {
3179            setClickable(true);
3180        }
3181        mOnClickListener = l;
3182    }
3183
3184    /**
3185     * Register a callback to be invoked when this view is clicked and held. If this view is not
3186     * long clickable, it becomes long clickable.
3187     *
3188     * @param l The callback that will run
3189     *
3190     * @see #setLongClickable(boolean)
3191     */
3192    public void setOnLongClickListener(OnLongClickListener l) {
3193        if (!isLongClickable()) {
3194            setLongClickable(true);
3195        }
3196        mOnLongClickListener = l;
3197    }
3198
3199    /**
3200     * Register a callback to be invoked when the context menu for this view is
3201     * being built. If this view is not long clickable, it becomes long clickable.
3202     *
3203     * @param l The callback that will run
3204     *
3205     */
3206    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3207        if (!isLongClickable()) {
3208            setLongClickable(true);
3209        }
3210        mOnCreateContextMenuListener = l;
3211    }
3212
3213    /**
3214     * Call this view's OnClickListener, if it is defined.
3215     *
3216     * @return True there was an assigned OnClickListener that was called, false
3217     *         otherwise is returned.
3218     */
3219    public boolean performClick() {
3220        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3221
3222        if (mOnClickListener != null) {
3223            playSoundEffect(SoundEffectConstants.CLICK);
3224            mOnClickListener.onClick(this);
3225            return true;
3226        }
3227
3228        return false;
3229    }
3230
3231    /**
3232     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3233     * OnLongClickListener did not consume the event.
3234     *
3235     * @return True if one of the above receivers consumed the event, false otherwise.
3236     */
3237    public boolean performLongClick() {
3238        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3239
3240        boolean handled = false;
3241        if (mOnLongClickListener != null) {
3242            handled = mOnLongClickListener.onLongClick(View.this);
3243        }
3244        if (!handled) {
3245            handled = showContextMenu();
3246        }
3247        if (handled) {
3248            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3249        }
3250        return handled;
3251    }
3252
3253    /**
3254     * Performs button-related actions during a touch down event.
3255     *
3256     * @param event The event.
3257     * @return True if the down was consumed.
3258     *
3259     * @hide
3260     */
3261    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3262        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3263            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3264                return true;
3265            }
3266        }
3267        return false;
3268    }
3269
3270    /**
3271     * Bring up the context menu for this view.
3272     *
3273     * @return Whether a context menu was displayed.
3274     */
3275    public boolean showContextMenu() {
3276        return getParent().showContextMenuForChild(this);
3277    }
3278
3279    /**
3280     * Bring up the context menu for this view, referring to the item under the specified point.
3281     *
3282     * @param x The referenced x coordinate.
3283     * @param y The referenced y coordinate.
3284     * @param metaState The keyboard modifiers that were pressed.
3285     * @return Whether a context menu was displayed.
3286     *
3287     * @hide
3288     */
3289    public boolean showContextMenu(float x, float y, int metaState) {
3290        return showContextMenu();
3291    }
3292
3293    /**
3294     * Start an action mode.
3295     *
3296     * @param callback Callback that will control the lifecycle of the action mode
3297     * @return The new action mode if it is started, null otherwise
3298     *
3299     * @see ActionMode
3300     */
3301    public ActionMode startActionMode(ActionMode.Callback callback) {
3302        return getParent().startActionModeForChild(this, callback);
3303    }
3304
3305    /**
3306     * Register a callback to be invoked when a key is pressed in this view.
3307     * @param l the key listener to attach to this view
3308     */
3309    public void setOnKeyListener(OnKeyListener l) {
3310        mOnKeyListener = l;
3311    }
3312
3313    /**
3314     * Register a callback to be invoked when a touch event is sent to this view.
3315     * @param l the touch listener to attach to this view
3316     */
3317    public void setOnTouchListener(OnTouchListener l) {
3318        mOnTouchListener = l;
3319    }
3320
3321    /**
3322     * Register a callback to be invoked when a generic motion event is sent to this view.
3323     * @param l the generic motion listener to attach to this view
3324     */
3325    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3326        mOnGenericMotionListener = l;
3327    }
3328
3329    /**
3330     * Register a drag event listener callback object for this View. The parameter is
3331     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3332     * View, the system calls the
3333     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3334     * @param l An implementation of {@link android.view.View.OnDragListener}.
3335     */
3336    public void setOnDragListener(OnDragListener l) {
3337        mOnDragListener = l;
3338    }
3339
3340    /**
3341     * Give this view focus. This will cause
3342     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3343     *
3344     * Note: this does not check whether this {@link View} should get focus, it just
3345     * gives it focus no matter what.  It should only be called internally by framework
3346     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3347     *
3348     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3349     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3350     *        focus moved when requestFocus() is called. It may not always
3351     *        apply, in which case use the default View.FOCUS_DOWN.
3352     * @param previouslyFocusedRect The rectangle of the view that had focus
3353     *        prior in this View's coordinate system.
3354     */
3355    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3356        if (DBG) {
3357            System.out.println(this + " requestFocus()");
3358        }
3359
3360        if ((mPrivateFlags & FOCUSED) == 0) {
3361            mPrivateFlags |= FOCUSED;
3362
3363            if (mParent != null) {
3364                mParent.requestChildFocus(this, this);
3365            }
3366
3367            onFocusChanged(true, direction, previouslyFocusedRect);
3368            refreshDrawableState();
3369        }
3370    }
3371
3372    /**
3373     * Request that a rectangle of this view be visible on the screen,
3374     * scrolling if necessary just enough.
3375     *
3376     * <p>A View should call this if it maintains some notion of which part
3377     * of its content is interesting.  For example, a text editing view
3378     * should call this when its cursor moves.
3379     *
3380     * @param rectangle The rectangle.
3381     * @return Whether any parent scrolled.
3382     */
3383    public boolean requestRectangleOnScreen(Rect rectangle) {
3384        return requestRectangleOnScreen(rectangle, false);
3385    }
3386
3387    /**
3388     * Request that a rectangle of this view be visible on the screen,
3389     * scrolling if necessary just enough.
3390     *
3391     * <p>A View should call this if it maintains some notion of which part
3392     * of its content is interesting.  For example, a text editing view
3393     * should call this when its cursor moves.
3394     *
3395     * <p>When <code>immediate</code> is set to true, scrolling will not be
3396     * animated.
3397     *
3398     * @param rectangle The rectangle.
3399     * @param immediate True to forbid animated scrolling, false otherwise
3400     * @return Whether any parent scrolled.
3401     */
3402    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3403        View child = this;
3404        ViewParent parent = mParent;
3405        boolean scrolled = false;
3406        while (parent != null) {
3407            scrolled |= parent.requestChildRectangleOnScreen(child,
3408                    rectangle, immediate);
3409
3410            // offset rect so next call has the rectangle in the
3411            // coordinate system of its direct child.
3412            rectangle.offset(child.getLeft(), child.getTop());
3413            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3414
3415            if (!(parent instanceof View)) {
3416                break;
3417            }
3418
3419            child = (View) parent;
3420            parent = child.getParent();
3421        }
3422        return scrolled;
3423    }
3424
3425    /**
3426     * Called when this view wants to give up focus. This will cause
3427     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3428     */
3429    public void clearFocus() {
3430        if (DBG) {
3431            System.out.println(this + " clearFocus()");
3432        }
3433
3434        if ((mPrivateFlags & FOCUSED) != 0) {
3435            mPrivateFlags &= ~FOCUSED;
3436
3437            if (mParent != null) {
3438                mParent.clearChildFocus(this);
3439            }
3440
3441            onFocusChanged(false, 0, null);
3442            refreshDrawableState();
3443        }
3444    }
3445
3446    /**
3447     * Called to clear the focus of a view that is about to be removed.
3448     * Doesn't call clearChildFocus, which prevents this view from taking
3449     * focus again before it has been removed from the parent
3450     */
3451    void clearFocusForRemoval() {
3452        if ((mPrivateFlags & FOCUSED) != 0) {
3453            mPrivateFlags &= ~FOCUSED;
3454
3455            onFocusChanged(false, 0, null);
3456            refreshDrawableState();
3457        }
3458    }
3459
3460    /**
3461     * Called internally by the view system when a new view is getting focus.
3462     * This is what clears the old focus.
3463     */
3464    void unFocus() {
3465        if (DBG) {
3466            System.out.println(this + " unFocus()");
3467        }
3468
3469        if ((mPrivateFlags & FOCUSED) != 0) {
3470            mPrivateFlags &= ~FOCUSED;
3471
3472            onFocusChanged(false, 0, null);
3473            refreshDrawableState();
3474        }
3475    }
3476
3477    /**
3478     * Returns true if this view has focus iteself, or is the ancestor of the
3479     * view that has focus.
3480     *
3481     * @return True if this view has or contains focus, false otherwise.
3482     */
3483    @ViewDebug.ExportedProperty(category = "focus")
3484    public boolean hasFocus() {
3485        return (mPrivateFlags & FOCUSED) != 0;
3486    }
3487
3488    /**
3489     * Returns true if this view is focusable or if it contains a reachable View
3490     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3491     * is a View whose parents do not block descendants focus.
3492     *
3493     * Only {@link #VISIBLE} views are considered focusable.
3494     *
3495     * @return True if the view is focusable or if the view contains a focusable
3496     *         View, false otherwise.
3497     *
3498     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3499     */
3500    public boolean hasFocusable() {
3501        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3502    }
3503
3504    /**
3505     * Called by the view system when the focus state of this view changes.
3506     * When the focus change event is caused by directional navigation, direction
3507     * and previouslyFocusedRect provide insight into where the focus is coming from.
3508     * When overriding, be sure to call up through to the super class so that
3509     * the standard focus handling will occur.
3510     *
3511     * @param gainFocus True if the View has focus; false otherwise.
3512     * @param direction The direction focus has moved when requestFocus()
3513     *                  is called to give this view focus. Values are
3514     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3515     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3516     *                  It may not always apply, in which case use the default.
3517     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3518     *        system, of the previously focused view.  If applicable, this will be
3519     *        passed in as finer grained information about where the focus is coming
3520     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3521     */
3522    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3523        if (gainFocus) {
3524            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3525        }
3526
3527        InputMethodManager imm = InputMethodManager.peekInstance();
3528        if (!gainFocus) {
3529            if (isPressed()) {
3530                setPressed(false);
3531            }
3532            if (imm != null && mAttachInfo != null
3533                    && mAttachInfo.mHasWindowFocus) {
3534                imm.focusOut(this);
3535            }
3536            onFocusLost();
3537        } else if (imm != null && mAttachInfo != null
3538                && mAttachInfo.mHasWindowFocus) {
3539            imm.focusIn(this);
3540        }
3541
3542        invalidate(true);
3543        if (mOnFocusChangeListener != null) {
3544            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3545        }
3546
3547        if (mAttachInfo != null) {
3548            mAttachInfo.mKeyDispatchState.reset(this);
3549        }
3550    }
3551
3552    /**
3553     * Sends an accessibility event of the given type. If accessiiblity is
3554     * not enabled this method has no effect. The default implementation calls
3555     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3556     * to populate information about the event source (this View), then calls
3557     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3558     * populate the text content of the event source including its descendants,
3559     * and last calls
3560     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3561     * on its parent to resuest sending of the event to interested parties.
3562     *
3563     * @param eventType The type of the event to send.
3564     *
3565     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3566     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3567     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3568     */
3569    public void sendAccessibilityEvent(int eventType) {
3570        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3571            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3572        }
3573    }
3574
3575    /**
3576     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3577     * takes as an argument an empty {@link AccessibilityEvent} and does not
3578     * perfrom a check whether accessibility is enabled.
3579     *
3580     * @param event The event to send.
3581     *
3582     * @see #sendAccessibilityEvent(int)
3583     */
3584    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3585        if (!isShown()) {
3586            return;
3587        }
3588        onInitializeAccessibilityEvent(event);
3589        dispatchPopulateAccessibilityEvent(event);
3590        // In the beginning we called #isShown(), so we know that getParent() is not null.
3591        getParent().requestSendAccessibilityEvent(this, event);
3592    }
3593
3594    /**
3595     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3596     * to its children for adding their text content to the event. Note that the
3597     * event text is populated in a separate dispatch path since we add to the
3598     * event not only the text of the source but also the text of all its descendants.
3599     * </p>
3600     * A typical implementation will call
3601     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3602     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3603     * on each child. Override this method if custom population of the event text
3604     * content is required.
3605     *
3606     * @param event The event.
3607     *
3608     * @return True if the event population was completed.
3609     */
3610    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3611        onPopulateAccessibilityEvent(event);
3612        return false;
3613    }
3614
3615    /**
3616     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3617     * giving a chance to this View to populate the accessibility event with its
3618     * text content. While the implementation is free to modify other event
3619     * attributes this should be performed in
3620     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
3621     * <p>
3622     * Example: Adding formatted date string to an accessibility event in addition
3623     *          to the text added by the super implementation.
3624     * </p><p><pre><code>
3625     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3626     *     super.onPopulateAccessibilityEvent(event);
3627     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
3628     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
3629     *         mCurrentDate.getTimeInMillis(), flags);
3630     *     event.getText().add(selectedDateUtterance);
3631     * }
3632     * </code></pre></p>
3633     *
3634     * @param event The accessibility event which to populate.
3635     *
3636     * @see #sendAccessibilityEvent(int)
3637     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3638     */
3639    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3640
3641    }
3642
3643    /**
3644     * Initializes an {@link AccessibilityEvent} with information about the
3645     * the type of the event and this View which is the event source. In other
3646     * words, the source of an accessibility event is the view whose state
3647     * change triggered firing the event.
3648     * <p>
3649     * Example: Setting the password property of an event in addition
3650     *          to properties set by the super implementation.
3651     * </p><p><pre><code>
3652     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3653     *    super.onInitializeAccessibilityEvent(event);
3654     *    event.setPassword(true);
3655     * }
3656     * </code></pre></p>
3657     * @param event The event to initialeze.
3658     *
3659     * @see #sendAccessibilityEvent(int)
3660     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3661     */
3662    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3663        event.setSource(this);
3664        event.setClassName(getClass().getName());
3665        event.setPackageName(getContext().getPackageName());
3666        event.setEnabled(isEnabled());
3667        event.setContentDescription(mContentDescription);
3668
3669        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
3670            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3671            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
3672            event.setItemCount(focusablesTempList.size());
3673            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3674            focusablesTempList.clear();
3675        }
3676    }
3677
3678    /**
3679     * Returns an {@link AccessibilityNodeInfo} representing this view from the
3680     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
3681     * This method is responsible for obtaining an accessibility node info from a
3682     * pool of reusable instances and calling
3683     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
3684     * initialize the former.
3685     * <p>
3686     * Note: The client is responsible for recycling the obtained instance by calling
3687     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
3688     * </p>
3689     * @return A populated {@link AccessibilityNodeInfo}.
3690     *
3691     * @see AccessibilityNodeInfo
3692     */
3693    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
3694        AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
3695        onInitializeAccessibilityNodeInfo(info);
3696        return info;
3697    }
3698
3699    /**
3700     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
3701     * The base implementation sets:
3702     * <ul>
3703     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
3704     *   <li>{@link AccessibilityNodeInfo#setBounds(Rect)},</li>
3705     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
3706     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
3707     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
3708     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
3709     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
3710     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
3711     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
3712     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
3713     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
3714     * </ul>
3715     * <p>
3716     * Subclasses should override this method, call the super implementation,
3717     * and set additional attributes.
3718     * </p>
3719     * @param info The instance to initialize.
3720     */
3721    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
3722        Rect bounds = mAttachInfo.mTmpInvalRect;
3723        getDrawingRect(bounds);
3724        info.setBounds(bounds);
3725
3726        ViewParent parent = getParent();
3727        if (parent instanceof View) {
3728            View parentView = (View) parent;
3729            info.setParent(parentView);
3730        }
3731
3732        info.setPackageName(mContext.getPackageName());
3733        info.setClassName(getClass().getName());
3734        info.setContentDescription(getContentDescription());
3735
3736        info.setEnabled(isEnabled());
3737        info.setClickable(isClickable());
3738        info.setFocusable(isFocusable());
3739        info.setFocused(isFocused());
3740        info.setSelected(isSelected());
3741        info.setLongClickable(isLongClickable());
3742
3743        // TODO: These make sense only if we are in an AdapterView but all
3744        // views can be selected. Maybe from accessiiblity perspective
3745        // we should report as selectable view in an AdapterView.
3746        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
3747        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
3748
3749        if (isFocusable()) {
3750            if (isFocused()) {
3751                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
3752            } else {
3753                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
3754            }
3755        }
3756    }
3757
3758    /**
3759     * Gets the unique identifier of this view on the screen for accessibility purposes.
3760     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
3761     *
3762     * @return The view accessibility id.
3763     *
3764     * @hide
3765     */
3766    public int getAccessibilityViewId() {
3767        if (mAccessibilityViewId == NO_ID) {
3768            mAccessibilityViewId = sNextAccessibilityViewId++;
3769        }
3770        return mAccessibilityViewId;
3771    }
3772
3773    /**
3774     * Gets the unique identifier of the window in which this View reseides.
3775     *
3776     * @return The window accessibility id.
3777     *
3778     * @hide
3779     */
3780    public int getAccessibilityWindowId() {
3781        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
3782    }
3783
3784    /**
3785     * Gets the {@link View} description. It briefly describes the view and is
3786     * primarily used for accessibility support. Set this property to enable
3787     * better accessibility support for your application. This is especially
3788     * true for views that do not have textual representation (For example,
3789     * ImageButton).
3790     *
3791     * @return The content descriptiopn.
3792     *
3793     * @attr ref android.R.styleable#View_contentDescription
3794     */
3795    public CharSequence getContentDescription() {
3796        return mContentDescription;
3797    }
3798
3799    /**
3800     * Sets the {@link View} description. It briefly describes the view and is
3801     * primarily used for accessibility support. Set this property to enable
3802     * better accessibility support for your application. This is especially
3803     * true for views that do not have textual representation (For example,
3804     * ImageButton).
3805     *
3806     * @param contentDescription The content description.
3807     *
3808     * @attr ref android.R.styleable#View_contentDescription
3809     */
3810    public void setContentDescription(CharSequence contentDescription) {
3811        mContentDescription = contentDescription;
3812    }
3813
3814    /**
3815     * Invoked whenever this view loses focus, either by losing window focus or by losing
3816     * focus within its window. This method can be used to clear any state tied to the
3817     * focus. For instance, if a button is held pressed with the trackball and the window
3818     * loses focus, this method can be used to cancel the press.
3819     *
3820     * Subclasses of View overriding this method should always call super.onFocusLost().
3821     *
3822     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
3823     * @see #onWindowFocusChanged(boolean)
3824     *
3825     * @hide pending API council approval
3826     */
3827    protected void onFocusLost() {
3828        resetPressedState();
3829    }
3830
3831    private void resetPressedState() {
3832        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
3833            return;
3834        }
3835
3836        if (isPressed()) {
3837            setPressed(false);
3838
3839            if (!mHasPerformedLongPress) {
3840                removeLongPressCallback();
3841            }
3842        }
3843    }
3844
3845    /**
3846     * Returns true if this view has focus
3847     *
3848     * @return True if this view has focus, false otherwise.
3849     */
3850    @ViewDebug.ExportedProperty(category = "focus")
3851    public boolean isFocused() {
3852        return (mPrivateFlags & FOCUSED) != 0;
3853    }
3854
3855    /**
3856     * Find the view in the hierarchy rooted at this view that currently has
3857     * focus.
3858     *
3859     * @return The view that currently has focus, or null if no focused view can
3860     *         be found.
3861     */
3862    public View findFocus() {
3863        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
3864    }
3865
3866    /**
3867     * Change whether this view is one of the set of scrollable containers in
3868     * its window.  This will be used to determine whether the window can
3869     * resize or must pan when a soft input area is open -- scrollable
3870     * containers allow the window to use resize mode since the container
3871     * will appropriately shrink.
3872     */
3873    public void setScrollContainer(boolean isScrollContainer) {
3874        if (isScrollContainer) {
3875            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
3876                mAttachInfo.mScrollContainers.add(this);
3877                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
3878            }
3879            mPrivateFlags |= SCROLL_CONTAINER;
3880        } else {
3881            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
3882                mAttachInfo.mScrollContainers.remove(this);
3883            }
3884            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
3885        }
3886    }
3887
3888    /**
3889     * Returns the quality of the drawing cache.
3890     *
3891     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3892     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3893     *
3894     * @see #setDrawingCacheQuality(int)
3895     * @see #setDrawingCacheEnabled(boolean)
3896     * @see #isDrawingCacheEnabled()
3897     *
3898     * @attr ref android.R.styleable#View_drawingCacheQuality
3899     */
3900    public int getDrawingCacheQuality() {
3901        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
3902    }
3903
3904    /**
3905     * Set the drawing cache quality of this view. This value is used only when the
3906     * drawing cache is enabled
3907     *
3908     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
3909     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
3910     *
3911     * @see #getDrawingCacheQuality()
3912     * @see #setDrawingCacheEnabled(boolean)
3913     * @see #isDrawingCacheEnabled()
3914     *
3915     * @attr ref android.R.styleable#View_drawingCacheQuality
3916     */
3917    public void setDrawingCacheQuality(int quality) {
3918        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
3919    }
3920
3921    /**
3922     * Returns whether the screen should remain on, corresponding to the current
3923     * value of {@link #KEEP_SCREEN_ON}.
3924     *
3925     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
3926     *
3927     * @see #setKeepScreenOn(boolean)
3928     *
3929     * @attr ref android.R.styleable#View_keepScreenOn
3930     */
3931    public boolean getKeepScreenOn() {
3932        return (mViewFlags & KEEP_SCREEN_ON) != 0;
3933    }
3934
3935    /**
3936     * Controls whether the screen should remain on, modifying the
3937     * value of {@link #KEEP_SCREEN_ON}.
3938     *
3939     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
3940     *
3941     * @see #getKeepScreenOn()
3942     *
3943     * @attr ref android.R.styleable#View_keepScreenOn
3944     */
3945    public void setKeepScreenOn(boolean keepScreenOn) {
3946        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
3947    }
3948
3949    /**
3950     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3951     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3952     *
3953     * @attr ref android.R.styleable#View_nextFocusLeft
3954     */
3955    public int getNextFocusLeftId() {
3956        return mNextFocusLeftId;
3957    }
3958
3959    /**
3960     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
3961     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
3962     * decide automatically.
3963     *
3964     * @attr ref android.R.styleable#View_nextFocusLeft
3965     */
3966    public void setNextFocusLeftId(int nextFocusLeftId) {
3967        mNextFocusLeftId = nextFocusLeftId;
3968    }
3969
3970    /**
3971     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3972     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3973     *
3974     * @attr ref android.R.styleable#View_nextFocusRight
3975     */
3976    public int getNextFocusRightId() {
3977        return mNextFocusRightId;
3978    }
3979
3980    /**
3981     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
3982     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
3983     * decide automatically.
3984     *
3985     * @attr ref android.R.styleable#View_nextFocusRight
3986     */
3987    public void setNextFocusRightId(int nextFocusRightId) {
3988        mNextFocusRightId = nextFocusRightId;
3989    }
3990
3991    /**
3992     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
3993     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
3994     *
3995     * @attr ref android.R.styleable#View_nextFocusUp
3996     */
3997    public int getNextFocusUpId() {
3998        return mNextFocusUpId;
3999    }
4000
4001    /**
4002     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4003     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4004     * decide automatically.
4005     *
4006     * @attr ref android.R.styleable#View_nextFocusUp
4007     */
4008    public void setNextFocusUpId(int nextFocusUpId) {
4009        mNextFocusUpId = nextFocusUpId;
4010    }
4011
4012    /**
4013     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4014     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4015     *
4016     * @attr ref android.R.styleable#View_nextFocusDown
4017     */
4018    public int getNextFocusDownId() {
4019        return mNextFocusDownId;
4020    }
4021
4022    /**
4023     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4024     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4025     * decide automatically.
4026     *
4027     * @attr ref android.R.styleable#View_nextFocusDown
4028     */
4029    public void setNextFocusDownId(int nextFocusDownId) {
4030        mNextFocusDownId = nextFocusDownId;
4031    }
4032
4033    /**
4034     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4035     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4036     *
4037     * @attr ref android.R.styleable#View_nextFocusForward
4038     */
4039    public int getNextFocusForwardId() {
4040        return mNextFocusForwardId;
4041    }
4042
4043    /**
4044     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4045     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4046     * decide automatically.
4047     *
4048     * @attr ref android.R.styleable#View_nextFocusForward
4049     */
4050    public void setNextFocusForwardId(int nextFocusForwardId) {
4051        mNextFocusForwardId = nextFocusForwardId;
4052    }
4053
4054    /**
4055     * Returns the visibility of this view and all of its ancestors
4056     *
4057     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4058     */
4059    public boolean isShown() {
4060        View current = this;
4061        //noinspection ConstantConditions
4062        do {
4063            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4064                return false;
4065            }
4066            ViewParent parent = current.mParent;
4067            if (parent == null) {
4068                return false; // We are not attached to the view root
4069            }
4070            if (!(parent instanceof View)) {
4071                return true;
4072            }
4073            current = (View) parent;
4074        } while (current != null);
4075
4076        return false;
4077    }
4078
4079    /**
4080     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4081     * is set
4082     *
4083     * @param insets Insets for system windows
4084     *
4085     * @return True if this view applied the insets, false otherwise
4086     */
4087    protected boolean fitSystemWindows(Rect insets) {
4088        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4089            mPaddingLeft = insets.left;
4090            mPaddingTop = insets.top;
4091            mPaddingRight = insets.right;
4092            mPaddingBottom = insets.bottom;
4093            requestLayout();
4094            return true;
4095        }
4096        return false;
4097    }
4098
4099    /**
4100     * Returns the visibility status for this view.
4101     *
4102     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4103     * @attr ref android.R.styleable#View_visibility
4104     */
4105    @ViewDebug.ExportedProperty(mapping = {
4106        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4107        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4108        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4109    })
4110    public int getVisibility() {
4111        return mViewFlags & VISIBILITY_MASK;
4112    }
4113
4114    /**
4115     * Set the enabled state of this view.
4116     *
4117     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4118     * @attr ref android.R.styleable#View_visibility
4119     */
4120    @RemotableViewMethod
4121    public void setVisibility(int visibility) {
4122        setFlags(visibility, VISIBILITY_MASK);
4123        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4124    }
4125
4126    /**
4127     * Returns the enabled status for this view. The interpretation of the
4128     * enabled state varies by subclass.
4129     *
4130     * @return True if this view is enabled, false otherwise.
4131     */
4132    @ViewDebug.ExportedProperty
4133    public boolean isEnabled() {
4134        return (mViewFlags & ENABLED_MASK) == ENABLED;
4135    }
4136
4137    /**
4138     * Set the enabled state of this view. The interpretation of the enabled
4139     * state varies by subclass.
4140     *
4141     * @param enabled True if this view is enabled, false otherwise.
4142     */
4143    @RemotableViewMethod
4144    public void setEnabled(boolean enabled) {
4145        if (enabled == isEnabled()) return;
4146
4147        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4148
4149        /*
4150         * The View most likely has to change its appearance, so refresh
4151         * the drawable state.
4152         */
4153        refreshDrawableState();
4154
4155        // Invalidate too, since the default behavior for views is to be
4156        // be drawn at 50% alpha rather than to change the drawable.
4157        invalidate(true);
4158    }
4159
4160    /**
4161     * Set whether this view can receive the focus.
4162     *
4163     * Setting this to false will also ensure that this view is not focusable
4164     * in touch mode.
4165     *
4166     * @param focusable If true, this view can receive the focus.
4167     *
4168     * @see #setFocusableInTouchMode(boolean)
4169     * @attr ref android.R.styleable#View_focusable
4170     */
4171    public void setFocusable(boolean focusable) {
4172        if (!focusable) {
4173            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4174        }
4175        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4176    }
4177
4178    /**
4179     * Set whether this view can receive focus while in touch mode.
4180     *
4181     * Setting this to true will also ensure that this view is focusable.
4182     *
4183     * @param focusableInTouchMode If true, this view can receive the focus while
4184     *   in touch mode.
4185     *
4186     * @see #setFocusable(boolean)
4187     * @attr ref android.R.styleable#View_focusableInTouchMode
4188     */
4189    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4190        // Focusable in touch mode should always be set before the focusable flag
4191        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4192        // which, in touch mode, will not successfully request focus on this view
4193        // because the focusable in touch mode flag is not set
4194        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4195        if (focusableInTouchMode) {
4196            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4197        }
4198    }
4199
4200    /**
4201     * Set whether this view should have sound effects enabled for events such as
4202     * clicking and touching.
4203     *
4204     * <p>You may wish to disable sound effects for a view if you already play sounds,
4205     * for instance, a dial key that plays dtmf tones.
4206     *
4207     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4208     * @see #isSoundEffectsEnabled()
4209     * @see #playSoundEffect(int)
4210     * @attr ref android.R.styleable#View_soundEffectsEnabled
4211     */
4212    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4213        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4214    }
4215
4216    /**
4217     * @return whether this view should have sound effects enabled for events such as
4218     *     clicking and touching.
4219     *
4220     * @see #setSoundEffectsEnabled(boolean)
4221     * @see #playSoundEffect(int)
4222     * @attr ref android.R.styleable#View_soundEffectsEnabled
4223     */
4224    @ViewDebug.ExportedProperty
4225    public boolean isSoundEffectsEnabled() {
4226        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4227    }
4228
4229    /**
4230     * Set whether this view should have haptic feedback for events such as
4231     * long presses.
4232     *
4233     * <p>You may wish to disable haptic feedback if your view already controls
4234     * its own haptic feedback.
4235     *
4236     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4237     * @see #isHapticFeedbackEnabled()
4238     * @see #performHapticFeedback(int)
4239     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4240     */
4241    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4242        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4243    }
4244
4245    /**
4246     * @return whether this view should have haptic feedback enabled for events
4247     * long presses.
4248     *
4249     * @see #setHapticFeedbackEnabled(boolean)
4250     * @see #performHapticFeedback(int)
4251     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4252     */
4253    @ViewDebug.ExportedProperty
4254    public boolean isHapticFeedbackEnabled() {
4255        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4256    }
4257
4258    /**
4259     * Returns the layout direction for this view.
4260     *
4261     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4262     *   {@link #LAYOUT_DIRECTION_RTL},
4263     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4264     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4265     * @attr ref android.R.styleable#View_layoutDirection
4266     * @hide
4267     */
4268    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4269        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4270        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4271        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4272        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4273    })
4274    public int getLayoutDirection() {
4275        return mViewFlags & LAYOUT_DIRECTION_MASK;
4276    }
4277
4278    /**
4279     * Set the layout direction for this view.
4280     *
4281     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4282     *   {@link #LAYOUT_DIRECTION_RTL},
4283     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4284     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4285     * @attr ref android.R.styleable#View_layoutDirection
4286     * @hide
4287     */
4288    @RemotableViewMethod
4289    public void setLayoutDirection(int layoutDirection) {
4290        setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4291    }
4292
4293    /**
4294     * If this view doesn't do any drawing on its own, set this flag to
4295     * allow further optimizations. By default, this flag is not set on
4296     * View, but could be set on some View subclasses such as ViewGroup.
4297     *
4298     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4299     * you should clear this flag.
4300     *
4301     * @param willNotDraw whether or not this View draw on its own
4302     */
4303    public void setWillNotDraw(boolean willNotDraw) {
4304        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4305    }
4306
4307    /**
4308     * Returns whether or not this View draws on its own.
4309     *
4310     * @return true if this view has nothing to draw, false otherwise
4311     */
4312    @ViewDebug.ExportedProperty(category = "drawing")
4313    public boolean willNotDraw() {
4314        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4315    }
4316
4317    /**
4318     * When a View's drawing cache is enabled, drawing is redirected to an
4319     * offscreen bitmap. Some views, like an ImageView, must be able to
4320     * bypass this mechanism if they already draw a single bitmap, to avoid
4321     * unnecessary usage of the memory.
4322     *
4323     * @param willNotCacheDrawing true if this view does not cache its
4324     *        drawing, false otherwise
4325     */
4326    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4327        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4328    }
4329
4330    /**
4331     * Returns whether or not this View can cache its drawing or not.
4332     *
4333     * @return true if this view does not cache its drawing, false otherwise
4334     */
4335    @ViewDebug.ExportedProperty(category = "drawing")
4336    public boolean willNotCacheDrawing() {
4337        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4338    }
4339
4340    /**
4341     * Indicates whether this view reacts to click events or not.
4342     *
4343     * @return true if the view is clickable, false otherwise
4344     *
4345     * @see #setClickable(boolean)
4346     * @attr ref android.R.styleable#View_clickable
4347     */
4348    @ViewDebug.ExportedProperty
4349    public boolean isClickable() {
4350        return (mViewFlags & CLICKABLE) == CLICKABLE;
4351    }
4352
4353    /**
4354     * Enables or disables click events for this view. When a view
4355     * is clickable it will change its state to "pressed" on every click.
4356     * Subclasses should set the view clickable to visually react to
4357     * user's clicks.
4358     *
4359     * @param clickable true to make the view clickable, false otherwise
4360     *
4361     * @see #isClickable()
4362     * @attr ref android.R.styleable#View_clickable
4363     */
4364    public void setClickable(boolean clickable) {
4365        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4366    }
4367
4368    /**
4369     * Indicates whether this view reacts to long click events or not.
4370     *
4371     * @return true if the view is long clickable, false otherwise
4372     *
4373     * @see #setLongClickable(boolean)
4374     * @attr ref android.R.styleable#View_longClickable
4375     */
4376    public boolean isLongClickable() {
4377        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4378    }
4379
4380    /**
4381     * Enables or disables long click events for this view. When a view is long
4382     * clickable it reacts to the user holding down the button for a longer
4383     * duration than a tap. This event can either launch the listener or a
4384     * context menu.
4385     *
4386     * @param longClickable true to make the view long clickable, false otherwise
4387     * @see #isLongClickable()
4388     * @attr ref android.R.styleable#View_longClickable
4389     */
4390    public void setLongClickable(boolean longClickable) {
4391        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4392    }
4393
4394    /**
4395     * Sets the pressed state for this view.
4396     *
4397     * @see #isClickable()
4398     * @see #setClickable(boolean)
4399     *
4400     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4401     *        the View's internal state from a previously set "pressed" state.
4402     */
4403    public void setPressed(boolean pressed) {
4404        if (pressed) {
4405            mPrivateFlags |= PRESSED;
4406        } else {
4407            mPrivateFlags &= ~PRESSED;
4408        }
4409        refreshDrawableState();
4410        dispatchSetPressed(pressed);
4411    }
4412
4413    /**
4414     * Dispatch setPressed to all of this View's children.
4415     *
4416     * @see #setPressed(boolean)
4417     *
4418     * @param pressed The new pressed state
4419     */
4420    protected void dispatchSetPressed(boolean pressed) {
4421    }
4422
4423    /**
4424     * Indicates whether the view is currently in pressed state. Unless
4425     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4426     * the pressed state.
4427     *
4428     * @see #setPressed(boolean)
4429     * @see #isClickable()
4430     * @see #setClickable(boolean)
4431     *
4432     * @return true if the view is currently pressed, false otherwise
4433     */
4434    public boolean isPressed() {
4435        return (mPrivateFlags & PRESSED) == PRESSED;
4436    }
4437
4438    /**
4439     * Indicates whether this view will save its state (that is,
4440     * whether its {@link #onSaveInstanceState} method will be called).
4441     *
4442     * @return Returns true if the view state saving is enabled, else false.
4443     *
4444     * @see #setSaveEnabled(boolean)
4445     * @attr ref android.R.styleable#View_saveEnabled
4446     */
4447    public boolean isSaveEnabled() {
4448        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4449    }
4450
4451    /**
4452     * Controls whether the saving of this view's state is
4453     * enabled (that is, whether its {@link #onSaveInstanceState} method
4454     * will be called).  Note that even if freezing is enabled, the
4455     * view still must have an id assigned to it (via {@link #setId(int)})
4456     * for its state to be saved.  This flag can only disable the
4457     * saving of this view; any child views may still have their state saved.
4458     *
4459     * @param enabled Set to false to <em>disable</em> state saving, or true
4460     * (the default) to allow it.
4461     *
4462     * @see #isSaveEnabled()
4463     * @see #setId(int)
4464     * @see #onSaveInstanceState()
4465     * @attr ref android.R.styleable#View_saveEnabled
4466     */
4467    public void setSaveEnabled(boolean enabled) {
4468        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4469    }
4470
4471    /**
4472     * Gets whether the framework should discard touches when the view's
4473     * window is obscured by another visible window.
4474     * Refer to the {@link View} security documentation for more details.
4475     *
4476     * @return True if touch filtering is enabled.
4477     *
4478     * @see #setFilterTouchesWhenObscured(boolean)
4479     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4480     */
4481    @ViewDebug.ExportedProperty
4482    public boolean getFilterTouchesWhenObscured() {
4483        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4484    }
4485
4486    /**
4487     * Sets whether the framework should discard touches when the view's
4488     * window is obscured by another visible window.
4489     * Refer to the {@link View} security documentation for more details.
4490     *
4491     * @param enabled True if touch filtering should be enabled.
4492     *
4493     * @see #getFilterTouchesWhenObscured
4494     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4495     */
4496    public void setFilterTouchesWhenObscured(boolean enabled) {
4497        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4498                FILTER_TOUCHES_WHEN_OBSCURED);
4499    }
4500
4501    /**
4502     * Indicates whether the entire hierarchy under this view will save its
4503     * state when a state saving traversal occurs from its parent.  The default
4504     * is true; if false, these views will not be saved unless
4505     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4506     *
4507     * @return Returns true if the view state saving from parent is enabled, else false.
4508     *
4509     * @see #setSaveFromParentEnabled(boolean)
4510     */
4511    public boolean isSaveFromParentEnabled() {
4512        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4513    }
4514
4515    /**
4516     * Controls whether the entire hierarchy under this view will save its
4517     * state when a state saving traversal occurs from its parent.  The default
4518     * is true; if false, these views will not be saved unless
4519     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4520     *
4521     * @param enabled Set to false to <em>disable</em> state saving, or true
4522     * (the default) to allow it.
4523     *
4524     * @see #isSaveFromParentEnabled()
4525     * @see #setId(int)
4526     * @see #onSaveInstanceState()
4527     */
4528    public void setSaveFromParentEnabled(boolean enabled) {
4529        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4530    }
4531
4532
4533    /**
4534     * Returns whether this View is able to take focus.
4535     *
4536     * @return True if this view can take focus, or false otherwise.
4537     * @attr ref android.R.styleable#View_focusable
4538     */
4539    @ViewDebug.ExportedProperty(category = "focus")
4540    public final boolean isFocusable() {
4541        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4542    }
4543
4544    /**
4545     * When a view is focusable, it may not want to take focus when in touch mode.
4546     * For example, a button would like focus when the user is navigating via a D-pad
4547     * so that the user can click on it, but once the user starts touching the screen,
4548     * the button shouldn't take focus
4549     * @return Whether the view is focusable in touch mode.
4550     * @attr ref android.R.styleable#View_focusableInTouchMode
4551     */
4552    @ViewDebug.ExportedProperty
4553    public final boolean isFocusableInTouchMode() {
4554        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4555    }
4556
4557    /**
4558     * Find the nearest view in the specified direction that can take focus.
4559     * This does not actually give focus to that view.
4560     *
4561     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4562     *
4563     * @return The nearest focusable in the specified direction, or null if none
4564     *         can be found.
4565     */
4566    public View focusSearch(int direction) {
4567        if (mParent != null) {
4568            return mParent.focusSearch(this, direction);
4569        } else {
4570            return null;
4571        }
4572    }
4573
4574    /**
4575     * This method is the last chance for the focused view and its ancestors to
4576     * respond to an arrow key. This is called when the focused view did not
4577     * consume the key internally, nor could the view system find a new view in
4578     * the requested direction to give focus to.
4579     *
4580     * @param focused The currently focused view.
4581     * @param direction The direction focus wants to move. One of FOCUS_UP,
4582     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4583     * @return True if the this view consumed this unhandled move.
4584     */
4585    public boolean dispatchUnhandledMove(View focused, int direction) {
4586        return false;
4587    }
4588
4589    /**
4590     * If a user manually specified the next view id for a particular direction,
4591     * use the root to look up the view.
4592     * @param root The root view of the hierarchy containing this view.
4593     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4594     * or FOCUS_BACKWARD.
4595     * @return The user specified next view, or null if there is none.
4596     */
4597    View findUserSetNextFocus(View root, int direction) {
4598        switch (direction) {
4599            case FOCUS_LEFT:
4600                if (mNextFocusLeftId == View.NO_ID) return null;
4601                return findViewShouldExist(root, mNextFocusLeftId);
4602            case FOCUS_RIGHT:
4603                if (mNextFocusRightId == View.NO_ID) return null;
4604                return findViewShouldExist(root, mNextFocusRightId);
4605            case FOCUS_UP:
4606                if (mNextFocusUpId == View.NO_ID) return null;
4607                return findViewShouldExist(root, mNextFocusUpId);
4608            case FOCUS_DOWN:
4609                if (mNextFocusDownId == View.NO_ID) return null;
4610                return findViewShouldExist(root, mNextFocusDownId);
4611            case FOCUS_FORWARD:
4612                if (mNextFocusForwardId == View.NO_ID) return null;
4613                return findViewShouldExist(root, mNextFocusForwardId);
4614            case FOCUS_BACKWARD: {
4615                final int id = mID;
4616                return root.findViewByPredicate(new Predicate<View>() {
4617                    @Override
4618                    public boolean apply(View t) {
4619                        return t.mNextFocusForwardId == id;
4620                    }
4621                });
4622            }
4623        }
4624        return null;
4625    }
4626
4627    private static View findViewShouldExist(View root, int childViewId) {
4628        View result = root.findViewById(childViewId);
4629        if (result == null) {
4630            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4631                    + "by user for id " + childViewId);
4632        }
4633        return result;
4634    }
4635
4636    /**
4637     * Find and return all focusable views that are descendants of this view,
4638     * possibly including this view if it is focusable itself.
4639     *
4640     * @param direction The direction of the focus
4641     * @return A list of focusable views
4642     */
4643    public ArrayList<View> getFocusables(int direction) {
4644        ArrayList<View> result = new ArrayList<View>(24);
4645        addFocusables(result, direction);
4646        return result;
4647    }
4648
4649    /**
4650     * Add any focusable views that are descendants of this view (possibly
4651     * including this view if it is focusable itself) to views.  If we are in touch mode,
4652     * only add views that are also focusable in touch mode.
4653     *
4654     * @param views Focusable views found so far
4655     * @param direction The direction of the focus
4656     */
4657    public void addFocusables(ArrayList<View> views, int direction) {
4658        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4659    }
4660
4661    /**
4662     * Adds any focusable views that are descendants of this view (possibly
4663     * including this view if it is focusable itself) to views. This method
4664     * adds all focusable views regardless if we are in touch mode or
4665     * only views focusable in touch mode if we are in touch mode depending on
4666     * the focusable mode paramater.
4667     *
4668     * @param views Focusable views found so far or null if all we are interested is
4669     *        the number of focusables.
4670     * @param direction The direction of the focus.
4671     * @param focusableMode The type of focusables to be added.
4672     *
4673     * @see #FOCUSABLES_ALL
4674     * @see #FOCUSABLES_TOUCH_MODE
4675     */
4676    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4677        if (!isFocusable()) {
4678            return;
4679        }
4680
4681        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4682                isInTouchMode() && !isFocusableInTouchMode()) {
4683            return;
4684        }
4685
4686        if (views != null) {
4687            views.add(this);
4688        }
4689    }
4690
4691    /**
4692     * Finds the Views that contain given text. The containment is case insensitive.
4693     * As View's text is considered any text content that View renders.
4694     *
4695     * @param outViews The output list of matching Views.
4696     * @param text The text to match against.
4697     */
4698    public void findViewsWithText(ArrayList<View> outViews, CharSequence text) {
4699    }
4700
4701    /**
4702     * Find and return all touchable views that are descendants of this view,
4703     * possibly including this view if it is touchable itself.
4704     *
4705     * @return A list of touchable views
4706     */
4707    public ArrayList<View> getTouchables() {
4708        ArrayList<View> result = new ArrayList<View>();
4709        addTouchables(result);
4710        return result;
4711    }
4712
4713    /**
4714     * Add any touchable views that are descendants of this view (possibly
4715     * including this view if it is touchable itself) to views.
4716     *
4717     * @param views Touchable views found so far
4718     */
4719    public void addTouchables(ArrayList<View> views) {
4720        final int viewFlags = mViewFlags;
4721
4722        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
4723                && (viewFlags & ENABLED_MASK) == ENABLED) {
4724            views.add(this);
4725        }
4726    }
4727
4728    /**
4729     * Call this to try to give focus to a specific view or to one of its
4730     * descendants.
4731     *
4732     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
4733     * false), or if it is focusable and it is not focusable in touch mode
4734     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
4735     *
4736     * See also {@link #focusSearch(int)}, which is what you call to say that you
4737     * have focus, and you want your parent to look for the next one.
4738     *
4739     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
4740     * {@link #FOCUS_DOWN} and <code>null</code>.
4741     *
4742     * @return Whether this view or one of its descendants actually took focus.
4743     */
4744    public final boolean requestFocus() {
4745        return requestFocus(View.FOCUS_DOWN);
4746    }
4747
4748
4749    /**
4750     * Call this to try to give focus to a specific view or to one of its
4751     * descendants and give it a hint about what direction focus is heading.
4752     *
4753     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
4754     * false), or if it is focusable and it is not focusable in touch mode
4755     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
4756     *
4757     * See also {@link #focusSearch(int)}, which is what you call to say that you
4758     * have focus, and you want your parent to look for the next one.
4759     *
4760     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
4761     * <code>null</code> set for the previously focused rectangle.
4762     *
4763     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4764     * @return Whether this view or one of its descendants actually took focus.
4765     */
4766    public final boolean requestFocus(int direction) {
4767        return requestFocus(direction, null);
4768    }
4769
4770    /**
4771     * Call this to try to give focus to a specific view or to one of its descendants
4772     * and give it hints about the direction and a specific rectangle that the focus
4773     * is coming from.  The rectangle can help give larger views a finer grained hint
4774     * about where focus is coming from, and therefore, where to show selection, or
4775     * forward focus change internally.
4776     *
4777     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
4778     * false), or if it is focusable and it is not focusable in touch mode
4779     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
4780     *
4781     * A View will not take focus if it is not visible.
4782     *
4783     * A View will not take focus if one of its parents has
4784     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
4785     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
4786     *
4787     * See also {@link #focusSearch(int)}, which is what you call to say that you
4788     * have focus, and you want your parent to look for the next one.
4789     *
4790     * You may wish to override this method if your custom {@link View} has an internal
4791     * {@link View} that it wishes to forward the request to.
4792     *
4793     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4794     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
4795     *        to give a finer grained hint about where focus is coming from.  May be null
4796     *        if there is no hint.
4797     * @return Whether this view or one of its descendants actually took focus.
4798     */
4799    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4800        // need to be focusable
4801        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
4802                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4803            return false;
4804        }
4805
4806        // need to be focusable in touch mode if in touch mode
4807        if (isInTouchMode() &&
4808            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
4809               return false;
4810        }
4811
4812        // need to not have any parents blocking us
4813        if (hasAncestorThatBlocksDescendantFocus()) {
4814            return false;
4815        }
4816
4817        handleFocusGainInternal(direction, previouslyFocusedRect);
4818        return true;
4819    }
4820
4821    /** Gets the ViewAncestor, or null if not attached. */
4822    /*package*/ ViewAncestor getViewAncestor() {
4823        View root = getRootView();
4824        return root != null ? (ViewAncestor)root.getParent() : null;
4825    }
4826
4827    /**
4828     * Call this to try to give focus to a specific view or to one of its descendants. This is a
4829     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
4830     * touch mode to request focus when they are touched.
4831     *
4832     * @return Whether this view or one of its descendants actually took focus.
4833     *
4834     * @see #isInTouchMode()
4835     *
4836     */
4837    public final boolean requestFocusFromTouch() {
4838        // Leave touch mode if we need to
4839        if (isInTouchMode()) {
4840            ViewAncestor viewRoot = getViewAncestor();
4841            if (viewRoot != null) {
4842                viewRoot.ensureTouchMode(false);
4843            }
4844        }
4845        return requestFocus(View.FOCUS_DOWN);
4846    }
4847
4848    /**
4849     * @return Whether any ancestor of this view blocks descendant focus.
4850     */
4851    private boolean hasAncestorThatBlocksDescendantFocus() {
4852        ViewParent ancestor = mParent;
4853        while (ancestor instanceof ViewGroup) {
4854            final ViewGroup vgAncestor = (ViewGroup) ancestor;
4855            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
4856                return true;
4857            } else {
4858                ancestor = vgAncestor.getParent();
4859            }
4860        }
4861        return false;
4862    }
4863
4864    /**
4865     * @hide
4866     */
4867    public void dispatchStartTemporaryDetach() {
4868        onStartTemporaryDetach();
4869    }
4870
4871    /**
4872     * This is called when a container is going to temporarily detach a child, with
4873     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
4874     * It will either be followed by {@link #onFinishTemporaryDetach()} or
4875     * {@link #onDetachedFromWindow()} when the container is done.
4876     */
4877    public void onStartTemporaryDetach() {
4878        removeUnsetPressCallback();
4879        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
4880    }
4881
4882    /**
4883     * @hide
4884     */
4885    public void dispatchFinishTemporaryDetach() {
4886        onFinishTemporaryDetach();
4887    }
4888
4889    /**
4890     * Called after {@link #onStartTemporaryDetach} when the container is done
4891     * changing the view.
4892     */
4893    public void onFinishTemporaryDetach() {
4894    }
4895
4896    /**
4897     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
4898     * for this view's window.  Returns null if the view is not currently attached
4899     * to the window.  Normally you will not need to use this directly, but
4900     * just use the standard high-level event callbacks like
4901     * {@link #onKeyDown(int, KeyEvent)}.
4902     */
4903    public KeyEvent.DispatcherState getKeyDispatcherState() {
4904        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
4905    }
4906
4907    /**
4908     * Dispatch a key event before it is processed by any input method
4909     * associated with the view hierarchy.  This can be used to intercept
4910     * key events in special situations before the IME consumes them; a
4911     * typical example would be handling the BACK key to update the application's
4912     * UI instead of allowing the IME to see it and close itself.
4913     *
4914     * @param event The key event to be dispatched.
4915     * @return True if the event was handled, false otherwise.
4916     */
4917    public boolean dispatchKeyEventPreIme(KeyEvent event) {
4918        return onKeyPreIme(event.getKeyCode(), event);
4919    }
4920
4921    /**
4922     * Dispatch a key event to the next view on the focus path. This path runs
4923     * from the top of the view tree down to the currently focused view. If this
4924     * view has focus, it will dispatch to itself. Otherwise it will dispatch
4925     * the next node down the focus path. This method also fires any key
4926     * listeners.
4927     *
4928     * @param event The key event to be dispatched.
4929     * @return True if the event was handled, false otherwise.
4930     */
4931    public boolean dispatchKeyEvent(KeyEvent event) {
4932        if (mInputEventConsistencyVerifier != null) {
4933            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
4934        }
4935
4936        // Give any attached key listener a first crack at the event.
4937        //noinspection SimplifiableIfStatement
4938        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
4939                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
4940            return true;
4941        }
4942
4943        if (event.dispatch(this, mAttachInfo != null
4944                ? mAttachInfo.mKeyDispatchState : null, this)) {
4945            return true;
4946        }
4947
4948        if (mInputEventConsistencyVerifier != null) {
4949            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
4950        }
4951        return false;
4952    }
4953
4954    /**
4955     * Dispatches a key shortcut event.
4956     *
4957     * @param event The key event to be dispatched.
4958     * @return True if the event was handled by the view, false otherwise.
4959     */
4960    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
4961        return onKeyShortcut(event.getKeyCode(), event);
4962    }
4963
4964    /**
4965     * Pass the touch screen motion event down to the target view, or this
4966     * view if it is the target.
4967     *
4968     * @param event The motion event to be dispatched.
4969     * @return True if the event was handled by the view, false otherwise.
4970     */
4971    public boolean dispatchTouchEvent(MotionEvent event) {
4972        if (mInputEventConsistencyVerifier != null) {
4973            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
4974        }
4975
4976        if (onFilterTouchEventForSecurity(event)) {
4977            //noinspection SimplifiableIfStatement
4978            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
4979                    mOnTouchListener.onTouch(this, event)) {
4980                return true;
4981            }
4982
4983            if (onTouchEvent(event)) {
4984                return true;
4985            }
4986        }
4987
4988        if (mInputEventConsistencyVerifier != null) {
4989            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
4990        }
4991        return false;
4992    }
4993
4994    /**
4995     * Filter the touch event to apply security policies.
4996     *
4997     * @param event The motion event to be filtered.
4998     * @return True if the event should be dispatched, false if the event should be dropped.
4999     *
5000     * @see #getFilterTouchesWhenObscured
5001     */
5002    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5003        //noinspection RedundantIfStatement
5004        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5005                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5006            // Window is obscured, drop this touch.
5007            return false;
5008        }
5009        return true;
5010    }
5011
5012    /**
5013     * Pass a trackball motion event down to the focused view.
5014     *
5015     * @param event The motion event to be dispatched.
5016     * @return True if the event was handled by the view, false otherwise.
5017     */
5018    public boolean dispatchTrackballEvent(MotionEvent event) {
5019        if (mInputEventConsistencyVerifier != null) {
5020            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5021        }
5022
5023        //Log.i("view", "view=" + this + ", " + event.toString());
5024        if (onTrackballEvent(event)) {
5025            return true;
5026        }
5027
5028        if (mInputEventConsistencyVerifier != null) {
5029            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5030        }
5031        return false;
5032    }
5033
5034    /**
5035     * Dispatch a generic motion event.
5036     * <p>
5037     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5038     * are delivered to the view under the pointer.  All other generic motion events are
5039     * delivered to the focused view.  Hover events are handled specially and are delivered
5040     * to {@link #onHoverEvent(MotionEvent)}.
5041     * </p>
5042     *
5043     * @param event The motion event to be dispatched.
5044     * @return True if the event was handled by the view, false otherwise.
5045     */
5046    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5047        if (mInputEventConsistencyVerifier != null) {
5048            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5049        }
5050
5051        final int source = event.getSource();
5052        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5053            final int action = event.getAction();
5054            if (action == MotionEvent.ACTION_HOVER_ENTER
5055                    || action == MotionEvent.ACTION_HOVER_MOVE
5056                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5057                if (dispatchHoverEvent(event)) {
5058                    return true;
5059                }
5060            } else if (dispatchGenericPointerEvent(event)) {
5061                return true;
5062            }
5063        } else if (dispatchGenericFocusedEvent(event)) {
5064            return true;
5065        }
5066
5067        //noinspection SimplifiableIfStatement
5068        if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5069                && mOnGenericMotionListener.onGenericMotion(this, event)) {
5070            return true;
5071        }
5072
5073        if (onGenericMotionEvent(event)) {
5074            return true;
5075        }
5076
5077        if (mInputEventConsistencyVerifier != null) {
5078            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5079        }
5080        return false;
5081    }
5082
5083    /**
5084     * Dispatch a hover event.
5085     * <p>
5086     * Do not call this method directly.
5087     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5088     * </p>
5089     *
5090     * @param event The motion event to be dispatched.
5091     * @return True if the event was handled by the view, false otherwise.
5092     * @hide
5093     */
5094    protected boolean dispatchHoverEvent(MotionEvent event) {
5095        return onHoverEvent(event);
5096    }
5097
5098    /**
5099     * Dispatch a generic motion event to the view under the first pointer.
5100     * <p>
5101     * Do not call this method directly.
5102     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5103     * </p>
5104     *
5105     * @param event The motion event to be dispatched.
5106     * @return True if the event was handled by the view, false otherwise.
5107     * @hide
5108     */
5109    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5110        return false;
5111    }
5112
5113    /**
5114     * Dispatch a generic motion event to the currently focused view.
5115     * <p>
5116     * Do not call this method directly.
5117     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5118     * </p>
5119     *
5120     * @param event The motion event to be dispatched.
5121     * @return True if the event was handled by the view, false otherwise.
5122     * @hide
5123     */
5124    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5125        return false;
5126    }
5127
5128    /**
5129     * Dispatch a pointer event.
5130     * <p>
5131     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5132     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5133     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5134     * and should not be expected to handle other pointing device features.
5135     * </p>
5136     *
5137     * @param event The motion event to be dispatched.
5138     * @return True if the event was handled by the view, false otherwise.
5139     * @hide
5140     */
5141    public final boolean dispatchPointerEvent(MotionEvent event) {
5142        if (event.isTouchEvent()) {
5143            return dispatchTouchEvent(event);
5144        } else {
5145            return dispatchGenericMotionEvent(event);
5146        }
5147    }
5148
5149    /**
5150     * Called when the window containing this view gains or loses window focus.
5151     * ViewGroups should override to route to their children.
5152     *
5153     * @param hasFocus True if the window containing this view now has focus,
5154     *        false otherwise.
5155     */
5156    public void dispatchWindowFocusChanged(boolean hasFocus) {
5157        onWindowFocusChanged(hasFocus);
5158    }
5159
5160    /**
5161     * Called when the window containing this view gains or loses focus.  Note
5162     * that this is separate from view focus: to receive key events, both
5163     * your view and its window must have focus.  If a window is displayed
5164     * on top of yours that takes input focus, then your own window will lose
5165     * focus but the view focus will remain unchanged.
5166     *
5167     * @param hasWindowFocus True if the window containing this view now has
5168     *        focus, false otherwise.
5169     */
5170    public void onWindowFocusChanged(boolean hasWindowFocus) {
5171        InputMethodManager imm = InputMethodManager.peekInstance();
5172        if (!hasWindowFocus) {
5173            if (isPressed()) {
5174                setPressed(false);
5175            }
5176            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5177                imm.focusOut(this);
5178            }
5179            removeLongPressCallback();
5180            removeTapCallback();
5181            onFocusLost();
5182        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5183            imm.focusIn(this);
5184        }
5185        refreshDrawableState();
5186    }
5187
5188    /**
5189     * Returns true if this view is in a window that currently has window focus.
5190     * Note that this is not the same as the view itself having focus.
5191     *
5192     * @return True if this view is in a window that currently has window focus.
5193     */
5194    public boolean hasWindowFocus() {
5195        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5196    }
5197
5198    /**
5199     * Dispatch a view visibility change down the view hierarchy.
5200     * ViewGroups should override to route to their children.
5201     * @param changedView The view whose visibility changed. Could be 'this' or
5202     * an ancestor view.
5203     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5204     * {@link #INVISIBLE} or {@link #GONE}.
5205     */
5206    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5207        onVisibilityChanged(changedView, visibility);
5208    }
5209
5210    /**
5211     * Called when the visibility of the view or an ancestor of the view is changed.
5212     * @param changedView The view whose visibility changed. Could be 'this' or
5213     * an ancestor view.
5214     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5215     * {@link #INVISIBLE} or {@link #GONE}.
5216     */
5217    protected void onVisibilityChanged(View changedView, int visibility) {
5218        if (visibility == VISIBLE) {
5219            if (mAttachInfo != null) {
5220                initialAwakenScrollBars();
5221            } else {
5222                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5223            }
5224        }
5225    }
5226
5227    /**
5228     * Dispatch a hint about whether this view is displayed. For instance, when
5229     * a View moves out of the screen, it might receives a display hint indicating
5230     * the view is not displayed. Applications should not <em>rely</em> on this hint
5231     * as there is no guarantee that they will receive one.
5232     *
5233     * @param hint A hint about whether or not this view is displayed:
5234     * {@link #VISIBLE} or {@link #INVISIBLE}.
5235     */
5236    public void dispatchDisplayHint(int hint) {
5237        onDisplayHint(hint);
5238    }
5239
5240    /**
5241     * Gives this view a hint about whether is displayed or not. For instance, when
5242     * a View moves out of the screen, it might receives a display hint indicating
5243     * the view is not displayed. Applications should not <em>rely</em> on this hint
5244     * as there is no guarantee that they will receive one.
5245     *
5246     * @param hint A hint about whether or not this view is displayed:
5247     * {@link #VISIBLE} or {@link #INVISIBLE}.
5248     */
5249    protected void onDisplayHint(int hint) {
5250    }
5251
5252    /**
5253     * Dispatch a window visibility change down the view hierarchy.
5254     * ViewGroups should override to route to their children.
5255     *
5256     * @param visibility The new visibility of the window.
5257     *
5258     * @see #onWindowVisibilityChanged(int)
5259     */
5260    public void dispatchWindowVisibilityChanged(int visibility) {
5261        onWindowVisibilityChanged(visibility);
5262    }
5263
5264    /**
5265     * Called when the window containing has change its visibility
5266     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5267     * that this tells you whether or not your window is being made visible
5268     * to the window manager; this does <em>not</em> tell you whether or not
5269     * your window is obscured by other windows on the screen, even if it
5270     * is itself visible.
5271     *
5272     * @param visibility The new visibility of the window.
5273     */
5274    protected void onWindowVisibilityChanged(int visibility) {
5275        if (visibility == VISIBLE) {
5276            initialAwakenScrollBars();
5277        }
5278    }
5279
5280    /**
5281     * Returns the current visibility of the window this view is attached to
5282     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5283     *
5284     * @return Returns the current visibility of the view's window.
5285     */
5286    public int getWindowVisibility() {
5287        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5288    }
5289
5290    /**
5291     * Retrieve the overall visible display size in which the window this view is
5292     * attached to has been positioned in.  This takes into account screen
5293     * decorations above the window, for both cases where the window itself
5294     * is being position inside of them or the window is being placed under
5295     * then and covered insets are used for the window to position its content
5296     * inside.  In effect, this tells you the available area where content can
5297     * be placed and remain visible to users.
5298     *
5299     * <p>This function requires an IPC back to the window manager to retrieve
5300     * the requested information, so should not be used in performance critical
5301     * code like drawing.
5302     *
5303     * @param outRect Filled in with the visible display frame.  If the view
5304     * is not attached to a window, this is simply the raw display size.
5305     */
5306    public void getWindowVisibleDisplayFrame(Rect outRect) {
5307        if (mAttachInfo != null) {
5308            try {
5309                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5310            } catch (RemoteException e) {
5311                return;
5312            }
5313            // XXX This is really broken, and probably all needs to be done
5314            // in the window manager, and we need to know more about whether
5315            // we want the area behind or in front of the IME.
5316            final Rect insets = mAttachInfo.mVisibleInsets;
5317            outRect.left += insets.left;
5318            outRect.top += insets.top;
5319            outRect.right -= insets.right;
5320            outRect.bottom -= insets.bottom;
5321            return;
5322        }
5323        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5324        d.getRectSize(outRect);
5325    }
5326
5327    /**
5328     * Dispatch a notification about a resource configuration change down
5329     * the view hierarchy.
5330     * ViewGroups should override to route to their children.
5331     *
5332     * @param newConfig The new resource configuration.
5333     *
5334     * @see #onConfigurationChanged(android.content.res.Configuration)
5335     */
5336    public void dispatchConfigurationChanged(Configuration newConfig) {
5337        onConfigurationChanged(newConfig);
5338    }
5339
5340    /**
5341     * Called when the current configuration of the resources being used
5342     * by the application have changed.  You can use this to decide when
5343     * to reload resources that can changed based on orientation and other
5344     * configuration characterstics.  You only need to use this if you are
5345     * not relying on the normal {@link android.app.Activity} mechanism of
5346     * recreating the activity instance upon a configuration change.
5347     *
5348     * @param newConfig The new resource configuration.
5349     */
5350    protected void onConfigurationChanged(Configuration newConfig) {
5351    }
5352
5353    /**
5354     * Private function to aggregate all per-view attributes in to the view
5355     * root.
5356     */
5357    void dispatchCollectViewAttributes(int visibility) {
5358        performCollectViewAttributes(visibility);
5359    }
5360
5361    void performCollectViewAttributes(int visibility) {
5362        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
5363            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
5364                mAttachInfo.mKeepScreenOn = true;
5365            }
5366            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
5367            if (mOnSystemUiVisibilityChangeListener != null) {
5368                mAttachInfo.mHasSystemUiListeners = true;
5369            }
5370        }
5371    }
5372
5373    void needGlobalAttributesUpdate(boolean force) {
5374        final AttachInfo ai = mAttachInfo;
5375        if (ai != null) {
5376            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
5377                    || ai.mHasSystemUiListeners) {
5378                ai.mRecomputeGlobalAttributes = true;
5379            }
5380        }
5381    }
5382
5383    /**
5384     * Returns whether the device is currently in touch mode.  Touch mode is entered
5385     * once the user begins interacting with the device by touch, and affects various
5386     * things like whether focus is always visible to the user.
5387     *
5388     * @return Whether the device is in touch mode.
5389     */
5390    @ViewDebug.ExportedProperty
5391    public boolean isInTouchMode() {
5392        if (mAttachInfo != null) {
5393            return mAttachInfo.mInTouchMode;
5394        } else {
5395            return ViewAncestor.isInTouchMode();
5396        }
5397    }
5398
5399    /**
5400     * Returns the context the view is running in, through which it can
5401     * access the current theme, resources, etc.
5402     *
5403     * @return The view's Context.
5404     */
5405    @ViewDebug.CapturedViewProperty
5406    public final Context getContext() {
5407        return mContext;
5408    }
5409
5410    /**
5411     * Handle a key event before it is processed by any input method
5412     * associated with the view hierarchy.  This can be used to intercept
5413     * key events in special situations before the IME consumes them; a
5414     * typical example would be handling the BACK key to update the application's
5415     * UI instead of allowing the IME to see it and close itself.
5416     *
5417     * @param keyCode The value in event.getKeyCode().
5418     * @param event Description of the key event.
5419     * @return If you handled the event, return true. If you want to allow the
5420     *         event to be handled by the next receiver, return false.
5421     */
5422    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5423        return false;
5424    }
5425
5426    /**
5427     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
5428     * KeyEvent.Callback.onKeyDown()}: perform press of the view
5429     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
5430     * is released, if the view is enabled and clickable.
5431     *
5432     * @param keyCode A key code that represents the button pressed, from
5433     *                {@link android.view.KeyEvent}.
5434     * @param event   The KeyEvent object that defines the button action.
5435     */
5436    public boolean onKeyDown(int keyCode, KeyEvent event) {
5437        boolean result = false;
5438
5439        switch (keyCode) {
5440            case KeyEvent.KEYCODE_DPAD_CENTER:
5441            case KeyEvent.KEYCODE_ENTER: {
5442                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5443                    return true;
5444                }
5445                // Long clickable items don't necessarily have to be clickable
5446                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
5447                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
5448                        (event.getRepeatCount() == 0)) {
5449                    setPressed(true);
5450                    checkForLongClick(0);
5451                    return true;
5452                }
5453                break;
5454            }
5455        }
5456        return result;
5457    }
5458
5459    /**
5460     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
5461     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
5462     * the event).
5463     */
5464    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
5465        return false;
5466    }
5467
5468    /**
5469     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
5470     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
5471     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
5472     * {@link KeyEvent#KEYCODE_ENTER} is released.
5473     *
5474     * @param keyCode A key code that represents the button pressed, from
5475     *                {@link android.view.KeyEvent}.
5476     * @param event   The KeyEvent object that defines the button action.
5477     */
5478    public boolean onKeyUp(int keyCode, KeyEvent event) {
5479        boolean result = false;
5480
5481        switch (keyCode) {
5482            case KeyEvent.KEYCODE_DPAD_CENTER:
5483            case KeyEvent.KEYCODE_ENTER: {
5484                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5485                    return true;
5486                }
5487                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
5488                    setPressed(false);
5489
5490                    if (!mHasPerformedLongPress) {
5491                        // This is a tap, so remove the longpress check
5492                        removeLongPressCallback();
5493
5494                        result = performClick();
5495                    }
5496                }
5497                break;
5498            }
5499        }
5500        return result;
5501    }
5502
5503    /**
5504     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
5505     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
5506     * the event).
5507     *
5508     * @param keyCode     A key code that represents the button pressed, from
5509     *                    {@link android.view.KeyEvent}.
5510     * @param repeatCount The number of times the action was made.
5511     * @param event       The KeyEvent object that defines the button action.
5512     */
5513    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5514        return false;
5515    }
5516
5517    /**
5518     * Called on the focused view when a key shortcut event is not handled.
5519     * Override this method to implement local key shortcuts for the View.
5520     * Key shortcuts can also be implemented by setting the
5521     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
5522     *
5523     * @param keyCode The value in event.getKeyCode().
5524     * @param event Description of the key event.
5525     * @return If you handled the event, return true. If you want to allow the
5526     *         event to be handled by the next receiver, return false.
5527     */
5528    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
5529        return false;
5530    }
5531
5532    /**
5533     * Check whether the called view is a text editor, in which case it
5534     * would make sense to automatically display a soft input window for
5535     * it.  Subclasses should override this if they implement
5536     * {@link #onCreateInputConnection(EditorInfo)} to return true if
5537     * a call on that method would return a non-null InputConnection, and
5538     * they are really a first-class editor that the user would normally
5539     * start typing on when the go into a window containing your view.
5540     *
5541     * <p>The default implementation always returns false.  This does
5542     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
5543     * will not be called or the user can not otherwise perform edits on your
5544     * view; it is just a hint to the system that this is not the primary
5545     * purpose of this view.
5546     *
5547     * @return Returns true if this view is a text editor, else false.
5548     */
5549    public boolean onCheckIsTextEditor() {
5550        return false;
5551    }
5552
5553    /**
5554     * Create a new InputConnection for an InputMethod to interact
5555     * with the view.  The default implementation returns null, since it doesn't
5556     * support input methods.  You can override this to implement such support.
5557     * This is only needed for views that take focus and text input.
5558     *
5559     * <p>When implementing this, you probably also want to implement
5560     * {@link #onCheckIsTextEditor()} to indicate you will return a
5561     * non-null InputConnection.
5562     *
5563     * @param outAttrs Fill in with attribute information about the connection.
5564     */
5565    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5566        return null;
5567    }
5568
5569    /**
5570     * Called by the {@link android.view.inputmethod.InputMethodManager}
5571     * when a view who is not the current
5572     * input connection target is trying to make a call on the manager.  The
5573     * default implementation returns false; you can override this to return
5574     * true for certain views if you are performing InputConnection proxying
5575     * to them.
5576     * @param view The View that is making the InputMethodManager call.
5577     * @return Return true to allow the call, false to reject.
5578     */
5579    public boolean checkInputConnectionProxy(View view) {
5580        return false;
5581    }
5582
5583    /**
5584     * Show the context menu for this view. It is not safe to hold on to the
5585     * menu after returning from this method.
5586     *
5587     * You should normally not overload this method. Overload
5588     * {@link #onCreateContextMenu(ContextMenu)} or define an
5589     * {@link OnCreateContextMenuListener} to add items to the context menu.
5590     *
5591     * @param menu The context menu to populate
5592     */
5593    public void createContextMenu(ContextMenu menu) {
5594        ContextMenuInfo menuInfo = getContextMenuInfo();
5595
5596        // Sets the current menu info so all items added to menu will have
5597        // my extra info set.
5598        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
5599
5600        onCreateContextMenu(menu);
5601        if (mOnCreateContextMenuListener != null) {
5602            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
5603        }
5604
5605        // Clear the extra information so subsequent items that aren't mine don't
5606        // have my extra info.
5607        ((MenuBuilder)menu).setCurrentMenuInfo(null);
5608
5609        if (mParent != null) {
5610            mParent.createContextMenu(menu);
5611        }
5612    }
5613
5614    /**
5615     * Views should implement this if they have extra information to associate
5616     * with the context menu. The return result is supplied as a parameter to
5617     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5618     * callback.
5619     *
5620     * @return Extra information about the item for which the context menu
5621     *         should be shown. This information will vary across different
5622     *         subclasses of View.
5623     */
5624    protected ContextMenuInfo getContextMenuInfo() {
5625        return null;
5626    }
5627
5628    /**
5629     * Views should implement this if the view itself is going to add items to
5630     * the context menu.
5631     *
5632     * @param menu the context menu to populate
5633     */
5634    protected void onCreateContextMenu(ContextMenu menu) {
5635    }
5636
5637    /**
5638     * Implement this method to handle trackball motion events.  The
5639     * <em>relative</em> movement of the trackball since the last event
5640     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5641     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
5642     * that a movement of 1 corresponds to the user pressing one DPAD key (so
5643     * they will often be fractional values, representing the more fine-grained
5644     * movement information available from a trackball).
5645     *
5646     * @param event The motion event.
5647     * @return True if the event was handled, false otherwise.
5648     */
5649    public boolean onTrackballEvent(MotionEvent event) {
5650        return false;
5651    }
5652
5653    /**
5654     * Implement this method to handle generic motion events.
5655     * <p>
5656     * Generic motion events describe joystick movements, mouse hovers, track pad
5657     * touches, scroll wheel movements and other input events.  The
5658     * {@link MotionEvent#getSource() source} of the motion event specifies
5659     * the class of input that was received.  Implementations of this method
5660     * must examine the bits in the source before processing the event.
5661     * The following code example shows how this is done.
5662     * </p><p>
5663     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5664     * are delivered to the view under the pointer.  All other generic motion events are
5665     * delivered to the focused view.
5666     * </p>
5667     * <code>
5668     * public boolean onGenericMotionEvent(MotionEvent event) {
5669     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
5670     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
5671     *             // process the joystick movement...
5672     *             return true;
5673     *         }
5674     *     }
5675     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
5676     *         switch (event.getAction()) {
5677     *             case MotionEvent.ACTION_HOVER_MOVE:
5678     *                 // process the mouse hover movement...
5679     *                 return true;
5680     *             case MotionEvent.ACTION_SCROLL:
5681     *                 // process the scroll wheel movement...
5682     *                 return true;
5683     *         }
5684     *     }
5685     *     return super.onGenericMotionEvent(event);
5686     * }
5687     * </code>
5688     *
5689     * @param event The generic motion event being processed.
5690     * @return True if the event was handled, false otherwise.
5691     */
5692    public boolean onGenericMotionEvent(MotionEvent event) {
5693        return false;
5694    }
5695
5696    /**
5697     * Implement this method to handle hover events.
5698     * <p>
5699     * Hover events are pointer events with action {@link MotionEvent#ACTION_HOVER_ENTER},
5700     * {@link MotionEvent#ACTION_HOVER_MOVE}, or {@link MotionEvent#ACTION_HOVER_EXIT}.
5701     * </p><p>
5702     * The view receives hover enter as the pointer enters the bounds of the view and hover
5703     * exit as the pointer exits the bound of the view or just before the pointer goes down
5704     * (which implies that {@link #onTouchEvent(MotionEvent)} will be called soon).
5705     * </p><p>
5706     * If the view would like to handle the hover event itself and prevent its children
5707     * from receiving hover, it should return true from this method.  If this method returns
5708     * true and a child has already received a hover enter event, the child will
5709     * automatically receive a hover exit event.
5710     * </p><p>
5711     * The default implementation sets the hovered state of the view if the view is
5712     * clickable.
5713     * </p>
5714     *
5715     * @param event The motion event that describes the hover.
5716     * @return True if this view handled the hover event and does not want its children
5717     * to receive the hover event.
5718     */
5719    public boolean onHoverEvent(MotionEvent event) {
5720        switch (event.getAction()) {
5721            case MotionEvent.ACTION_HOVER_ENTER:
5722                setHovered(true);
5723                break;
5724
5725            case MotionEvent.ACTION_HOVER_EXIT:
5726                setHovered(false);
5727                break;
5728        }
5729
5730        return false;
5731    }
5732
5733    /**
5734     * Returns true if the view is currently hovered.
5735     *
5736     * @return True if the view is currently hovered.
5737     */
5738    public boolean isHovered() {
5739        return (mPrivateFlags & HOVERED) != 0;
5740    }
5741
5742    /**
5743     * Sets whether the view is currently hovered.
5744     *
5745     * @param hovered True if the view is hovered.
5746     */
5747    public void setHovered(boolean hovered) {
5748        if (hovered) {
5749            if ((mPrivateFlags & HOVERED) == 0) {
5750                mPrivateFlags |= HOVERED;
5751                refreshDrawableState();
5752                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
5753            }
5754        } else {
5755            if ((mPrivateFlags & HOVERED) != 0) {
5756                mPrivateFlags &= ~HOVERED;
5757                refreshDrawableState();
5758                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
5759            }
5760        }
5761    }
5762
5763    /**
5764     * Implement this method to handle touch screen motion events.
5765     *
5766     * @param event The motion event.
5767     * @return True if the event was handled, false otherwise.
5768     */
5769    public boolean onTouchEvent(MotionEvent event) {
5770        final int viewFlags = mViewFlags;
5771
5772        if ((viewFlags & ENABLED_MASK) == DISABLED) {
5773            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
5774                mPrivateFlags &= ~PRESSED;
5775                refreshDrawableState();
5776            }
5777            // A disabled view that is clickable still consumes the touch
5778            // events, it just doesn't respond to them.
5779            return (((viewFlags & CLICKABLE) == CLICKABLE ||
5780                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
5781        }
5782
5783        if (mTouchDelegate != null) {
5784            if (mTouchDelegate.onTouchEvent(event)) {
5785                return true;
5786            }
5787        }
5788
5789        if (((viewFlags & CLICKABLE) == CLICKABLE ||
5790                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
5791            switch (event.getAction()) {
5792                case MotionEvent.ACTION_UP:
5793                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
5794                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
5795                        // take focus if we don't have it already and we should in
5796                        // touch mode.
5797                        boolean focusTaken = false;
5798                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
5799                            focusTaken = requestFocus();
5800                        }
5801
5802                        if (prepressed) {
5803                            // The button is being released before we actually
5804                            // showed it as pressed.  Make it show the pressed
5805                            // state now (before scheduling the click) to ensure
5806                            // the user sees it.
5807                            mPrivateFlags |= PRESSED;
5808                            refreshDrawableState();
5809                       }
5810
5811                        if (!mHasPerformedLongPress) {
5812                            // This is a tap, so remove the longpress check
5813                            removeLongPressCallback();
5814
5815                            // Only perform take click actions if we were in the pressed state
5816                            if (!focusTaken) {
5817                                // Use a Runnable and post this rather than calling
5818                                // performClick directly. This lets other visual state
5819                                // of the view update before click actions start.
5820                                if (mPerformClick == null) {
5821                                    mPerformClick = new PerformClick();
5822                                }
5823                                if (!post(mPerformClick)) {
5824                                    performClick();
5825                                }
5826                            }
5827                        }
5828
5829                        if (mUnsetPressedState == null) {
5830                            mUnsetPressedState = new UnsetPressedState();
5831                        }
5832
5833                        if (prepressed) {
5834                            postDelayed(mUnsetPressedState,
5835                                    ViewConfiguration.getPressedStateDuration());
5836                        } else if (!post(mUnsetPressedState)) {
5837                            // If the post failed, unpress right now
5838                            mUnsetPressedState.run();
5839                        }
5840                        removeTapCallback();
5841                    }
5842                    break;
5843
5844                case MotionEvent.ACTION_DOWN:
5845                    mHasPerformedLongPress = false;
5846
5847                    if (performButtonActionOnTouchDown(event)) {
5848                        break;
5849                    }
5850
5851                    // Walk up the hierarchy to determine if we're inside a scrolling container.
5852                    boolean isInScrollingContainer = false;
5853                    ViewParent p = getParent();
5854                    while (p != null && p instanceof ViewGroup) {
5855                        if (((ViewGroup) p).shouldDelayChildPressedState()) {
5856                            isInScrollingContainer = true;
5857                            break;
5858                        }
5859                        p = p.getParent();
5860                    }
5861
5862                    // For views inside a scrolling container, delay the pressed feedback for
5863                    // a short period in case this is a scroll.
5864                    if (isInScrollingContainer) {
5865                        mPrivateFlags |= PREPRESSED;
5866                        if (mPendingCheckForTap == null) {
5867                            mPendingCheckForTap = new CheckForTap();
5868                        }
5869                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
5870                    } else {
5871                        // Not inside a scrolling container, so show the feedback right away
5872                        mPrivateFlags |= PRESSED;
5873                        refreshDrawableState();
5874                        checkForLongClick(0);
5875                    }
5876                    break;
5877
5878                case MotionEvent.ACTION_CANCEL:
5879                    mPrivateFlags &= ~PRESSED;
5880                    refreshDrawableState();
5881                    removeTapCallback();
5882                    break;
5883
5884                case MotionEvent.ACTION_MOVE:
5885                    final int x = (int) event.getX();
5886                    final int y = (int) event.getY();
5887
5888                    // Be lenient about moving outside of buttons
5889                    if (!pointInView(x, y, mTouchSlop)) {
5890                        // Outside button
5891                        removeTapCallback();
5892                        if ((mPrivateFlags & PRESSED) != 0) {
5893                            // Remove any future long press/tap checks
5894                            removeLongPressCallback();
5895
5896                            // Need to switch from pressed to not pressed
5897                            mPrivateFlags &= ~PRESSED;
5898                            refreshDrawableState();
5899                        }
5900                    }
5901                    break;
5902            }
5903            return true;
5904        }
5905
5906        return false;
5907    }
5908
5909    /**
5910     * Remove the longpress detection timer.
5911     */
5912    private void removeLongPressCallback() {
5913        if (mPendingCheckForLongPress != null) {
5914          removeCallbacks(mPendingCheckForLongPress);
5915        }
5916    }
5917
5918    /**
5919     * Remove the pending click action
5920     */
5921    private void removePerformClickCallback() {
5922        if (mPerformClick != null) {
5923            removeCallbacks(mPerformClick);
5924        }
5925    }
5926
5927    /**
5928     * Remove the prepress detection timer.
5929     */
5930    private void removeUnsetPressCallback() {
5931        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
5932            setPressed(false);
5933            removeCallbacks(mUnsetPressedState);
5934        }
5935    }
5936
5937    /**
5938     * Remove the tap detection timer.
5939     */
5940    private void removeTapCallback() {
5941        if (mPendingCheckForTap != null) {
5942            mPrivateFlags &= ~PREPRESSED;
5943            removeCallbacks(mPendingCheckForTap);
5944        }
5945    }
5946
5947    /**
5948     * Cancels a pending long press.  Your subclass can use this if you
5949     * want the context menu to come up if the user presses and holds
5950     * at the same place, but you don't want it to come up if they press
5951     * and then move around enough to cause scrolling.
5952     */
5953    public void cancelLongPress() {
5954        removeLongPressCallback();
5955
5956        /*
5957         * The prepressed state handled by the tap callback is a display
5958         * construct, but the tap callback will post a long press callback
5959         * less its own timeout. Remove it here.
5960         */
5961        removeTapCallback();
5962    }
5963
5964    /**
5965     * Sets the TouchDelegate for this View.
5966     */
5967    public void setTouchDelegate(TouchDelegate delegate) {
5968        mTouchDelegate = delegate;
5969    }
5970
5971    /**
5972     * Gets the TouchDelegate for this View.
5973     */
5974    public TouchDelegate getTouchDelegate() {
5975        return mTouchDelegate;
5976    }
5977
5978    /**
5979     * Set flags controlling behavior of this view.
5980     *
5981     * @param flags Constant indicating the value which should be set
5982     * @param mask Constant indicating the bit range that should be changed
5983     */
5984    void setFlags(int flags, int mask) {
5985        int old = mViewFlags;
5986        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
5987
5988        int changed = mViewFlags ^ old;
5989        if (changed == 0) {
5990            return;
5991        }
5992        int privateFlags = mPrivateFlags;
5993
5994        /* Check if the FOCUSABLE bit has changed */
5995        if (((changed & FOCUSABLE_MASK) != 0) &&
5996                ((privateFlags & HAS_BOUNDS) !=0)) {
5997            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
5998                    && ((privateFlags & FOCUSED) != 0)) {
5999                /* Give up focus if we are no longer focusable */
6000                clearFocus();
6001            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6002                    && ((privateFlags & FOCUSED) == 0)) {
6003                /*
6004                 * Tell the view system that we are now available to take focus
6005                 * if no one else already has it.
6006                 */
6007                if (mParent != null) mParent.focusableViewAvailable(this);
6008            }
6009        }
6010
6011        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6012            if ((changed & VISIBILITY_MASK) != 0) {
6013                /*
6014                 * If this view is becoming visible, set the DRAWN flag so that
6015                 * the next invalidate() will not be skipped.
6016                 */
6017                mPrivateFlags |= DRAWN;
6018
6019                needGlobalAttributesUpdate(true);
6020
6021                // a view becoming visible is worth notifying the parent
6022                // about in case nothing has focus.  even if this specific view
6023                // isn't focusable, it may contain something that is, so let
6024                // the root view try to give this focus if nothing else does.
6025                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6026                    mParent.focusableViewAvailable(this);
6027                }
6028            }
6029        }
6030
6031        /* Check if the GONE bit has changed */
6032        if ((changed & GONE) != 0) {
6033            needGlobalAttributesUpdate(false);
6034            requestLayout();
6035            invalidate(true);
6036
6037            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6038                if (hasFocus()) clearFocus();
6039                destroyDrawingCache();
6040            }
6041            if (mAttachInfo != null) {
6042                mAttachInfo.mViewVisibilityChanged = true;
6043            }
6044        }
6045
6046        /* Check if the VISIBLE bit has changed */
6047        if ((changed & INVISIBLE) != 0) {
6048            needGlobalAttributesUpdate(false);
6049            invalidate(true);
6050
6051            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6052                // root view becoming invisible shouldn't clear focus
6053                if (getRootView() != this) {
6054                    clearFocus();
6055                }
6056            }
6057            if (mAttachInfo != null) {
6058                mAttachInfo.mViewVisibilityChanged = true;
6059            }
6060        }
6061
6062        if ((changed & VISIBILITY_MASK) != 0) {
6063            if (mParent instanceof ViewGroup) {
6064                ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
6065                ((View) mParent).invalidate(true);
6066            }
6067            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6068        }
6069
6070        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6071            destroyDrawingCache();
6072        }
6073
6074        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6075            destroyDrawingCache();
6076            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6077            invalidateParentCaches();
6078        }
6079
6080        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6081            destroyDrawingCache();
6082            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6083        }
6084
6085        if ((changed & DRAW_MASK) != 0) {
6086            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6087                if (mBGDrawable != null) {
6088                    mPrivateFlags &= ~SKIP_DRAW;
6089                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6090                } else {
6091                    mPrivateFlags |= SKIP_DRAW;
6092                }
6093            } else {
6094                mPrivateFlags &= ~SKIP_DRAW;
6095            }
6096            requestLayout();
6097            invalidate(true);
6098        }
6099
6100        if ((changed & KEEP_SCREEN_ON) != 0) {
6101            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6102                mParent.recomputeViewAttributes(this);
6103            }
6104        }
6105
6106        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6107            requestLayout();
6108        }
6109    }
6110
6111    /**
6112     * Change the view's z order in the tree, so it's on top of other sibling
6113     * views
6114     */
6115    public void bringToFront() {
6116        if (mParent != null) {
6117            mParent.bringChildToFront(this);
6118        }
6119    }
6120
6121    /**
6122     * This is called in response to an internal scroll in this view (i.e., the
6123     * view scrolled its own contents). This is typically as a result of
6124     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6125     * called.
6126     *
6127     * @param l Current horizontal scroll origin.
6128     * @param t Current vertical scroll origin.
6129     * @param oldl Previous horizontal scroll origin.
6130     * @param oldt Previous vertical scroll origin.
6131     */
6132    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6133        mBackgroundSizeChanged = true;
6134
6135        final AttachInfo ai = mAttachInfo;
6136        if (ai != null) {
6137            ai.mViewScrollChanged = true;
6138        }
6139    }
6140
6141    /**
6142     * Interface definition for a callback to be invoked when the layout bounds of a view
6143     * changes due to layout processing.
6144     */
6145    public interface OnLayoutChangeListener {
6146        /**
6147         * Called when the focus state of a view has changed.
6148         *
6149         * @param v The view whose state has changed.
6150         * @param left The new value of the view's left property.
6151         * @param top The new value of the view's top property.
6152         * @param right The new value of the view's right property.
6153         * @param bottom The new value of the view's bottom property.
6154         * @param oldLeft The previous value of the view's left property.
6155         * @param oldTop The previous value of the view's top property.
6156         * @param oldRight The previous value of the view's right property.
6157         * @param oldBottom The previous value of the view's bottom property.
6158         */
6159        void onLayoutChange(View v, int left, int top, int right, int bottom,
6160            int oldLeft, int oldTop, int oldRight, int oldBottom);
6161    }
6162
6163    /**
6164     * This is called during layout when the size of this view has changed. If
6165     * you were just added to the view hierarchy, you're called with the old
6166     * values of 0.
6167     *
6168     * @param w Current width of this view.
6169     * @param h Current height of this view.
6170     * @param oldw Old width of this view.
6171     * @param oldh Old height of this view.
6172     */
6173    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6174    }
6175
6176    /**
6177     * Called by draw to draw the child views. This may be overridden
6178     * by derived classes to gain control just before its children are drawn
6179     * (but after its own view has been drawn).
6180     * @param canvas the canvas on which to draw the view
6181     */
6182    protected void dispatchDraw(Canvas canvas) {
6183    }
6184
6185    /**
6186     * Gets the parent of this view. Note that the parent is a
6187     * ViewParent and not necessarily a View.
6188     *
6189     * @return Parent of this view.
6190     */
6191    public final ViewParent getParent() {
6192        return mParent;
6193    }
6194
6195    /**
6196     * Set the horizontal scrolled position of your view. This will cause a call to
6197     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6198     * invalidated.
6199     * @param value the x position to scroll to
6200     */
6201    public void setScrollX(int value) {
6202        scrollTo(value, mScrollY);
6203    }
6204
6205    /**
6206     * Set the vertical scrolled position of your view. This will cause a call to
6207     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6208     * invalidated.
6209     * @param value the y position to scroll to
6210     */
6211    public void setScrollY(int value) {
6212        scrollTo(mScrollX, value);
6213    }
6214
6215    /**
6216     * Return the scrolled left position of this view. This is the left edge of
6217     * the displayed part of your view. You do not need to draw any pixels
6218     * farther left, since those are outside of the frame of your view on
6219     * screen.
6220     *
6221     * @return The left edge of the displayed part of your view, in pixels.
6222     */
6223    public final int getScrollX() {
6224        return mScrollX;
6225    }
6226
6227    /**
6228     * Return the scrolled top position of this view. This is the top edge of
6229     * the displayed part of your view. You do not need to draw any pixels above
6230     * it, since those are outside of the frame of your view on screen.
6231     *
6232     * @return The top edge of the displayed part of your view, in pixels.
6233     */
6234    public final int getScrollY() {
6235        return mScrollY;
6236    }
6237
6238    /**
6239     * Return the width of the your view.
6240     *
6241     * @return The width of your view, in pixels.
6242     */
6243    @ViewDebug.ExportedProperty(category = "layout")
6244    public final int getWidth() {
6245        return mRight - mLeft;
6246    }
6247
6248    /**
6249     * Return the height of your view.
6250     *
6251     * @return The height of your view, in pixels.
6252     */
6253    @ViewDebug.ExportedProperty(category = "layout")
6254    public final int getHeight() {
6255        return mBottom - mTop;
6256    }
6257
6258    /**
6259     * Return the visible drawing bounds of your view. Fills in the output
6260     * rectangle with the values from getScrollX(), getScrollY(),
6261     * getWidth(), and getHeight().
6262     *
6263     * @param outRect The (scrolled) drawing bounds of the view.
6264     */
6265    public void getDrawingRect(Rect outRect) {
6266        outRect.left = mScrollX;
6267        outRect.top = mScrollY;
6268        outRect.right = mScrollX + (mRight - mLeft);
6269        outRect.bottom = mScrollY + (mBottom - mTop);
6270    }
6271
6272    /**
6273     * Like {@link #getMeasuredWidthAndState()}, but only returns the
6274     * raw width component (that is the result is masked by
6275     * {@link #MEASURED_SIZE_MASK}).
6276     *
6277     * @return The raw measured width of this view.
6278     */
6279    public final int getMeasuredWidth() {
6280        return mMeasuredWidth & MEASURED_SIZE_MASK;
6281    }
6282
6283    /**
6284     * Return the full width measurement information for this view as computed
6285     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6286     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6287     * This should be used during measurement and layout calculations only. Use
6288     * {@link #getWidth()} to see how wide a view is after layout.
6289     *
6290     * @return The measured width of this view as a bit mask.
6291     */
6292    public final int getMeasuredWidthAndState() {
6293        return mMeasuredWidth;
6294    }
6295
6296    /**
6297     * Like {@link #getMeasuredHeightAndState()}, but only returns the
6298     * raw width component (that is the result is masked by
6299     * {@link #MEASURED_SIZE_MASK}).
6300     *
6301     * @return The raw measured height of this view.
6302     */
6303    public final int getMeasuredHeight() {
6304        return mMeasuredHeight & MEASURED_SIZE_MASK;
6305    }
6306
6307    /**
6308     * Return the full height measurement information for this view as computed
6309     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6310     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6311     * This should be used during measurement and layout calculations only. Use
6312     * {@link #getHeight()} to see how wide a view is after layout.
6313     *
6314     * @return The measured width of this view as a bit mask.
6315     */
6316    public final int getMeasuredHeightAndState() {
6317        return mMeasuredHeight;
6318    }
6319
6320    /**
6321     * Return only the state bits of {@link #getMeasuredWidthAndState()}
6322     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
6323     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
6324     * and the height component is at the shifted bits
6325     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
6326     */
6327    public final int getMeasuredState() {
6328        return (mMeasuredWidth&MEASURED_STATE_MASK)
6329                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
6330                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
6331    }
6332
6333    /**
6334     * The transform matrix of this view, which is calculated based on the current
6335     * roation, scale, and pivot properties.
6336     *
6337     * @see #getRotation()
6338     * @see #getScaleX()
6339     * @see #getScaleY()
6340     * @see #getPivotX()
6341     * @see #getPivotY()
6342     * @return The current transform matrix for the view
6343     */
6344    public Matrix getMatrix() {
6345        updateMatrix();
6346        return mMatrix;
6347    }
6348
6349    /**
6350     * Utility function to determine if the value is far enough away from zero to be
6351     * considered non-zero.
6352     * @param value A floating point value to check for zero-ness
6353     * @return whether the passed-in value is far enough away from zero to be considered non-zero
6354     */
6355    private static boolean nonzero(float value) {
6356        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
6357    }
6358
6359    /**
6360     * Returns true if the transform matrix is the identity matrix.
6361     * Recomputes the matrix if necessary.
6362     *
6363     * @return True if the transform matrix is the identity matrix, false otherwise.
6364     */
6365    final boolean hasIdentityMatrix() {
6366        updateMatrix();
6367        return mMatrixIsIdentity;
6368    }
6369
6370    /**
6371     * Recomputes the transform matrix if necessary.
6372     */
6373    private void updateMatrix() {
6374        if (mMatrixDirty) {
6375            // transform-related properties have changed since the last time someone
6376            // asked for the matrix; recalculate it with the current values
6377
6378            // Figure out if we need to update the pivot point
6379            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6380                if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
6381                    mPrevWidth = mRight - mLeft;
6382                    mPrevHeight = mBottom - mTop;
6383                    mPivotX = mPrevWidth / 2f;
6384                    mPivotY = mPrevHeight / 2f;
6385                }
6386            }
6387            mMatrix.reset();
6388            if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
6389                mMatrix.setTranslate(mTranslationX, mTranslationY);
6390                mMatrix.preRotate(mRotation, mPivotX, mPivotY);
6391                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6392            } else {
6393                if (mCamera == null) {
6394                    mCamera = new Camera();
6395                    matrix3D = new Matrix();
6396                }
6397                mCamera.save();
6398                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6399                mCamera.rotate(mRotationX, mRotationY, -mRotation);
6400                mCamera.getMatrix(matrix3D);
6401                matrix3D.preTranslate(-mPivotX, -mPivotY);
6402                matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
6403                mMatrix.postConcat(matrix3D);
6404                mCamera.restore();
6405            }
6406            mMatrixDirty = false;
6407            mMatrixIsIdentity = mMatrix.isIdentity();
6408            mInverseMatrixDirty = true;
6409        }
6410    }
6411
6412    /**
6413     * Utility method to retrieve the inverse of the current mMatrix property.
6414     * We cache the matrix to avoid recalculating it when transform properties
6415     * have not changed.
6416     *
6417     * @return The inverse of the current matrix of this view.
6418     */
6419    final Matrix getInverseMatrix() {
6420        updateMatrix();
6421        if (mInverseMatrixDirty) {
6422            if (mInverseMatrix == null) {
6423                mInverseMatrix = new Matrix();
6424            }
6425            mMatrix.invert(mInverseMatrix);
6426            mInverseMatrixDirty = false;
6427        }
6428        return mInverseMatrix;
6429    }
6430
6431    /**
6432     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
6433     * views are drawn) from the camera to this view. The camera's distance
6434     * affects 3D transformations, for instance rotations around the X and Y
6435     * axis. If the rotationX or rotationY properties are changed and this view is
6436     * large (more than half the size of the screen), it is recommended to always
6437     * use a camera distance that's greater than the height (X axis rotation) or
6438     * the width (Y axis rotation) of this view.</p>
6439     *
6440     * <p>The distance of the camera from the view plane can have an affect on the
6441     * perspective distortion of the view when it is rotated around the x or y axis.
6442     * For example, a large distance will result in a large viewing angle, and there
6443     * will not be much perspective distortion of the view as it rotates. A short
6444     * distance may cause much more perspective distortion upon rotation, and can
6445     * also result in some drawing artifacts if the rotated view ends up partially
6446     * behind the camera (which is why the recommendation is to use a distance at
6447     * least as far as the size of the view, if the view is to be rotated.)</p>
6448     *
6449     * <p>The distance is expressed in "depth pixels." The default distance depends
6450     * on the screen density. For instance, on a medium density display, the
6451     * default distance is 1280. On a high density display, the default distance
6452     * is 1920.</p>
6453     *
6454     * <p>If you want to specify a distance that leads to visually consistent
6455     * results across various densities, use the following formula:</p>
6456     * <pre>
6457     * float scale = context.getResources().getDisplayMetrics().density;
6458     * view.setCameraDistance(distance * scale);
6459     * </pre>
6460     *
6461     * <p>The density scale factor of a high density display is 1.5,
6462     * and 1920 = 1280 * 1.5.</p>
6463     *
6464     * @param distance The distance in "depth pixels", if negative the opposite
6465     *        value is used
6466     *
6467     * @see #setRotationX(float)
6468     * @see #setRotationY(float)
6469     */
6470    public void setCameraDistance(float distance) {
6471        invalidateParentCaches();
6472        invalidate(false);
6473
6474        final float dpi = mResources.getDisplayMetrics().densityDpi;
6475        if (mCamera == null) {
6476            mCamera = new Camera();
6477            matrix3D = new Matrix();
6478        }
6479
6480        mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
6481        mMatrixDirty = true;
6482
6483        invalidate(false);
6484    }
6485
6486    /**
6487     * The degrees that the view is rotated around the pivot point.
6488     *
6489     * @see #setRotation(float)
6490     * @see #getPivotX()
6491     * @see #getPivotY()
6492     *
6493     * @return The degrees of rotation.
6494     */
6495    public float getRotation() {
6496        return mRotation;
6497    }
6498
6499    /**
6500     * Sets the degrees that the view is rotated around the pivot point. Increasing values
6501     * result in clockwise rotation.
6502     *
6503     * @param rotation The degrees of rotation.
6504     *
6505     * @see #getRotation()
6506     * @see #getPivotX()
6507     * @see #getPivotY()
6508     * @see #setRotationX(float)
6509     * @see #setRotationY(float)
6510     *
6511     * @attr ref android.R.styleable#View_rotation
6512     */
6513    public void setRotation(float rotation) {
6514        if (mRotation != rotation) {
6515            invalidateParentCaches();
6516            // Double-invalidation is necessary to capture view's old and new areas
6517            invalidate(false);
6518            mRotation = rotation;
6519            mMatrixDirty = true;
6520            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6521            invalidate(false);
6522        }
6523    }
6524
6525    /**
6526     * The degrees that the view is rotated around the vertical axis through the pivot point.
6527     *
6528     * @see #getPivotX()
6529     * @see #getPivotY()
6530     * @see #setRotationY(float)
6531     *
6532     * @return The degrees of Y rotation.
6533     */
6534    public float getRotationY() {
6535        return mRotationY;
6536    }
6537
6538    /**
6539     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
6540     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
6541     * down the y axis.
6542     *
6543     * When rotating large views, it is recommended to adjust the camera distance
6544     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
6545     *
6546     * @param rotationY The degrees of Y rotation.
6547     *
6548     * @see #getRotationY()
6549     * @see #getPivotX()
6550     * @see #getPivotY()
6551     * @see #setRotation(float)
6552     * @see #setRotationX(float)
6553     * @see #setCameraDistance(float)
6554     *
6555     * @attr ref android.R.styleable#View_rotationY
6556     */
6557    public void setRotationY(float rotationY) {
6558        if (mRotationY != rotationY) {
6559            invalidateParentCaches();
6560            // Double-invalidation is necessary to capture view's old and new areas
6561            invalidate(false);
6562            mRotationY = rotationY;
6563            mMatrixDirty = true;
6564            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6565            invalidate(false);
6566        }
6567    }
6568
6569    /**
6570     * The degrees that the view is rotated around the horizontal axis through the pivot point.
6571     *
6572     * @see #getPivotX()
6573     * @see #getPivotY()
6574     * @see #setRotationX(float)
6575     *
6576     * @return The degrees of X rotation.
6577     */
6578    public float getRotationX() {
6579        return mRotationX;
6580    }
6581
6582    /**
6583     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
6584     * Increasing values result in clockwise rotation from the viewpoint of looking down the
6585     * x axis.
6586     *
6587     * When rotating large views, it is recommended to adjust the camera distance
6588     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
6589     *
6590     * @param rotationX The degrees of X rotation.
6591     *
6592     * @see #getRotationX()
6593     * @see #getPivotX()
6594     * @see #getPivotY()
6595     * @see #setRotation(float)
6596     * @see #setRotationY(float)
6597     * @see #setCameraDistance(float)
6598     *
6599     * @attr ref android.R.styleable#View_rotationX
6600     */
6601    public void setRotationX(float rotationX) {
6602        if (mRotationX != rotationX) {
6603            invalidateParentCaches();
6604            // Double-invalidation is necessary to capture view's old and new areas
6605            invalidate(false);
6606            mRotationX = rotationX;
6607            mMatrixDirty = true;
6608            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6609            invalidate(false);
6610        }
6611    }
6612
6613    /**
6614     * The amount that the view is scaled in x around the pivot point, as a proportion of
6615     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
6616     *
6617     * <p>By default, this is 1.0f.
6618     *
6619     * @see #getPivotX()
6620     * @see #getPivotY()
6621     * @return The scaling factor.
6622     */
6623    public float getScaleX() {
6624        return mScaleX;
6625    }
6626
6627    /**
6628     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
6629     * the view's unscaled width. A value of 1 means that no scaling is applied.
6630     *
6631     * @param scaleX The scaling factor.
6632     * @see #getPivotX()
6633     * @see #getPivotY()
6634     *
6635     * @attr ref android.R.styleable#View_scaleX
6636     */
6637    public void setScaleX(float scaleX) {
6638        if (mScaleX != scaleX) {
6639            invalidateParentCaches();
6640            // Double-invalidation is necessary to capture view's old and new areas
6641            invalidate(false);
6642            mScaleX = scaleX;
6643            mMatrixDirty = true;
6644            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6645            invalidate(false);
6646        }
6647    }
6648
6649    /**
6650     * The amount that the view is scaled in y around the pivot point, as a proportion of
6651     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
6652     *
6653     * <p>By default, this is 1.0f.
6654     *
6655     * @see #getPivotX()
6656     * @see #getPivotY()
6657     * @return The scaling factor.
6658     */
6659    public float getScaleY() {
6660        return mScaleY;
6661    }
6662
6663    /**
6664     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
6665     * the view's unscaled width. A value of 1 means that no scaling is applied.
6666     *
6667     * @param scaleY The scaling factor.
6668     * @see #getPivotX()
6669     * @see #getPivotY()
6670     *
6671     * @attr ref android.R.styleable#View_scaleY
6672     */
6673    public void setScaleY(float scaleY) {
6674        if (mScaleY != scaleY) {
6675            invalidateParentCaches();
6676            // Double-invalidation is necessary to capture view's old and new areas
6677            invalidate(false);
6678            mScaleY = scaleY;
6679            mMatrixDirty = true;
6680            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6681            invalidate(false);
6682        }
6683    }
6684
6685    /**
6686     * The x location of the point around which the view is {@link #setRotation(float) rotated}
6687     * and {@link #setScaleX(float) scaled}.
6688     *
6689     * @see #getRotation()
6690     * @see #getScaleX()
6691     * @see #getScaleY()
6692     * @see #getPivotY()
6693     * @return The x location of the pivot point.
6694     */
6695    public float getPivotX() {
6696        return mPivotX;
6697    }
6698
6699    /**
6700     * Sets the x location of the point around which the view is
6701     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
6702     * By default, the pivot point is centered on the object.
6703     * Setting this property disables this behavior and causes the view to use only the
6704     * explicitly set pivotX and pivotY values.
6705     *
6706     * @param pivotX The x location of the pivot point.
6707     * @see #getRotation()
6708     * @see #getScaleX()
6709     * @see #getScaleY()
6710     * @see #getPivotY()
6711     *
6712     * @attr ref android.R.styleable#View_transformPivotX
6713     */
6714    public void setPivotX(float pivotX) {
6715        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
6716        if (mPivotX != pivotX) {
6717            invalidateParentCaches();
6718            // Double-invalidation is necessary to capture view's old and new areas
6719            invalidate(false);
6720            mPivotX = pivotX;
6721            mMatrixDirty = true;
6722            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6723            invalidate(false);
6724        }
6725    }
6726
6727    /**
6728     * The y location of the point around which the view is {@link #setRotation(float) rotated}
6729     * and {@link #setScaleY(float) scaled}.
6730     *
6731     * @see #getRotation()
6732     * @see #getScaleX()
6733     * @see #getScaleY()
6734     * @see #getPivotY()
6735     * @return The y location of the pivot point.
6736     */
6737    public float getPivotY() {
6738        return mPivotY;
6739    }
6740
6741    /**
6742     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
6743     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
6744     * Setting this property disables this behavior and causes the view to use only the
6745     * explicitly set pivotX and pivotY values.
6746     *
6747     * @param pivotY The y location of the pivot point.
6748     * @see #getRotation()
6749     * @see #getScaleX()
6750     * @see #getScaleY()
6751     * @see #getPivotY()
6752     *
6753     * @attr ref android.R.styleable#View_transformPivotY
6754     */
6755    public void setPivotY(float pivotY) {
6756        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
6757        if (mPivotY != pivotY) {
6758            invalidateParentCaches();
6759            // Double-invalidation is necessary to capture view's old and new areas
6760            invalidate(false);
6761            mPivotY = pivotY;
6762            mMatrixDirty = true;
6763            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6764            invalidate(false);
6765        }
6766    }
6767
6768    /**
6769     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
6770     * completely transparent and 1 means the view is completely opaque.
6771     *
6772     * <p>By default this is 1.0f.
6773     * @return The opacity of the view.
6774     */
6775    public float getAlpha() {
6776        return mAlpha;
6777    }
6778
6779    /**
6780     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
6781     * completely transparent and 1 means the view is completely opaque.</p>
6782     *
6783     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
6784     * responsible for applying the opacity itself. Otherwise, calling this method is
6785     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
6786     * setting a hardware layer.</p>
6787     *
6788     * @param alpha The opacity of the view.
6789     *
6790     * @see #setLayerType(int, android.graphics.Paint)
6791     *
6792     * @attr ref android.R.styleable#View_alpha
6793     */
6794    public void setAlpha(float alpha) {
6795        mAlpha = alpha;
6796        invalidateParentCaches();
6797        if (onSetAlpha((int) (alpha * 255))) {
6798            mPrivateFlags |= ALPHA_SET;
6799            // subclass is handling alpha - don't optimize rendering cache invalidation
6800            invalidate(true);
6801        } else {
6802            mPrivateFlags &= ~ALPHA_SET;
6803            invalidate(false);
6804        }
6805    }
6806
6807    /**
6808     * Faster version of setAlpha() which performs the same steps except there are
6809     * no calls to invalidate(). The caller of this function should perform proper invalidation
6810     * on the parent and this object. The return value indicates whether the subclass handles
6811     * alpha (the return value for onSetAlpha()).
6812     *
6813     * @param alpha The new value for the alpha property
6814     * @return true if the View subclass handles alpha (the return value for onSetAlpha())
6815     */
6816    boolean setAlphaNoInvalidation(float alpha) {
6817        mAlpha = alpha;
6818        boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
6819        if (subclassHandlesAlpha) {
6820            mPrivateFlags |= ALPHA_SET;
6821        } else {
6822            mPrivateFlags &= ~ALPHA_SET;
6823        }
6824        return subclassHandlesAlpha;
6825    }
6826
6827    /**
6828     * Top position of this view relative to its parent.
6829     *
6830     * @return The top of this view, in pixels.
6831     */
6832    @ViewDebug.CapturedViewProperty
6833    public final int getTop() {
6834        return mTop;
6835    }
6836
6837    /**
6838     * Sets the top position of this view relative to its parent. This method is meant to be called
6839     * by the layout system and should not generally be called otherwise, because the property
6840     * may be changed at any time by the layout.
6841     *
6842     * @param top The top of this view, in pixels.
6843     */
6844    public final void setTop(int top) {
6845        if (top != mTop) {
6846            updateMatrix();
6847            if (mMatrixIsIdentity) {
6848                if (mAttachInfo != null) {
6849                    int minTop;
6850                    int yLoc;
6851                    if (top < mTop) {
6852                        minTop = top;
6853                        yLoc = top - mTop;
6854                    } else {
6855                        minTop = mTop;
6856                        yLoc = 0;
6857                    }
6858                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
6859                }
6860            } else {
6861                // Double-invalidation is necessary to capture view's old and new areas
6862                invalidate(true);
6863            }
6864
6865            int width = mRight - mLeft;
6866            int oldHeight = mBottom - mTop;
6867
6868            mTop = top;
6869
6870            onSizeChanged(width, mBottom - mTop, width, oldHeight);
6871
6872            if (!mMatrixIsIdentity) {
6873                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6874                    // A change in dimension means an auto-centered pivot point changes, too
6875                    mMatrixDirty = true;
6876                }
6877                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6878                invalidate(true);
6879            }
6880            mBackgroundSizeChanged = true;
6881            invalidateParentIfNeeded();
6882        }
6883    }
6884
6885    /**
6886     * Bottom position of this view relative to its parent.
6887     *
6888     * @return The bottom of this view, in pixels.
6889     */
6890    @ViewDebug.CapturedViewProperty
6891    public final int getBottom() {
6892        return mBottom;
6893    }
6894
6895    /**
6896     * True if this view has changed since the last time being drawn.
6897     *
6898     * @return The dirty state of this view.
6899     */
6900    public boolean isDirty() {
6901        return (mPrivateFlags & DIRTY_MASK) != 0;
6902    }
6903
6904    /**
6905     * Sets the bottom position of this view relative to its parent. This method is meant to be
6906     * called by the layout system and should not generally be called otherwise, because the
6907     * property may be changed at any time by the layout.
6908     *
6909     * @param bottom The bottom of this view, in pixels.
6910     */
6911    public final void setBottom(int bottom) {
6912        if (bottom != mBottom) {
6913            updateMatrix();
6914            if (mMatrixIsIdentity) {
6915                if (mAttachInfo != null) {
6916                    int maxBottom;
6917                    if (bottom < mBottom) {
6918                        maxBottom = mBottom;
6919                    } else {
6920                        maxBottom = bottom;
6921                    }
6922                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
6923                }
6924            } else {
6925                // Double-invalidation is necessary to capture view's old and new areas
6926                invalidate(true);
6927            }
6928
6929            int width = mRight - mLeft;
6930            int oldHeight = mBottom - mTop;
6931
6932            mBottom = bottom;
6933
6934            onSizeChanged(width, mBottom - mTop, width, oldHeight);
6935
6936            if (!mMatrixIsIdentity) {
6937                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6938                    // A change in dimension means an auto-centered pivot point changes, too
6939                    mMatrixDirty = true;
6940                }
6941                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6942                invalidate(true);
6943            }
6944            mBackgroundSizeChanged = true;
6945            invalidateParentIfNeeded();
6946        }
6947    }
6948
6949    /**
6950     * Left position of this view relative to its parent.
6951     *
6952     * @return The left edge of this view, in pixels.
6953     */
6954    @ViewDebug.CapturedViewProperty
6955    public final int getLeft() {
6956        return mLeft;
6957    }
6958
6959    /**
6960     * Sets the left position of this view relative to its parent. This method is meant to be called
6961     * by the layout system and should not generally be called otherwise, because the property
6962     * may be changed at any time by the layout.
6963     *
6964     * @param left The bottom of this view, in pixels.
6965     */
6966    public final void setLeft(int left) {
6967        if (left != mLeft) {
6968            updateMatrix();
6969            if (mMatrixIsIdentity) {
6970                if (mAttachInfo != null) {
6971                    int minLeft;
6972                    int xLoc;
6973                    if (left < mLeft) {
6974                        minLeft = left;
6975                        xLoc = left - mLeft;
6976                    } else {
6977                        minLeft = mLeft;
6978                        xLoc = 0;
6979                    }
6980                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
6981                }
6982            } else {
6983                // Double-invalidation is necessary to capture view's old and new areas
6984                invalidate(true);
6985            }
6986
6987            int oldWidth = mRight - mLeft;
6988            int height = mBottom - mTop;
6989
6990            mLeft = left;
6991
6992            onSizeChanged(mRight - mLeft, height, oldWidth, height);
6993
6994            if (!mMatrixIsIdentity) {
6995                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6996                    // A change in dimension means an auto-centered pivot point changes, too
6997                    mMatrixDirty = true;
6998                }
6999                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7000                invalidate(true);
7001            }
7002            mBackgroundSizeChanged = true;
7003            invalidateParentIfNeeded();
7004        }
7005    }
7006
7007    /**
7008     * Right position of this view relative to its parent.
7009     *
7010     * @return The right edge of this view, in pixels.
7011     */
7012    @ViewDebug.CapturedViewProperty
7013    public final int getRight() {
7014        return mRight;
7015    }
7016
7017    /**
7018     * Sets the right position of this view relative to its parent. This method is meant to be called
7019     * by the layout system and should not generally be called otherwise, because the property
7020     * may be changed at any time by the layout.
7021     *
7022     * @param right The bottom of this view, in pixels.
7023     */
7024    public final void setRight(int right) {
7025        if (right != mRight) {
7026            updateMatrix();
7027            if (mMatrixIsIdentity) {
7028                if (mAttachInfo != null) {
7029                    int maxRight;
7030                    if (right < mRight) {
7031                        maxRight = mRight;
7032                    } else {
7033                        maxRight = right;
7034                    }
7035                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7036                }
7037            } else {
7038                // Double-invalidation is necessary to capture view's old and new areas
7039                invalidate(true);
7040            }
7041
7042            int oldWidth = mRight - mLeft;
7043            int height = mBottom - mTop;
7044
7045            mRight = right;
7046
7047            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7048
7049            if (!mMatrixIsIdentity) {
7050                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7051                    // A change in dimension means an auto-centered pivot point changes, too
7052                    mMatrixDirty = true;
7053                }
7054                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7055                invalidate(true);
7056            }
7057            mBackgroundSizeChanged = true;
7058            invalidateParentIfNeeded();
7059        }
7060    }
7061
7062    /**
7063     * The visual x position of this view, in pixels. This is equivalent to the
7064     * {@link #setTranslationX(float) translationX} property plus the current
7065     * {@link #getLeft() left} property.
7066     *
7067     * @return The visual x position of this view, in pixels.
7068     */
7069    public float getX() {
7070        return mLeft + mTranslationX;
7071    }
7072
7073    /**
7074     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7075     * {@link #setTranslationX(float) translationX} property to be the difference between
7076     * the x value passed in and the current {@link #getLeft() left} property.
7077     *
7078     * @param x The visual x position of this view, in pixels.
7079     */
7080    public void setX(float x) {
7081        setTranslationX(x - mLeft);
7082    }
7083
7084    /**
7085     * The visual y position of this view, in pixels. This is equivalent to the
7086     * {@link #setTranslationY(float) translationY} property plus the current
7087     * {@link #getTop() top} property.
7088     *
7089     * @return The visual y position of this view, in pixels.
7090     */
7091    public float getY() {
7092        return mTop + mTranslationY;
7093    }
7094
7095    /**
7096     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7097     * {@link #setTranslationY(float) translationY} property to be the difference between
7098     * the y value passed in and the current {@link #getTop() top} property.
7099     *
7100     * @param y The visual y position of this view, in pixels.
7101     */
7102    public void setY(float y) {
7103        setTranslationY(y - mTop);
7104    }
7105
7106
7107    /**
7108     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7109     * This position is post-layout, in addition to wherever the object's
7110     * layout placed it.
7111     *
7112     * @return The horizontal position of this view relative to its left position, in pixels.
7113     */
7114    public float getTranslationX() {
7115        return mTranslationX;
7116    }
7117
7118    /**
7119     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7120     * This effectively positions the object post-layout, in addition to wherever the object's
7121     * layout placed it.
7122     *
7123     * @param translationX The horizontal position of this view relative to its left position,
7124     * in pixels.
7125     *
7126     * @attr ref android.R.styleable#View_translationX
7127     */
7128    public void setTranslationX(float translationX) {
7129        if (mTranslationX != translationX) {
7130            invalidateParentCaches();
7131            // Double-invalidation is necessary to capture view's old and new areas
7132            invalidate(false);
7133            mTranslationX = translationX;
7134            mMatrixDirty = true;
7135            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7136            invalidate(false);
7137        }
7138    }
7139
7140    /**
7141     * The horizontal location of this view relative to its {@link #getTop() top} position.
7142     * This position is post-layout, in addition to wherever the object's
7143     * layout placed it.
7144     *
7145     * @return The vertical position of this view relative to its top position,
7146     * in pixels.
7147     */
7148    public float getTranslationY() {
7149        return mTranslationY;
7150    }
7151
7152    /**
7153     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7154     * This effectively positions the object post-layout, in addition to wherever the object's
7155     * layout placed it.
7156     *
7157     * @param translationY The vertical position of this view relative to its top position,
7158     * in pixels.
7159     *
7160     * @attr ref android.R.styleable#View_translationY
7161     */
7162    public void setTranslationY(float translationY) {
7163        if (mTranslationY != translationY) {
7164            invalidateParentCaches();
7165            // Double-invalidation is necessary to capture view's old and new areas
7166            invalidate(false);
7167            mTranslationY = translationY;
7168            mMatrixDirty = true;
7169            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7170            invalidate(false);
7171        }
7172    }
7173
7174    /**
7175     * @hide
7176     */
7177    public void setFastTranslationX(float x) {
7178        mTranslationX = x;
7179        mMatrixDirty = true;
7180    }
7181
7182    /**
7183     * @hide
7184     */
7185    public void setFastTranslationY(float y) {
7186        mTranslationY = y;
7187        mMatrixDirty = true;
7188    }
7189
7190    /**
7191     * @hide
7192     */
7193    public void setFastX(float x) {
7194        mTranslationX = x - mLeft;
7195        mMatrixDirty = true;
7196    }
7197
7198    /**
7199     * @hide
7200     */
7201    public void setFastY(float y) {
7202        mTranslationY = y - mTop;
7203        mMatrixDirty = true;
7204    }
7205
7206    /**
7207     * @hide
7208     */
7209    public void setFastScaleX(float x) {
7210        mScaleX = x;
7211        mMatrixDirty = true;
7212    }
7213
7214    /**
7215     * @hide
7216     */
7217    public void setFastScaleY(float y) {
7218        mScaleY = y;
7219        mMatrixDirty = true;
7220    }
7221
7222    /**
7223     * @hide
7224     */
7225    public void setFastAlpha(float alpha) {
7226        mAlpha = alpha;
7227    }
7228
7229    /**
7230     * @hide
7231     */
7232    public void setFastRotationY(float y) {
7233        mRotationY = y;
7234        mMatrixDirty = true;
7235    }
7236
7237    /**
7238     * Hit rectangle in parent's coordinates
7239     *
7240     * @param outRect The hit rectangle of the view.
7241     */
7242    public void getHitRect(Rect outRect) {
7243        updateMatrix();
7244        if (mMatrixIsIdentity || mAttachInfo == null) {
7245            outRect.set(mLeft, mTop, mRight, mBottom);
7246        } else {
7247            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
7248            tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
7249            mMatrix.mapRect(tmpRect);
7250            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
7251                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
7252        }
7253    }
7254
7255    /**
7256     * Determines whether the given point, in local coordinates is inside the view.
7257     */
7258    /*package*/ final boolean pointInView(float localX, float localY) {
7259        return localX >= 0 && localX < (mRight - mLeft)
7260                && localY >= 0 && localY < (mBottom - mTop);
7261    }
7262
7263    /**
7264     * Utility method to determine whether the given point, in local coordinates,
7265     * is inside the view, where the area of the view is expanded by the slop factor.
7266     * This method is called while processing touch-move events to determine if the event
7267     * is still within the view.
7268     */
7269    private boolean pointInView(float localX, float localY, float slop) {
7270        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
7271                localY < ((mBottom - mTop) + slop);
7272    }
7273
7274    /**
7275     * When a view has focus and the user navigates away from it, the next view is searched for
7276     * starting from the rectangle filled in by this method.
7277     *
7278     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
7279     * of the view.  However, if your view maintains some idea of internal selection,
7280     * such as a cursor, or a selected row or column, you should override this method and
7281     * fill in a more specific rectangle.
7282     *
7283     * @param r The rectangle to fill in, in this view's coordinates.
7284     */
7285    public void getFocusedRect(Rect r) {
7286        getDrawingRect(r);
7287    }
7288
7289    /**
7290     * If some part of this view is not clipped by any of its parents, then
7291     * return that area in r in global (root) coordinates. To convert r to local
7292     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
7293     * -globalOffset.y)) If the view is completely clipped or translated out,
7294     * return false.
7295     *
7296     * @param r If true is returned, r holds the global coordinates of the
7297     *        visible portion of this view.
7298     * @param globalOffset If true is returned, globalOffset holds the dx,dy
7299     *        between this view and its root. globalOffet may be null.
7300     * @return true if r is non-empty (i.e. part of the view is visible at the
7301     *         root level.
7302     */
7303    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
7304        int width = mRight - mLeft;
7305        int height = mBottom - mTop;
7306        if (width > 0 && height > 0) {
7307            r.set(0, 0, width, height);
7308            if (globalOffset != null) {
7309                globalOffset.set(-mScrollX, -mScrollY);
7310            }
7311            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
7312        }
7313        return false;
7314    }
7315
7316    public final boolean getGlobalVisibleRect(Rect r) {
7317        return getGlobalVisibleRect(r, null);
7318    }
7319
7320    public final boolean getLocalVisibleRect(Rect r) {
7321        Point offset = new Point();
7322        if (getGlobalVisibleRect(r, offset)) {
7323            r.offset(-offset.x, -offset.y); // make r local
7324            return true;
7325        }
7326        return false;
7327    }
7328
7329    /**
7330     * Offset this view's vertical location by the specified number of pixels.
7331     *
7332     * @param offset the number of pixels to offset the view by
7333     */
7334    public void offsetTopAndBottom(int offset) {
7335        if (offset != 0) {
7336            updateMatrix();
7337            if (mMatrixIsIdentity) {
7338                final ViewParent p = mParent;
7339                if (p != null && mAttachInfo != null) {
7340                    final Rect r = mAttachInfo.mTmpInvalRect;
7341                    int minTop;
7342                    int maxBottom;
7343                    int yLoc;
7344                    if (offset < 0) {
7345                        minTop = mTop + offset;
7346                        maxBottom = mBottom;
7347                        yLoc = offset;
7348                    } else {
7349                        minTop = mTop;
7350                        maxBottom = mBottom + offset;
7351                        yLoc = 0;
7352                    }
7353                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
7354                    p.invalidateChild(this, r);
7355                }
7356            } else {
7357                invalidate(false);
7358            }
7359
7360            mTop += offset;
7361            mBottom += offset;
7362
7363            if (!mMatrixIsIdentity) {
7364                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7365                invalidate(false);
7366            }
7367            invalidateParentIfNeeded();
7368        }
7369    }
7370
7371    /**
7372     * Offset this view's horizontal location by the specified amount of pixels.
7373     *
7374     * @param offset the numer of pixels to offset the view by
7375     */
7376    public void offsetLeftAndRight(int offset) {
7377        if (offset != 0) {
7378            updateMatrix();
7379            if (mMatrixIsIdentity) {
7380                final ViewParent p = mParent;
7381                if (p != null && mAttachInfo != null) {
7382                    final Rect r = mAttachInfo.mTmpInvalRect;
7383                    int minLeft;
7384                    int maxRight;
7385                    if (offset < 0) {
7386                        minLeft = mLeft + offset;
7387                        maxRight = mRight;
7388                    } else {
7389                        minLeft = mLeft;
7390                        maxRight = mRight + offset;
7391                    }
7392                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
7393                    p.invalidateChild(this, r);
7394                }
7395            } else {
7396                invalidate(false);
7397            }
7398
7399            mLeft += offset;
7400            mRight += offset;
7401
7402            if (!mMatrixIsIdentity) {
7403                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7404                invalidate(false);
7405            }
7406            invalidateParentIfNeeded();
7407        }
7408    }
7409
7410    /**
7411     * Get the LayoutParams associated with this view. All views should have
7412     * layout parameters. These supply parameters to the <i>parent</i> of this
7413     * view specifying how it should be arranged. There are many subclasses of
7414     * ViewGroup.LayoutParams, and these correspond to the different subclasses
7415     * of ViewGroup that are responsible for arranging their children.
7416     *
7417     * This method may return null if this View is not attached to a parent
7418     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
7419     * was not invoked successfully. When a View is attached to a parent
7420     * ViewGroup, this method must not return null.
7421     *
7422     * @return The LayoutParams associated with this view, or null if no
7423     *         parameters have been set yet
7424     */
7425    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
7426    public ViewGroup.LayoutParams getLayoutParams() {
7427        return mLayoutParams;
7428    }
7429
7430    /**
7431     * Set the layout parameters associated with this view. These supply
7432     * parameters to the <i>parent</i> of this view specifying how it should be
7433     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
7434     * correspond to the different subclasses of ViewGroup that are responsible
7435     * for arranging their children.
7436     *
7437     * @param params The layout parameters for this view, cannot be null
7438     */
7439    public void setLayoutParams(ViewGroup.LayoutParams params) {
7440        if (params == null) {
7441            throw new NullPointerException("Layout parameters cannot be null");
7442        }
7443        mLayoutParams = params;
7444        requestLayout();
7445    }
7446
7447    /**
7448     * Set the scrolled position of your view. This will cause a call to
7449     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7450     * invalidated.
7451     * @param x the x position to scroll to
7452     * @param y the y position to scroll to
7453     */
7454    public void scrollTo(int x, int y) {
7455        if (mScrollX != x || mScrollY != y) {
7456            int oldX = mScrollX;
7457            int oldY = mScrollY;
7458            mScrollX = x;
7459            mScrollY = y;
7460            invalidateParentCaches();
7461            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
7462            if (!awakenScrollBars()) {
7463                invalidate(true);
7464            }
7465        }
7466    }
7467
7468    /**
7469     * Move the scrolled position of your view. This will cause a call to
7470     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7471     * invalidated.
7472     * @param x the amount of pixels to scroll by horizontally
7473     * @param y the amount of pixels to scroll by vertically
7474     */
7475    public void scrollBy(int x, int y) {
7476        scrollTo(mScrollX + x, mScrollY + y);
7477    }
7478
7479    /**
7480     * <p>Trigger the scrollbars to draw. When invoked this method starts an
7481     * animation to fade the scrollbars out after a default delay. If a subclass
7482     * provides animated scrolling, the start delay should equal the duration
7483     * of the scrolling animation.</p>
7484     *
7485     * <p>The animation starts only if at least one of the scrollbars is
7486     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
7487     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7488     * this method returns true, and false otherwise. If the animation is
7489     * started, this method calls {@link #invalidate()}; in that case the
7490     * caller should not call {@link #invalidate()}.</p>
7491     *
7492     * <p>This method should be invoked every time a subclass directly updates
7493     * the scroll parameters.</p>
7494     *
7495     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
7496     * and {@link #scrollTo(int, int)}.</p>
7497     *
7498     * @return true if the animation is played, false otherwise
7499     *
7500     * @see #awakenScrollBars(int)
7501     * @see #scrollBy(int, int)
7502     * @see #scrollTo(int, int)
7503     * @see #isHorizontalScrollBarEnabled()
7504     * @see #isVerticalScrollBarEnabled()
7505     * @see #setHorizontalScrollBarEnabled(boolean)
7506     * @see #setVerticalScrollBarEnabled(boolean)
7507     */
7508    protected boolean awakenScrollBars() {
7509        return mScrollCache != null &&
7510                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
7511    }
7512
7513    /**
7514     * Trigger the scrollbars to draw.
7515     * This method differs from awakenScrollBars() only in its default duration.
7516     * initialAwakenScrollBars() will show the scroll bars for longer than
7517     * usual to give the user more of a chance to notice them.
7518     *
7519     * @return true if the animation is played, false otherwise.
7520     */
7521    private boolean initialAwakenScrollBars() {
7522        return mScrollCache != null &&
7523                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
7524    }
7525
7526    /**
7527     * <p>
7528     * Trigger the scrollbars to draw. When invoked this method starts an
7529     * animation to fade the scrollbars out after a fixed delay. If a subclass
7530     * provides animated scrolling, the start delay should equal the duration of
7531     * the scrolling animation.
7532     * </p>
7533     *
7534     * <p>
7535     * The animation starts only if at least one of the scrollbars is enabled,
7536     * as specified by {@link #isHorizontalScrollBarEnabled()} and
7537     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7538     * this method returns true, and false otherwise. If the animation is
7539     * started, this method calls {@link #invalidate()}; in that case the caller
7540     * should not call {@link #invalidate()}.
7541     * </p>
7542     *
7543     * <p>
7544     * This method should be invoked everytime a subclass directly updates the
7545     * scroll parameters.
7546     * </p>
7547     *
7548     * @param startDelay the delay, in milliseconds, after which the animation
7549     *        should start; when the delay is 0, the animation starts
7550     *        immediately
7551     * @return true if the animation is played, false otherwise
7552     *
7553     * @see #scrollBy(int, int)
7554     * @see #scrollTo(int, int)
7555     * @see #isHorizontalScrollBarEnabled()
7556     * @see #isVerticalScrollBarEnabled()
7557     * @see #setHorizontalScrollBarEnabled(boolean)
7558     * @see #setVerticalScrollBarEnabled(boolean)
7559     */
7560    protected boolean awakenScrollBars(int startDelay) {
7561        return awakenScrollBars(startDelay, true);
7562    }
7563
7564    /**
7565     * <p>
7566     * Trigger the scrollbars to draw. When invoked this method starts an
7567     * animation to fade the scrollbars out after a fixed delay. If a subclass
7568     * provides animated scrolling, the start delay should equal the duration of
7569     * the scrolling animation.
7570     * </p>
7571     *
7572     * <p>
7573     * The animation starts only if at least one of the scrollbars is enabled,
7574     * as specified by {@link #isHorizontalScrollBarEnabled()} and
7575     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7576     * this method returns true, and false otherwise. If the animation is
7577     * started, this method calls {@link #invalidate()} if the invalidate parameter
7578     * is set to true; in that case the caller
7579     * should not call {@link #invalidate()}.
7580     * </p>
7581     *
7582     * <p>
7583     * This method should be invoked everytime a subclass directly updates the
7584     * scroll parameters.
7585     * </p>
7586     *
7587     * @param startDelay the delay, in milliseconds, after which the animation
7588     *        should start; when the delay is 0, the animation starts
7589     *        immediately
7590     *
7591     * @param invalidate Wheter this method should call invalidate
7592     *
7593     * @return true if the animation is played, false otherwise
7594     *
7595     * @see #scrollBy(int, int)
7596     * @see #scrollTo(int, int)
7597     * @see #isHorizontalScrollBarEnabled()
7598     * @see #isVerticalScrollBarEnabled()
7599     * @see #setHorizontalScrollBarEnabled(boolean)
7600     * @see #setVerticalScrollBarEnabled(boolean)
7601     */
7602    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
7603        final ScrollabilityCache scrollCache = mScrollCache;
7604
7605        if (scrollCache == null || !scrollCache.fadeScrollBars) {
7606            return false;
7607        }
7608
7609        if (scrollCache.scrollBar == null) {
7610            scrollCache.scrollBar = new ScrollBarDrawable();
7611        }
7612
7613        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
7614
7615            if (invalidate) {
7616                // Invalidate to show the scrollbars
7617                invalidate(true);
7618            }
7619
7620            if (scrollCache.state == ScrollabilityCache.OFF) {
7621                // FIXME: this is copied from WindowManagerService.
7622                // We should get this value from the system when it
7623                // is possible to do so.
7624                final int KEY_REPEAT_FIRST_DELAY = 750;
7625                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
7626            }
7627
7628            // Tell mScrollCache when we should start fading. This may
7629            // extend the fade start time if one was already scheduled
7630            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
7631            scrollCache.fadeStartTime = fadeStartTime;
7632            scrollCache.state = ScrollabilityCache.ON;
7633
7634            // Schedule our fader to run, unscheduling any old ones first
7635            if (mAttachInfo != null) {
7636                mAttachInfo.mHandler.removeCallbacks(scrollCache);
7637                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
7638            }
7639
7640            return true;
7641        }
7642
7643        return false;
7644    }
7645
7646    /**
7647     * Mark the the area defined by dirty as needing to be drawn. If the view is
7648     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
7649     * in the future. This must be called from a UI thread. To call from a non-UI
7650     * thread, call {@link #postInvalidate()}.
7651     *
7652     * WARNING: This method is destructive to dirty.
7653     * @param dirty the rectangle representing the bounds of the dirty region
7654     */
7655    public void invalidate(Rect dirty) {
7656        if (ViewDebug.TRACE_HIERARCHY) {
7657            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
7658        }
7659
7660        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
7661                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
7662                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
7663            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7664            mPrivateFlags |= INVALIDATED;
7665            final ViewParent p = mParent;
7666            final AttachInfo ai = mAttachInfo;
7667            //noinspection PointlessBooleanExpression,ConstantConditions
7668            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
7669                if (p != null && ai != null && ai.mHardwareAccelerated) {
7670                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
7671                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
7672                    p.invalidateChild(this, null);
7673                    return;
7674                }
7675            }
7676            if (p != null && ai != null) {
7677                final int scrollX = mScrollX;
7678                final int scrollY = mScrollY;
7679                final Rect r = ai.mTmpInvalRect;
7680                r.set(dirty.left - scrollX, dirty.top - scrollY,
7681                        dirty.right - scrollX, dirty.bottom - scrollY);
7682                mParent.invalidateChild(this, r);
7683            }
7684        }
7685    }
7686
7687    /**
7688     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
7689     * The coordinates of the dirty rect are relative to the view.
7690     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
7691     * will be called at some point in the future. This must be called from
7692     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
7693     * @param l the left position of the dirty region
7694     * @param t the top position of the dirty region
7695     * @param r the right position of the dirty region
7696     * @param b the bottom position of the dirty region
7697     */
7698    public void invalidate(int l, int t, int r, int b) {
7699        if (ViewDebug.TRACE_HIERARCHY) {
7700            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
7701        }
7702
7703        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
7704                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
7705                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
7706            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7707            mPrivateFlags |= INVALIDATED;
7708            final ViewParent p = mParent;
7709            final AttachInfo ai = mAttachInfo;
7710            //noinspection PointlessBooleanExpression,ConstantConditions
7711            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
7712                if (p != null && ai != null && ai.mHardwareAccelerated) {
7713                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
7714                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
7715                    p.invalidateChild(this, null);
7716                    return;
7717                }
7718            }
7719            if (p != null && ai != null && l < r && t < b) {
7720                final int scrollX = mScrollX;
7721                final int scrollY = mScrollY;
7722                final Rect tmpr = ai.mTmpInvalRect;
7723                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
7724                p.invalidateChild(this, tmpr);
7725            }
7726        }
7727    }
7728
7729    /**
7730     * Invalidate the whole view. If the view is visible,
7731     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
7732     * the future. This must be called from a UI thread. To call from a non-UI thread,
7733     * call {@link #postInvalidate()}.
7734     */
7735    public void invalidate() {
7736        invalidate(true);
7737    }
7738
7739    /**
7740     * This is where the invalidate() work actually happens. A full invalidate()
7741     * causes the drawing cache to be invalidated, but this function can be called with
7742     * invalidateCache set to false to skip that invalidation step for cases that do not
7743     * need it (for example, a component that remains at the same dimensions with the same
7744     * content).
7745     *
7746     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
7747     * well. This is usually true for a full invalidate, but may be set to false if the
7748     * View's contents or dimensions have not changed.
7749     */
7750    void invalidate(boolean invalidateCache) {
7751        if (ViewDebug.TRACE_HIERARCHY) {
7752            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
7753        }
7754
7755        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
7756                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
7757                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
7758            mLastIsOpaque = isOpaque();
7759            mPrivateFlags &= ~DRAWN;
7760            if (invalidateCache) {
7761                mPrivateFlags |= INVALIDATED;
7762                mPrivateFlags &= ~DRAWING_CACHE_VALID;
7763            }
7764            final AttachInfo ai = mAttachInfo;
7765            final ViewParent p = mParent;
7766            //noinspection PointlessBooleanExpression,ConstantConditions
7767            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
7768                if (p != null && ai != null && ai.mHardwareAccelerated) {
7769                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
7770                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
7771                    p.invalidateChild(this, null);
7772                    return;
7773                }
7774            }
7775
7776            if (p != null && ai != null) {
7777                final Rect r = ai.mTmpInvalRect;
7778                r.set(0, 0, mRight - mLeft, mBottom - mTop);
7779                // Don't call invalidate -- we don't want to internally scroll
7780                // our own bounds
7781                p.invalidateChild(this, r);
7782            }
7783        }
7784    }
7785
7786    /**
7787     * @hide
7788     */
7789    public void fastInvalidate() {
7790        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
7791            (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
7792            (mPrivateFlags & INVALIDATED) != INVALIDATED) {
7793            if (mParent instanceof View) {
7794                ((View) mParent).mPrivateFlags |= INVALIDATED;
7795            }
7796            mPrivateFlags &= ~DRAWN;
7797            mPrivateFlags |= INVALIDATED;
7798            mPrivateFlags &= ~DRAWING_CACHE_VALID;
7799            if (mParent != null && mAttachInfo != null) {
7800                if (mAttachInfo.mHardwareAccelerated) {
7801                    mParent.invalidateChild(this, null);
7802                } else {
7803                    final Rect r = mAttachInfo.mTmpInvalRect;
7804                    r.set(0, 0, mRight - mLeft, mBottom - mTop);
7805                    // Don't call invalidate -- we don't want to internally scroll
7806                    // our own bounds
7807                    mParent.invalidateChild(this, r);
7808                }
7809            }
7810        }
7811    }
7812
7813    /**
7814     * Used to indicate that the parent of this view should clear its caches. This functionality
7815     * is used to force the parent to rebuild its display list (when hardware-accelerated),
7816     * which is necessary when various parent-managed properties of the view change, such as
7817     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
7818     * clears the parent caches and does not causes an invalidate event.
7819     *
7820     * @hide
7821     */
7822    protected void invalidateParentCaches() {
7823        if (mParent instanceof View) {
7824            ((View) mParent).mPrivateFlags |= INVALIDATED;
7825        }
7826    }
7827
7828    /**
7829     * Used to indicate that the parent of this view should be invalidated. This functionality
7830     * is used to force the parent to rebuild its display list (when hardware-accelerated),
7831     * which is necessary when various parent-managed properties of the view change, such as
7832     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
7833     * an invalidation event to the parent.
7834     *
7835     * @hide
7836     */
7837    protected void invalidateParentIfNeeded() {
7838        if (isHardwareAccelerated() && mParent instanceof View) {
7839            ((View) mParent).invalidate(true);
7840        }
7841    }
7842
7843    /**
7844     * Indicates whether this View is opaque. An opaque View guarantees that it will
7845     * draw all the pixels overlapping its bounds using a fully opaque color.
7846     *
7847     * Subclasses of View should override this method whenever possible to indicate
7848     * whether an instance is opaque. Opaque Views are treated in a special way by
7849     * the View hierarchy, possibly allowing it to perform optimizations during
7850     * invalidate/draw passes.
7851     *
7852     * @return True if this View is guaranteed to be fully opaque, false otherwise.
7853     */
7854    @ViewDebug.ExportedProperty(category = "drawing")
7855    public boolean isOpaque() {
7856        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
7857                (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
7858    }
7859
7860    /**
7861     * @hide
7862     */
7863    protected void computeOpaqueFlags() {
7864        // Opaque if:
7865        //   - Has a background
7866        //   - Background is opaque
7867        //   - Doesn't have scrollbars or scrollbars are inside overlay
7868
7869        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
7870            mPrivateFlags |= OPAQUE_BACKGROUND;
7871        } else {
7872            mPrivateFlags &= ~OPAQUE_BACKGROUND;
7873        }
7874
7875        final int flags = mViewFlags;
7876        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
7877                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
7878            mPrivateFlags |= OPAQUE_SCROLLBARS;
7879        } else {
7880            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
7881        }
7882    }
7883
7884    /**
7885     * @hide
7886     */
7887    protected boolean hasOpaqueScrollbars() {
7888        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
7889    }
7890
7891    /**
7892     * @return A handler associated with the thread running the View. This
7893     * handler can be used to pump events in the UI events queue.
7894     */
7895    public Handler getHandler() {
7896        if (mAttachInfo != null) {
7897            return mAttachInfo.mHandler;
7898        }
7899        return null;
7900    }
7901
7902    /**
7903     * Causes the Runnable to be added to the message queue.
7904     * The runnable will be run on the user interface thread.
7905     *
7906     * @param action The Runnable that will be executed.
7907     *
7908     * @return Returns true if the Runnable was successfully placed in to the
7909     *         message queue.  Returns false on failure, usually because the
7910     *         looper processing the message queue is exiting.
7911     */
7912    public boolean post(Runnable action) {
7913        Handler handler;
7914        AttachInfo attachInfo = mAttachInfo;
7915        if (attachInfo != null) {
7916            handler = attachInfo.mHandler;
7917        } else {
7918            // Assume that post will succeed later
7919            ViewAncestor.getRunQueue().post(action);
7920            return true;
7921        }
7922
7923        return handler.post(action);
7924    }
7925
7926    /**
7927     * Causes the Runnable to be added to the message queue, to be run
7928     * after the specified amount of time elapses.
7929     * The runnable will be run on the user interface thread.
7930     *
7931     * @param action The Runnable that will be executed.
7932     * @param delayMillis The delay (in milliseconds) until the Runnable
7933     *        will be executed.
7934     *
7935     * @return true if the Runnable was successfully placed in to the
7936     *         message queue.  Returns false on failure, usually because the
7937     *         looper processing the message queue is exiting.  Note that a
7938     *         result of true does not mean the Runnable will be processed --
7939     *         if the looper is quit before the delivery time of the message
7940     *         occurs then the message will be dropped.
7941     */
7942    public boolean postDelayed(Runnable action, long delayMillis) {
7943        Handler handler;
7944        AttachInfo attachInfo = mAttachInfo;
7945        if (attachInfo != null) {
7946            handler = attachInfo.mHandler;
7947        } else {
7948            // Assume that post will succeed later
7949            ViewAncestor.getRunQueue().postDelayed(action, delayMillis);
7950            return true;
7951        }
7952
7953        return handler.postDelayed(action, delayMillis);
7954    }
7955
7956    /**
7957     * Removes the specified Runnable from the message queue.
7958     *
7959     * @param action The Runnable to remove from the message handling queue
7960     *
7961     * @return true if this view could ask the Handler to remove the Runnable,
7962     *         false otherwise. When the returned value is true, the Runnable
7963     *         may or may not have been actually removed from the message queue
7964     *         (for instance, if the Runnable was not in the queue already.)
7965     */
7966    public boolean removeCallbacks(Runnable action) {
7967        Handler handler;
7968        AttachInfo attachInfo = mAttachInfo;
7969        if (attachInfo != null) {
7970            handler = attachInfo.mHandler;
7971        } else {
7972            // Assume that post will succeed later
7973            ViewAncestor.getRunQueue().removeCallbacks(action);
7974            return true;
7975        }
7976
7977        handler.removeCallbacks(action);
7978        return true;
7979    }
7980
7981    /**
7982     * Cause an invalidate to happen on a subsequent cycle through the event loop.
7983     * Use this to invalidate the View from a non-UI thread.
7984     *
7985     * @see #invalidate()
7986     */
7987    public void postInvalidate() {
7988        postInvalidateDelayed(0);
7989    }
7990
7991    /**
7992     * Cause an invalidate of the specified area to happen on a subsequent cycle
7993     * through the event loop. Use this to invalidate the View from a non-UI thread.
7994     *
7995     * @param left The left coordinate of the rectangle to invalidate.
7996     * @param top The top coordinate of the rectangle to invalidate.
7997     * @param right The right coordinate of the rectangle to invalidate.
7998     * @param bottom The bottom coordinate of the rectangle to invalidate.
7999     *
8000     * @see #invalidate(int, int, int, int)
8001     * @see #invalidate(Rect)
8002     */
8003    public void postInvalidate(int left, int top, int right, int bottom) {
8004        postInvalidateDelayed(0, left, top, right, bottom);
8005    }
8006
8007    /**
8008     * Cause an invalidate to happen on a subsequent cycle through the event
8009     * loop. Waits for the specified amount of time.
8010     *
8011     * @param delayMilliseconds the duration in milliseconds to delay the
8012     *         invalidation by
8013     */
8014    public void postInvalidateDelayed(long delayMilliseconds) {
8015        // We try only with the AttachInfo because there's no point in invalidating
8016        // if we are not attached to our window
8017        AttachInfo attachInfo = mAttachInfo;
8018        if (attachInfo != null) {
8019            Message msg = Message.obtain();
8020            msg.what = AttachInfo.INVALIDATE_MSG;
8021            msg.obj = this;
8022            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8023        }
8024    }
8025
8026    /**
8027     * Cause an invalidate of the specified area to happen on a subsequent cycle
8028     * through the event loop. Waits for the specified amount of time.
8029     *
8030     * @param delayMilliseconds the duration in milliseconds to delay the
8031     *         invalidation by
8032     * @param left The left coordinate of the rectangle to invalidate.
8033     * @param top The top coordinate of the rectangle to invalidate.
8034     * @param right The right coordinate of the rectangle to invalidate.
8035     * @param bottom The bottom coordinate of the rectangle to invalidate.
8036     */
8037    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8038            int right, int bottom) {
8039
8040        // We try only with the AttachInfo because there's no point in invalidating
8041        // if we are not attached to our window
8042        AttachInfo attachInfo = mAttachInfo;
8043        if (attachInfo != null) {
8044            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8045            info.target = this;
8046            info.left = left;
8047            info.top = top;
8048            info.right = right;
8049            info.bottom = bottom;
8050
8051            final Message msg = Message.obtain();
8052            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8053            msg.obj = info;
8054            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8055        }
8056    }
8057
8058    /**
8059     * Called by a parent to request that a child update its values for mScrollX
8060     * and mScrollY if necessary. This will typically be done if the child is
8061     * animating a scroll using a {@link android.widget.Scroller Scroller}
8062     * object.
8063     */
8064    public void computeScroll() {
8065    }
8066
8067    /**
8068     * <p>Indicate whether the horizontal edges are faded when the view is
8069     * scrolled horizontally.</p>
8070     *
8071     * @return true if the horizontal edges should are faded on scroll, false
8072     *         otherwise
8073     *
8074     * @see #setHorizontalFadingEdgeEnabled(boolean)
8075     * @attr ref android.R.styleable#View_fadingEdge
8076     */
8077    public boolean isHorizontalFadingEdgeEnabled() {
8078        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8079    }
8080
8081    /**
8082     * <p>Define whether the horizontal edges should be faded when this view
8083     * is scrolled horizontally.</p>
8084     *
8085     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8086     *                                    be faded when the view is scrolled
8087     *                                    horizontally
8088     *
8089     * @see #isHorizontalFadingEdgeEnabled()
8090     * @attr ref android.R.styleable#View_fadingEdge
8091     */
8092    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8093        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8094            if (horizontalFadingEdgeEnabled) {
8095                initScrollCache();
8096            }
8097
8098            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8099        }
8100    }
8101
8102    /**
8103     * <p>Indicate whether the vertical edges are faded when the view is
8104     * scrolled horizontally.</p>
8105     *
8106     * @return true if the vertical edges should are faded on scroll, false
8107     *         otherwise
8108     *
8109     * @see #setVerticalFadingEdgeEnabled(boolean)
8110     * @attr ref android.R.styleable#View_fadingEdge
8111     */
8112    public boolean isVerticalFadingEdgeEnabled() {
8113        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8114    }
8115
8116    /**
8117     * <p>Define whether the vertical edges should be faded when this view
8118     * is scrolled vertically.</p>
8119     *
8120     * @param verticalFadingEdgeEnabled true if the vertical edges should
8121     *                                  be faded when the view is scrolled
8122     *                                  vertically
8123     *
8124     * @see #isVerticalFadingEdgeEnabled()
8125     * @attr ref android.R.styleable#View_fadingEdge
8126     */
8127    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8128        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8129            if (verticalFadingEdgeEnabled) {
8130                initScrollCache();
8131            }
8132
8133            mViewFlags ^= FADING_EDGE_VERTICAL;
8134        }
8135    }
8136
8137    /**
8138     * Returns the strength, or intensity, of the top faded edge. The strength is
8139     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8140     * returns 0.0 or 1.0 but no value in between.
8141     *
8142     * Subclasses should override this method to provide a smoother fade transition
8143     * when scrolling occurs.
8144     *
8145     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8146     */
8147    protected float getTopFadingEdgeStrength() {
8148        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8149    }
8150
8151    /**
8152     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8153     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8154     * returns 0.0 or 1.0 but no value in between.
8155     *
8156     * Subclasses should override this method to provide a smoother fade transition
8157     * when scrolling occurs.
8158     *
8159     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8160     */
8161    protected float getBottomFadingEdgeStrength() {
8162        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8163                computeVerticalScrollRange() ? 1.0f : 0.0f;
8164    }
8165
8166    /**
8167     * Returns the strength, or intensity, of the left faded edge. The strength is
8168     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8169     * returns 0.0 or 1.0 but no value in between.
8170     *
8171     * Subclasses should override this method to provide a smoother fade transition
8172     * when scrolling occurs.
8173     *
8174     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8175     */
8176    protected float getLeftFadingEdgeStrength() {
8177        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8178    }
8179
8180    /**
8181     * Returns the strength, or intensity, of the right faded edge. The strength is
8182     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8183     * returns 0.0 or 1.0 but no value in between.
8184     *
8185     * Subclasses should override this method to provide a smoother fade transition
8186     * when scrolling occurs.
8187     *
8188     * @return the intensity of the right fade as a float between 0.0f and 1.0f
8189     */
8190    protected float getRightFadingEdgeStrength() {
8191        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
8192                computeHorizontalScrollRange() ? 1.0f : 0.0f;
8193    }
8194
8195    /**
8196     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
8197     * scrollbar is not drawn by default.</p>
8198     *
8199     * @return true if the horizontal scrollbar should be painted, false
8200     *         otherwise
8201     *
8202     * @see #setHorizontalScrollBarEnabled(boolean)
8203     */
8204    public boolean isHorizontalScrollBarEnabled() {
8205        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8206    }
8207
8208    /**
8209     * <p>Define whether the horizontal scrollbar should be drawn or not. The
8210     * scrollbar is not drawn by default.</p>
8211     *
8212     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
8213     *                                   be painted
8214     *
8215     * @see #isHorizontalScrollBarEnabled()
8216     */
8217    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
8218        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
8219            mViewFlags ^= SCROLLBARS_HORIZONTAL;
8220            computeOpaqueFlags();
8221            recomputePadding();
8222        }
8223    }
8224
8225    /**
8226     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
8227     * scrollbar is not drawn by default.</p>
8228     *
8229     * @return true if the vertical scrollbar should be painted, false
8230     *         otherwise
8231     *
8232     * @see #setVerticalScrollBarEnabled(boolean)
8233     */
8234    public boolean isVerticalScrollBarEnabled() {
8235        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
8236    }
8237
8238    /**
8239     * <p>Define whether the vertical scrollbar should be drawn or not. The
8240     * scrollbar is not drawn by default.</p>
8241     *
8242     * @param verticalScrollBarEnabled true if the vertical scrollbar should
8243     *                                 be painted
8244     *
8245     * @see #isVerticalScrollBarEnabled()
8246     */
8247    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
8248        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
8249            mViewFlags ^= SCROLLBARS_VERTICAL;
8250            computeOpaqueFlags();
8251            recomputePadding();
8252        }
8253    }
8254
8255    /**
8256     * @hide
8257     */
8258    protected void recomputePadding() {
8259        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
8260    }
8261
8262    /**
8263     * Define whether scrollbars will fade when the view is not scrolling.
8264     *
8265     * @param fadeScrollbars wheter to enable fading
8266     *
8267     */
8268    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
8269        initScrollCache();
8270        final ScrollabilityCache scrollabilityCache = mScrollCache;
8271        scrollabilityCache.fadeScrollBars = fadeScrollbars;
8272        if (fadeScrollbars) {
8273            scrollabilityCache.state = ScrollabilityCache.OFF;
8274        } else {
8275            scrollabilityCache.state = ScrollabilityCache.ON;
8276        }
8277    }
8278
8279    /**
8280     *
8281     * Returns true if scrollbars will fade when this view is not scrolling
8282     *
8283     * @return true if scrollbar fading is enabled
8284     */
8285    public boolean isScrollbarFadingEnabled() {
8286        return mScrollCache != null && mScrollCache.fadeScrollBars;
8287    }
8288
8289    /**
8290     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
8291     * inset. When inset, they add to the padding of the view. And the scrollbars
8292     * can be drawn inside the padding area or on the edge of the view. For example,
8293     * if a view has a background drawable and you want to draw the scrollbars
8294     * inside the padding specified by the drawable, you can use
8295     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
8296     * appear at the edge of the view, ignoring the padding, then you can use
8297     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
8298     * @param style the style of the scrollbars. Should be one of
8299     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
8300     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
8301     * @see #SCROLLBARS_INSIDE_OVERLAY
8302     * @see #SCROLLBARS_INSIDE_INSET
8303     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8304     * @see #SCROLLBARS_OUTSIDE_INSET
8305     */
8306    public void setScrollBarStyle(int style) {
8307        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
8308            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
8309            computeOpaqueFlags();
8310            recomputePadding();
8311        }
8312    }
8313
8314    /**
8315     * <p>Returns the current scrollbar style.</p>
8316     * @return the current scrollbar style
8317     * @see #SCROLLBARS_INSIDE_OVERLAY
8318     * @see #SCROLLBARS_INSIDE_INSET
8319     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8320     * @see #SCROLLBARS_OUTSIDE_INSET
8321     */
8322    public int getScrollBarStyle() {
8323        return mViewFlags & SCROLLBARS_STYLE_MASK;
8324    }
8325
8326    /**
8327     * <p>Compute the horizontal range that the horizontal scrollbar
8328     * represents.</p>
8329     *
8330     * <p>The range is expressed in arbitrary units that must be the same as the
8331     * units used by {@link #computeHorizontalScrollExtent()} and
8332     * {@link #computeHorizontalScrollOffset()}.</p>
8333     *
8334     * <p>The default range is the drawing width of this view.</p>
8335     *
8336     * @return the total horizontal range represented by the horizontal
8337     *         scrollbar
8338     *
8339     * @see #computeHorizontalScrollExtent()
8340     * @see #computeHorizontalScrollOffset()
8341     * @see android.widget.ScrollBarDrawable
8342     */
8343    protected int computeHorizontalScrollRange() {
8344        return getWidth();
8345    }
8346
8347    /**
8348     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
8349     * within the horizontal range. This value is used to compute the position
8350     * of the thumb within the scrollbar's track.</p>
8351     *
8352     * <p>The range is expressed in arbitrary units that must be the same as the
8353     * units used by {@link #computeHorizontalScrollRange()} and
8354     * {@link #computeHorizontalScrollExtent()}.</p>
8355     *
8356     * <p>The default offset is the scroll offset of this view.</p>
8357     *
8358     * @return the horizontal offset of the scrollbar's thumb
8359     *
8360     * @see #computeHorizontalScrollRange()
8361     * @see #computeHorizontalScrollExtent()
8362     * @see android.widget.ScrollBarDrawable
8363     */
8364    protected int computeHorizontalScrollOffset() {
8365        return mScrollX;
8366    }
8367
8368    /**
8369     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
8370     * within the horizontal range. This value is used to compute the length
8371     * of the thumb within the scrollbar's track.</p>
8372     *
8373     * <p>The range is expressed in arbitrary units that must be the same as the
8374     * units used by {@link #computeHorizontalScrollRange()} and
8375     * {@link #computeHorizontalScrollOffset()}.</p>
8376     *
8377     * <p>The default extent is the drawing width of this view.</p>
8378     *
8379     * @return the horizontal extent of the scrollbar's thumb
8380     *
8381     * @see #computeHorizontalScrollRange()
8382     * @see #computeHorizontalScrollOffset()
8383     * @see android.widget.ScrollBarDrawable
8384     */
8385    protected int computeHorizontalScrollExtent() {
8386        return getWidth();
8387    }
8388
8389    /**
8390     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
8391     *
8392     * <p>The range is expressed in arbitrary units that must be the same as the
8393     * units used by {@link #computeVerticalScrollExtent()} and
8394     * {@link #computeVerticalScrollOffset()}.</p>
8395     *
8396     * @return the total vertical range represented by the vertical scrollbar
8397     *
8398     * <p>The default range is the drawing height of this view.</p>
8399     *
8400     * @see #computeVerticalScrollExtent()
8401     * @see #computeVerticalScrollOffset()
8402     * @see android.widget.ScrollBarDrawable
8403     */
8404    protected int computeVerticalScrollRange() {
8405        return getHeight();
8406    }
8407
8408    /**
8409     * <p>Compute the vertical offset of the vertical scrollbar's thumb
8410     * within the horizontal range. This value is used to compute the position
8411     * of the thumb within the scrollbar's track.</p>
8412     *
8413     * <p>The range is expressed in arbitrary units that must be the same as the
8414     * units used by {@link #computeVerticalScrollRange()} and
8415     * {@link #computeVerticalScrollExtent()}.</p>
8416     *
8417     * <p>The default offset is the scroll offset of this view.</p>
8418     *
8419     * @return the vertical offset of the scrollbar's thumb
8420     *
8421     * @see #computeVerticalScrollRange()
8422     * @see #computeVerticalScrollExtent()
8423     * @see android.widget.ScrollBarDrawable
8424     */
8425    protected int computeVerticalScrollOffset() {
8426        return mScrollY;
8427    }
8428
8429    /**
8430     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
8431     * within the vertical range. This value is used to compute the length
8432     * of the thumb within the scrollbar's track.</p>
8433     *
8434     * <p>The range is expressed in arbitrary units that must be the same as the
8435     * units used by {@link #computeVerticalScrollRange()} and
8436     * {@link #computeVerticalScrollOffset()}.</p>
8437     *
8438     * <p>The default extent is the drawing height of this view.</p>
8439     *
8440     * @return the vertical extent of the scrollbar's thumb
8441     *
8442     * @see #computeVerticalScrollRange()
8443     * @see #computeVerticalScrollOffset()
8444     * @see android.widget.ScrollBarDrawable
8445     */
8446    protected int computeVerticalScrollExtent() {
8447        return getHeight();
8448    }
8449
8450    /**
8451     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
8452     * scrollbars are painted only if they have been awakened first.</p>
8453     *
8454     * @param canvas the canvas on which to draw the scrollbars
8455     *
8456     * @see #awakenScrollBars(int)
8457     */
8458    protected final void onDrawScrollBars(Canvas canvas) {
8459        // scrollbars are drawn only when the animation is running
8460        final ScrollabilityCache cache = mScrollCache;
8461        if (cache != null) {
8462
8463            int state = cache.state;
8464
8465            if (state == ScrollabilityCache.OFF) {
8466                return;
8467            }
8468
8469            boolean invalidate = false;
8470
8471            if (state == ScrollabilityCache.FADING) {
8472                // We're fading -- get our fade interpolation
8473                if (cache.interpolatorValues == null) {
8474                    cache.interpolatorValues = new float[1];
8475                }
8476
8477                float[] values = cache.interpolatorValues;
8478
8479                // Stops the animation if we're done
8480                if (cache.scrollBarInterpolator.timeToValues(values) ==
8481                        Interpolator.Result.FREEZE_END) {
8482                    cache.state = ScrollabilityCache.OFF;
8483                } else {
8484                    cache.scrollBar.setAlpha(Math.round(values[0]));
8485                }
8486
8487                // This will make the scroll bars inval themselves after
8488                // drawing. We only want this when we're fading so that
8489                // we prevent excessive redraws
8490                invalidate = true;
8491            } else {
8492                // We're just on -- but we may have been fading before so
8493                // reset alpha
8494                cache.scrollBar.setAlpha(255);
8495            }
8496
8497
8498            final int viewFlags = mViewFlags;
8499
8500            final boolean drawHorizontalScrollBar =
8501                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8502            final boolean drawVerticalScrollBar =
8503                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
8504                && !isVerticalScrollBarHidden();
8505
8506            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
8507                final int width = mRight - mLeft;
8508                final int height = mBottom - mTop;
8509
8510                final ScrollBarDrawable scrollBar = cache.scrollBar;
8511
8512                final int scrollX = mScrollX;
8513                final int scrollY = mScrollY;
8514                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
8515
8516                int left, top, right, bottom;
8517
8518                if (drawHorizontalScrollBar) {
8519                    int size = scrollBar.getSize(false);
8520                    if (size <= 0) {
8521                        size = cache.scrollBarSize;
8522                    }
8523
8524                    scrollBar.setParameters(computeHorizontalScrollRange(),
8525                                            computeHorizontalScrollOffset(),
8526                                            computeHorizontalScrollExtent(), false);
8527                    final int verticalScrollBarGap = drawVerticalScrollBar ?
8528                            getVerticalScrollbarWidth() : 0;
8529                    top = scrollY + height - size - (mUserPaddingBottom & inside);
8530                    left = scrollX + (mPaddingLeft & inside);
8531                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
8532                    bottom = top + size;
8533                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
8534                    if (invalidate) {
8535                        invalidate(left, top, right, bottom);
8536                    }
8537                }
8538
8539                if (drawVerticalScrollBar) {
8540                    int size = scrollBar.getSize(true);
8541                    if (size <= 0) {
8542                        size = cache.scrollBarSize;
8543                    }
8544
8545                    scrollBar.setParameters(computeVerticalScrollRange(),
8546                                            computeVerticalScrollOffset(),
8547                                            computeVerticalScrollExtent(), true);
8548                    switch (mVerticalScrollbarPosition) {
8549                        default:
8550                        case SCROLLBAR_POSITION_DEFAULT:
8551                        case SCROLLBAR_POSITION_RIGHT:
8552                            left = scrollX + width - size - (mUserPaddingRight & inside);
8553                            break;
8554                        case SCROLLBAR_POSITION_LEFT:
8555                            left = scrollX + (mUserPaddingLeft & inside);
8556                            break;
8557                    }
8558                    top = scrollY + (mPaddingTop & inside);
8559                    right = left + size;
8560                    bottom = scrollY + height - (mUserPaddingBottom & inside);
8561                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
8562                    if (invalidate) {
8563                        invalidate(left, top, right, bottom);
8564                    }
8565                }
8566            }
8567        }
8568    }
8569
8570    /**
8571     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
8572     * FastScroller is visible.
8573     * @return whether to temporarily hide the vertical scrollbar
8574     * @hide
8575     */
8576    protected boolean isVerticalScrollBarHidden() {
8577        return false;
8578    }
8579
8580    /**
8581     * <p>Draw the horizontal scrollbar if
8582     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
8583     *
8584     * @param canvas the canvas on which to draw the scrollbar
8585     * @param scrollBar the scrollbar's drawable
8586     *
8587     * @see #isHorizontalScrollBarEnabled()
8588     * @see #computeHorizontalScrollRange()
8589     * @see #computeHorizontalScrollExtent()
8590     * @see #computeHorizontalScrollOffset()
8591     * @see android.widget.ScrollBarDrawable
8592     * @hide
8593     */
8594    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
8595            int l, int t, int r, int b) {
8596        scrollBar.setBounds(l, t, r, b);
8597        scrollBar.draw(canvas);
8598    }
8599
8600    /**
8601     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
8602     * returns true.</p>
8603     *
8604     * @param canvas the canvas on which to draw the scrollbar
8605     * @param scrollBar the scrollbar's drawable
8606     *
8607     * @see #isVerticalScrollBarEnabled()
8608     * @see #computeVerticalScrollRange()
8609     * @see #computeVerticalScrollExtent()
8610     * @see #computeVerticalScrollOffset()
8611     * @see android.widget.ScrollBarDrawable
8612     * @hide
8613     */
8614    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
8615            int l, int t, int r, int b) {
8616        scrollBar.setBounds(l, t, r, b);
8617        scrollBar.draw(canvas);
8618    }
8619
8620    /**
8621     * Implement this to do your drawing.
8622     *
8623     * @param canvas the canvas on which the background will be drawn
8624     */
8625    protected void onDraw(Canvas canvas) {
8626    }
8627
8628    /*
8629     * Caller is responsible for calling requestLayout if necessary.
8630     * (This allows addViewInLayout to not request a new layout.)
8631     */
8632    void assignParent(ViewParent parent) {
8633        if (mParent == null) {
8634            mParent = parent;
8635        } else if (parent == null) {
8636            mParent = null;
8637        } else {
8638            throw new RuntimeException("view " + this + " being added, but"
8639                    + " it already has a parent");
8640        }
8641    }
8642
8643    /**
8644     * This is called when the view is attached to a window.  At this point it
8645     * has a Surface and will start drawing.  Note that this function is
8646     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
8647     * however it may be called any time before the first onDraw -- including
8648     * before or after {@link #onMeasure(int, int)}.
8649     *
8650     * @see #onDetachedFromWindow()
8651     */
8652    protected void onAttachedToWindow() {
8653        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
8654            mParent.requestTransparentRegion(this);
8655        }
8656        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
8657            initialAwakenScrollBars();
8658            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
8659        }
8660        jumpDrawablesToCurrentState();
8661        resolveLayoutDirection();
8662    }
8663
8664    /**
8665     * Resolving the layout direction. LTR is set initially.
8666     * We are supposing here that the parent directionality will be resolved before its children
8667     */
8668    private void resolveLayoutDirection() {
8669        mPrivateFlags2 &= ~RESOLVED_LAYOUT_RTL;
8670        switch (getLayoutDirection()) {
8671            case LAYOUT_DIRECTION_INHERIT:
8672                // If this is root view, no need to look at parent's layout dir.
8673                if (mParent != null && mParent instanceof ViewGroup &&
8674                        ((ViewGroup) mParent).isLayoutRtl()) {
8675                    mPrivateFlags2 |= RESOLVED_LAYOUT_RTL;
8676                }
8677                break;
8678            case LAYOUT_DIRECTION_RTL:
8679                mPrivateFlags2 |= RESOLVED_LAYOUT_RTL;
8680                break;
8681        }
8682    }
8683
8684    /**
8685     * This is called when the view is detached from a window.  At this point it
8686     * no longer has a surface for drawing.
8687     *
8688     * @see #onAttachedToWindow()
8689     */
8690    protected void onDetachedFromWindow() {
8691        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
8692
8693        removeUnsetPressCallback();
8694        removeLongPressCallback();
8695        removePerformClickCallback();
8696
8697        destroyDrawingCache();
8698
8699        if (mHardwareLayer != null) {
8700            mHardwareLayer.destroy();
8701            mHardwareLayer = null;
8702        }
8703
8704        if (mDisplayList != null) {
8705            mDisplayList.invalidate();
8706        }
8707
8708        if (mAttachInfo != null) {
8709            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
8710            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
8711        }
8712
8713        mCurrentAnimation = null;
8714    }
8715
8716    /**
8717     * @return The number of times this view has been attached to a window
8718     */
8719    protected int getWindowAttachCount() {
8720        return mWindowAttachCount;
8721    }
8722
8723    /**
8724     * Retrieve a unique token identifying the window this view is attached to.
8725     * @return Return the window's token for use in
8726     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
8727     */
8728    public IBinder getWindowToken() {
8729        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
8730    }
8731
8732    /**
8733     * Retrieve a unique token identifying the top-level "real" window of
8734     * the window that this view is attached to.  That is, this is like
8735     * {@link #getWindowToken}, except if the window this view in is a panel
8736     * window (attached to another containing window), then the token of
8737     * the containing window is returned instead.
8738     *
8739     * @return Returns the associated window token, either
8740     * {@link #getWindowToken()} or the containing window's token.
8741     */
8742    public IBinder getApplicationWindowToken() {
8743        AttachInfo ai = mAttachInfo;
8744        if (ai != null) {
8745            IBinder appWindowToken = ai.mPanelParentWindowToken;
8746            if (appWindowToken == null) {
8747                appWindowToken = ai.mWindowToken;
8748            }
8749            return appWindowToken;
8750        }
8751        return null;
8752    }
8753
8754    /**
8755     * Retrieve private session object this view hierarchy is using to
8756     * communicate with the window manager.
8757     * @return the session object to communicate with the window manager
8758     */
8759    /*package*/ IWindowSession getWindowSession() {
8760        return mAttachInfo != null ? mAttachInfo.mSession : null;
8761    }
8762
8763    /**
8764     * @param info the {@link android.view.View.AttachInfo} to associated with
8765     *        this view
8766     */
8767    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
8768        //System.out.println("Attached! " + this);
8769        mAttachInfo = info;
8770        mWindowAttachCount++;
8771        // We will need to evaluate the drawable state at least once.
8772        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
8773        if (mFloatingTreeObserver != null) {
8774            info.mTreeObserver.merge(mFloatingTreeObserver);
8775            mFloatingTreeObserver = null;
8776        }
8777        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
8778            mAttachInfo.mScrollContainers.add(this);
8779            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
8780        }
8781        performCollectViewAttributes(visibility);
8782        onAttachedToWindow();
8783
8784        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
8785                mOnAttachStateChangeListeners;
8786        if (listeners != null && listeners.size() > 0) {
8787            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
8788            // perform the dispatching. The iterator is a safe guard against listeners that
8789            // could mutate the list by calling the various add/remove methods. This prevents
8790            // the array from being modified while we iterate it.
8791            for (OnAttachStateChangeListener listener : listeners) {
8792                listener.onViewAttachedToWindow(this);
8793            }
8794        }
8795
8796        int vis = info.mWindowVisibility;
8797        if (vis != GONE) {
8798            onWindowVisibilityChanged(vis);
8799        }
8800        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
8801            // If nobody has evaluated the drawable state yet, then do it now.
8802            refreshDrawableState();
8803        }
8804    }
8805
8806    void dispatchDetachedFromWindow() {
8807        AttachInfo info = mAttachInfo;
8808        if (info != null) {
8809            int vis = info.mWindowVisibility;
8810            if (vis != GONE) {
8811                onWindowVisibilityChanged(GONE);
8812            }
8813        }
8814
8815        onDetachedFromWindow();
8816
8817        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
8818                mOnAttachStateChangeListeners;
8819        if (listeners != null && listeners.size() > 0) {
8820            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
8821            // perform the dispatching. The iterator is a safe guard against listeners that
8822            // could mutate the list by calling the various add/remove methods. This prevents
8823            // the array from being modified while we iterate it.
8824            for (OnAttachStateChangeListener listener : listeners) {
8825                listener.onViewDetachedFromWindow(this);
8826            }
8827        }
8828
8829        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
8830            mAttachInfo.mScrollContainers.remove(this);
8831            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
8832        }
8833
8834        mAttachInfo = null;
8835    }
8836
8837    /**
8838     * Store this view hierarchy's frozen state into the given container.
8839     *
8840     * @param container The SparseArray in which to save the view's state.
8841     *
8842     * @see #restoreHierarchyState(android.util.SparseArray)
8843     * @see #dispatchSaveInstanceState(android.util.SparseArray)
8844     * @see #onSaveInstanceState()
8845     */
8846    public void saveHierarchyState(SparseArray<Parcelable> container) {
8847        dispatchSaveInstanceState(container);
8848    }
8849
8850    /**
8851     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
8852     * this view and its children. May be overridden to modify how freezing happens to a
8853     * view's children; for example, some views may want to not store state for their children.
8854     *
8855     * @param container The SparseArray in which to save the view's state.
8856     *
8857     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
8858     * @see #saveHierarchyState(android.util.SparseArray)
8859     * @see #onSaveInstanceState()
8860     */
8861    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
8862        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
8863            mPrivateFlags &= ~SAVE_STATE_CALLED;
8864            Parcelable state = onSaveInstanceState();
8865            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
8866                throw new IllegalStateException(
8867                        "Derived class did not call super.onSaveInstanceState()");
8868            }
8869            if (state != null) {
8870                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
8871                // + ": " + state);
8872                container.put(mID, state);
8873            }
8874        }
8875    }
8876
8877    /**
8878     * Hook allowing a view to generate a representation of its internal state
8879     * that can later be used to create a new instance with that same state.
8880     * This state should only contain information that is not persistent or can
8881     * not be reconstructed later. For example, you will never store your
8882     * current position on screen because that will be computed again when a
8883     * new instance of the view is placed in its view hierarchy.
8884     * <p>
8885     * Some examples of things you may store here: the current cursor position
8886     * in a text view (but usually not the text itself since that is stored in a
8887     * content provider or other persistent storage), the currently selected
8888     * item in a list view.
8889     *
8890     * @return Returns a Parcelable object containing the view's current dynamic
8891     *         state, or null if there is nothing interesting to save. The
8892     *         default implementation returns null.
8893     * @see #onRestoreInstanceState(android.os.Parcelable)
8894     * @see #saveHierarchyState(android.util.SparseArray)
8895     * @see #dispatchSaveInstanceState(android.util.SparseArray)
8896     * @see #setSaveEnabled(boolean)
8897     */
8898    protected Parcelable onSaveInstanceState() {
8899        mPrivateFlags |= SAVE_STATE_CALLED;
8900        return BaseSavedState.EMPTY_STATE;
8901    }
8902
8903    /**
8904     * Restore this view hierarchy's frozen state from the given container.
8905     *
8906     * @param container The SparseArray which holds previously frozen states.
8907     *
8908     * @see #saveHierarchyState(android.util.SparseArray)
8909     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
8910     * @see #onRestoreInstanceState(android.os.Parcelable)
8911     */
8912    public void restoreHierarchyState(SparseArray<Parcelable> container) {
8913        dispatchRestoreInstanceState(container);
8914    }
8915
8916    /**
8917     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
8918     * state for this view and its children. May be overridden to modify how restoring
8919     * happens to a view's children; for example, some views may want to not store state
8920     * for their children.
8921     *
8922     * @param container The SparseArray which holds previously saved state.
8923     *
8924     * @see #dispatchSaveInstanceState(android.util.SparseArray)
8925     * @see #restoreHierarchyState(android.util.SparseArray)
8926     * @see #onRestoreInstanceState(android.os.Parcelable)
8927     */
8928    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
8929        if (mID != NO_ID) {
8930            Parcelable state = container.get(mID);
8931            if (state != null) {
8932                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
8933                // + ": " + state);
8934                mPrivateFlags &= ~SAVE_STATE_CALLED;
8935                onRestoreInstanceState(state);
8936                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
8937                    throw new IllegalStateException(
8938                            "Derived class did not call super.onRestoreInstanceState()");
8939                }
8940            }
8941        }
8942    }
8943
8944    /**
8945     * Hook allowing a view to re-apply a representation of its internal state that had previously
8946     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
8947     * null state.
8948     *
8949     * @param state The frozen state that had previously been returned by
8950     *        {@link #onSaveInstanceState}.
8951     *
8952     * @see #onSaveInstanceState()
8953     * @see #restoreHierarchyState(android.util.SparseArray)
8954     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
8955     */
8956    protected void onRestoreInstanceState(Parcelable state) {
8957        mPrivateFlags |= SAVE_STATE_CALLED;
8958        if (state != BaseSavedState.EMPTY_STATE && state != null) {
8959            throw new IllegalArgumentException("Wrong state class, expecting View State but "
8960                    + "received " + state.getClass().toString() + " instead. This usually happens "
8961                    + "when two views of different type have the same id in the same hierarchy. "
8962                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
8963                    + "other views do not use the same id.");
8964        }
8965    }
8966
8967    /**
8968     * <p>Return the time at which the drawing of the view hierarchy started.</p>
8969     *
8970     * @return the drawing start time in milliseconds
8971     */
8972    public long getDrawingTime() {
8973        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
8974    }
8975
8976    /**
8977     * <p>Enables or disables the duplication of the parent's state into this view. When
8978     * duplication is enabled, this view gets its drawable state from its parent rather
8979     * than from its own internal properties.</p>
8980     *
8981     * <p>Note: in the current implementation, setting this property to true after the
8982     * view was added to a ViewGroup might have no effect at all. This property should
8983     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
8984     *
8985     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
8986     * property is enabled, an exception will be thrown.</p>
8987     *
8988     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
8989     * parent, these states should not be affected by this method.</p>
8990     *
8991     * @param enabled True to enable duplication of the parent's drawable state, false
8992     *                to disable it.
8993     *
8994     * @see #getDrawableState()
8995     * @see #isDuplicateParentStateEnabled()
8996     */
8997    public void setDuplicateParentStateEnabled(boolean enabled) {
8998        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
8999    }
9000
9001    /**
9002     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9003     *
9004     * @return True if this view's drawable state is duplicated from the parent,
9005     *         false otherwise
9006     *
9007     * @see #getDrawableState()
9008     * @see #setDuplicateParentStateEnabled(boolean)
9009     */
9010    public boolean isDuplicateParentStateEnabled() {
9011        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9012    }
9013
9014    /**
9015     * <p>Specifies the type of layer backing this view. The layer can be
9016     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9017     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
9018     *
9019     * <p>A layer is associated with an optional {@link android.graphics.Paint}
9020     * instance that controls how the layer is composed on screen. The following
9021     * properties of the paint are taken into account when composing the layer:</p>
9022     * <ul>
9023     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
9024     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
9025     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
9026     * </ul>
9027     *
9028     * <p>If this view has an alpha value set to < 1.0 by calling
9029     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
9030     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
9031     * equivalent to setting a hardware layer on this view and providing a paint with
9032     * the desired alpha value.<p>
9033     *
9034     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
9035     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
9036     * for more information on when and how to use layers.</p>
9037     *
9038     * @param layerType The ype of layer to use with this view, must be one of
9039     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9040     *        {@link #LAYER_TYPE_HARDWARE}
9041     * @param paint The paint used to compose the layer. This argument is optional
9042     *        and can be null. It is ignored when the layer type is
9043     *        {@link #LAYER_TYPE_NONE}
9044     *
9045     * @see #getLayerType()
9046     * @see #LAYER_TYPE_NONE
9047     * @see #LAYER_TYPE_SOFTWARE
9048     * @see #LAYER_TYPE_HARDWARE
9049     * @see #setAlpha(float)
9050     *
9051     * @attr ref android.R.styleable#View_layerType
9052     */
9053    public void setLayerType(int layerType, Paint paint) {
9054        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
9055            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
9056                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
9057        }
9058
9059        if (layerType == mLayerType) {
9060            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
9061                mLayerPaint = paint == null ? new Paint() : paint;
9062                invalidateParentCaches();
9063                invalidate(true);
9064            }
9065            return;
9066        }
9067
9068        // Destroy any previous software drawing cache if needed
9069        switch (mLayerType) {
9070            case LAYER_TYPE_HARDWARE:
9071                if (mHardwareLayer != null) {
9072                    mHardwareLayer.destroy();
9073                    mHardwareLayer = null;
9074                }
9075                // fall through - unaccelerated views may use software layer mechanism instead
9076            case LAYER_TYPE_SOFTWARE:
9077                if (mDrawingCache != null) {
9078                    mDrawingCache.recycle();
9079                    mDrawingCache = null;
9080                }
9081
9082                if (mUnscaledDrawingCache != null) {
9083                    mUnscaledDrawingCache.recycle();
9084                    mUnscaledDrawingCache = null;
9085                }
9086                break;
9087            default:
9088                break;
9089        }
9090
9091        mLayerType = layerType;
9092        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
9093        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
9094        mLocalDirtyRect = layerDisabled ? null : new Rect();
9095
9096        invalidateParentCaches();
9097        invalidate(true);
9098    }
9099
9100    /**
9101     * Indicates what type of layer is currently associated with this view. By default
9102     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
9103     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
9104     * for more information on the different types of layers.
9105     *
9106     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9107     *         {@link #LAYER_TYPE_HARDWARE}
9108     *
9109     * @see #setLayerType(int, android.graphics.Paint)
9110     * @see #buildLayer()
9111     * @see #LAYER_TYPE_NONE
9112     * @see #LAYER_TYPE_SOFTWARE
9113     * @see #LAYER_TYPE_HARDWARE
9114     */
9115    public int getLayerType() {
9116        return mLayerType;
9117    }
9118
9119    /**
9120     * Forces this view's layer to be created and this view to be rendered
9121     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
9122     * invoking this method will have no effect.
9123     *
9124     * This method can for instance be used to render a view into its layer before
9125     * starting an animation. If this view is complex, rendering into the layer
9126     * before starting the animation will avoid skipping frames.
9127     *
9128     * @throws IllegalStateException If this view is not attached to a window
9129     *
9130     * @see #setLayerType(int, android.graphics.Paint)
9131     */
9132    public void buildLayer() {
9133        if (mLayerType == LAYER_TYPE_NONE) return;
9134
9135        if (mAttachInfo == null) {
9136            throw new IllegalStateException("This view must be attached to a window first");
9137        }
9138
9139        switch (mLayerType) {
9140            case LAYER_TYPE_HARDWARE:
9141                getHardwareLayer();
9142                break;
9143            case LAYER_TYPE_SOFTWARE:
9144                buildDrawingCache(true);
9145                break;
9146        }
9147    }
9148
9149    /**
9150     * <p>Returns a hardware layer that can be used to draw this view again
9151     * without executing its draw method.</p>
9152     *
9153     * @return A HardwareLayer ready to render, or null if an error occurred.
9154     */
9155    HardwareLayer getHardwareLayer() {
9156        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null) {
9157            return null;
9158        }
9159
9160        final int width = mRight - mLeft;
9161        final int height = mBottom - mTop;
9162
9163        if (width == 0 || height == 0) {
9164            return null;
9165        }
9166
9167        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
9168            if (mHardwareLayer == null) {
9169                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
9170                        width, height, isOpaque());
9171                mLocalDirtyRect.setEmpty();
9172            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
9173                mHardwareLayer.resize(width, height);
9174                mLocalDirtyRect.setEmpty();
9175            }
9176
9177            Canvas currentCanvas = mAttachInfo.mHardwareCanvas;
9178            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
9179            mAttachInfo.mHardwareCanvas = canvas;
9180            try {
9181                canvas.setViewport(width, height);
9182                canvas.onPreDraw(mLocalDirtyRect);
9183                mLocalDirtyRect.setEmpty();
9184
9185                final int restoreCount = canvas.save();
9186
9187                computeScroll();
9188                canvas.translate(-mScrollX, -mScrollY);
9189
9190                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9191
9192                // Fast path for layouts with no backgrounds
9193                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9194                    mPrivateFlags &= ~DIRTY_MASK;
9195                    dispatchDraw(canvas);
9196                } else {
9197                    draw(canvas);
9198                }
9199
9200                canvas.restoreToCount(restoreCount);
9201            } finally {
9202                canvas.onPostDraw();
9203                mHardwareLayer.end(currentCanvas);
9204                mAttachInfo.mHardwareCanvas = currentCanvas;
9205            }
9206        }
9207
9208        return mHardwareLayer;
9209    }
9210
9211    /**
9212     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
9213     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
9214     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
9215     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
9216     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
9217     * null.</p>
9218     *
9219     * <p>Enabling the drawing cache is similar to
9220     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
9221     * acceleration is turned off. When hardware acceleration is turned on, enabling the
9222     * drawing cache has no effect on rendering because the system uses a different mechanism
9223     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
9224     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
9225     * for information on how to enable software and hardware layers.</p>
9226     *
9227     * <p>This API can be used to manually generate
9228     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
9229     * {@link #getDrawingCache()}.</p>
9230     *
9231     * @param enabled true to enable the drawing cache, false otherwise
9232     *
9233     * @see #isDrawingCacheEnabled()
9234     * @see #getDrawingCache()
9235     * @see #buildDrawingCache()
9236     * @see #setLayerType(int, android.graphics.Paint)
9237     */
9238    public void setDrawingCacheEnabled(boolean enabled) {
9239        mCachingFailed = false;
9240        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
9241    }
9242
9243    /**
9244     * <p>Indicates whether the drawing cache is enabled for this view.</p>
9245     *
9246     * @return true if the drawing cache is enabled
9247     *
9248     * @see #setDrawingCacheEnabled(boolean)
9249     * @see #getDrawingCache()
9250     */
9251    @ViewDebug.ExportedProperty(category = "drawing")
9252    public boolean isDrawingCacheEnabled() {
9253        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
9254    }
9255
9256    /**
9257     * Debugging utility which recursively outputs the dirty state of a view and its
9258     * descendants.
9259     *
9260     * @hide
9261     */
9262    @SuppressWarnings({"UnusedDeclaration"})
9263    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
9264        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
9265                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
9266                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
9267                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
9268        if (clear) {
9269            mPrivateFlags &= clearMask;
9270        }
9271        if (this instanceof ViewGroup) {
9272            ViewGroup parent = (ViewGroup) this;
9273            final int count = parent.getChildCount();
9274            for (int i = 0; i < count; i++) {
9275                final View child = parent.getChildAt(i);
9276                child.outputDirtyFlags(indent + "  ", clear, clearMask);
9277            }
9278        }
9279    }
9280
9281    /**
9282     * This method is used by ViewGroup to cause its children to restore or recreate their
9283     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
9284     * to recreate its own display list, which would happen if it went through the normal
9285     * draw/dispatchDraw mechanisms.
9286     *
9287     * @hide
9288     */
9289    protected void dispatchGetDisplayList() {}
9290
9291    /**
9292     * A view that is not attached or hardware accelerated cannot create a display list.
9293     * This method checks these conditions and returns the appropriate result.
9294     *
9295     * @return true if view has the ability to create a display list, false otherwise.
9296     *
9297     * @hide
9298     */
9299    public boolean canHaveDisplayList() {
9300        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
9301    }
9302
9303    /**
9304     * <p>Returns a display list that can be used to draw this view again
9305     * without executing its draw method.</p>
9306     *
9307     * @return A DisplayList ready to replay, or null if caching is not enabled.
9308     *
9309     * @hide
9310     */
9311    public DisplayList getDisplayList() {
9312        if (!canHaveDisplayList()) {
9313            return null;
9314        }
9315
9316        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
9317                mDisplayList == null || !mDisplayList.isValid() ||
9318                mRecreateDisplayList)) {
9319            // Don't need to recreate the display list, just need to tell our
9320            // children to restore/recreate theirs
9321            if (mDisplayList != null && mDisplayList.isValid() &&
9322                    !mRecreateDisplayList) {
9323                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9324                mPrivateFlags &= ~DIRTY_MASK;
9325                dispatchGetDisplayList();
9326
9327                return mDisplayList;
9328            }
9329
9330            // If we got here, we're recreating it. Mark it as such to ensure that
9331            // we copy in child display lists into ours in drawChild()
9332            mRecreateDisplayList = true;
9333            if (mDisplayList == null) {
9334                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this);
9335                // If we're creating a new display list, make sure our parent gets invalidated
9336                // since they will need to recreate their display list to account for this
9337                // new child display list.
9338                invalidateParentCaches();
9339            }
9340
9341            final HardwareCanvas canvas = mDisplayList.start();
9342            try {
9343                int width = mRight - mLeft;
9344                int height = mBottom - mTop;
9345
9346                canvas.setViewport(width, height);
9347                // The dirty rect should always be null for a display list
9348                canvas.onPreDraw(null);
9349
9350                final int restoreCount = canvas.save();
9351
9352                computeScroll();
9353                canvas.translate(-mScrollX, -mScrollY);
9354                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9355
9356                // Fast path for layouts with no backgrounds
9357                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9358                    mPrivateFlags &= ~DIRTY_MASK;
9359                    dispatchDraw(canvas);
9360                } else {
9361                    draw(canvas);
9362                }
9363
9364                canvas.restoreToCount(restoreCount);
9365            } finally {
9366                canvas.onPostDraw();
9367
9368                mDisplayList.end();
9369            }
9370        } else {
9371            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9372            mPrivateFlags &= ~DIRTY_MASK;
9373        }
9374
9375        return mDisplayList;
9376    }
9377
9378    /**
9379     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
9380     *
9381     * @return A non-scaled bitmap representing this view or null if cache is disabled.
9382     *
9383     * @see #getDrawingCache(boolean)
9384     */
9385    public Bitmap getDrawingCache() {
9386        return getDrawingCache(false);
9387    }
9388
9389    /**
9390     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
9391     * is null when caching is disabled. If caching is enabled and the cache is not ready,
9392     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
9393     * draw from the cache when the cache is enabled. To benefit from the cache, you must
9394     * request the drawing cache by calling this method and draw it on screen if the
9395     * returned bitmap is not null.</p>
9396     *
9397     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
9398     * this method will create a bitmap of the same size as this view. Because this bitmap
9399     * will be drawn scaled by the parent ViewGroup, the result on screen might show
9400     * scaling artifacts. To avoid such artifacts, you should call this method by setting
9401     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
9402     * size than the view. This implies that your application must be able to handle this
9403     * size.</p>
9404     *
9405     * @param autoScale Indicates whether the generated bitmap should be scaled based on
9406     *        the current density of the screen when the application is in compatibility
9407     *        mode.
9408     *
9409     * @return A bitmap representing this view or null if cache is disabled.
9410     *
9411     * @see #setDrawingCacheEnabled(boolean)
9412     * @see #isDrawingCacheEnabled()
9413     * @see #buildDrawingCache(boolean)
9414     * @see #destroyDrawingCache()
9415     */
9416    public Bitmap getDrawingCache(boolean autoScale) {
9417        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
9418            return null;
9419        }
9420        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
9421            buildDrawingCache(autoScale);
9422        }
9423        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
9424    }
9425
9426    /**
9427     * <p>Frees the resources used by the drawing cache. If you call
9428     * {@link #buildDrawingCache()} manually without calling
9429     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
9430     * should cleanup the cache with this method afterwards.</p>
9431     *
9432     * @see #setDrawingCacheEnabled(boolean)
9433     * @see #buildDrawingCache()
9434     * @see #getDrawingCache()
9435     */
9436    public void destroyDrawingCache() {
9437        if (mDrawingCache != null) {
9438            mDrawingCache.recycle();
9439            mDrawingCache = null;
9440        }
9441        if (mUnscaledDrawingCache != null) {
9442            mUnscaledDrawingCache.recycle();
9443            mUnscaledDrawingCache = null;
9444        }
9445    }
9446
9447    /**
9448     * Setting a solid background color for the drawing cache's bitmaps will improve
9449     * perfromance and memory usage. Note, though that this should only be used if this
9450     * view will always be drawn on top of a solid color.
9451     *
9452     * @param color The background color to use for the drawing cache's bitmap
9453     *
9454     * @see #setDrawingCacheEnabled(boolean)
9455     * @see #buildDrawingCache()
9456     * @see #getDrawingCache()
9457     */
9458    public void setDrawingCacheBackgroundColor(int color) {
9459        if (color != mDrawingCacheBackgroundColor) {
9460            mDrawingCacheBackgroundColor = color;
9461            mPrivateFlags &= ~DRAWING_CACHE_VALID;
9462        }
9463    }
9464
9465    /**
9466     * @see #setDrawingCacheBackgroundColor(int)
9467     *
9468     * @return The background color to used for the drawing cache's bitmap
9469     */
9470    public int getDrawingCacheBackgroundColor() {
9471        return mDrawingCacheBackgroundColor;
9472    }
9473
9474    /**
9475     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
9476     *
9477     * @see #buildDrawingCache(boolean)
9478     */
9479    public void buildDrawingCache() {
9480        buildDrawingCache(false);
9481    }
9482
9483    /**
9484     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
9485     *
9486     * <p>If you call {@link #buildDrawingCache()} manually without calling
9487     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
9488     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
9489     *
9490     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
9491     * this method will create a bitmap of the same size as this view. Because this bitmap
9492     * will be drawn scaled by the parent ViewGroup, the result on screen might show
9493     * scaling artifacts. To avoid such artifacts, you should call this method by setting
9494     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
9495     * size than the view. This implies that your application must be able to handle this
9496     * size.</p>
9497     *
9498     * <p>You should avoid calling this method when hardware acceleration is enabled. If
9499     * you do not need the drawing cache bitmap, calling this method will increase memory
9500     * usage and cause the view to be rendered in software once, thus negatively impacting
9501     * performance.</p>
9502     *
9503     * @see #getDrawingCache()
9504     * @see #destroyDrawingCache()
9505     */
9506    public void buildDrawingCache(boolean autoScale) {
9507        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
9508                mDrawingCache == null : mUnscaledDrawingCache == null)) {
9509            mCachingFailed = false;
9510
9511            if (ViewDebug.TRACE_HIERARCHY) {
9512                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
9513            }
9514
9515            int width = mRight - mLeft;
9516            int height = mBottom - mTop;
9517
9518            final AttachInfo attachInfo = mAttachInfo;
9519            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
9520
9521            if (autoScale && scalingRequired) {
9522                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
9523                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
9524            }
9525
9526            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
9527            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
9528            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
9529
9530            if (width <= 0 || height <= 0 ||
9531                     // Projected bitmap size in bytes
9532                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
9533                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
9534                destroyDrawingCache();
9535                mCachingFailed = true;
9536                return;
9537            }
9538
9539            boolean clear = true;
9540            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
9541
9542            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
9543                Bitmap.Config quality;
9544                if (!opaque) {
9545                    // Never pick ARGB_4444 because it looks awful
9546                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
9547                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
9548                        case DRAWING_CACHE_QUALITY_AUTO:
9549                            quality = Bitmap.Config.ARGB_8888;
9550                            break;
9551                        case DRAWING_CACHE_QUALITY_LOW:
9552                            quality = Bitmap.Config.ARGB_8888;
9553                            break;
9554                        case DRAWING_CACHE_QUALITY_HIGH:
9555                            quality = Bitmap.Config.ARGB_8888;
9556                            break;
9557                        default:
9558                            quality = Bitmap.Config.ARGB_8888;
9559                            break;
9560                    }
9561                } else {
9562                    // Optimization for translucent windows
9563                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
9564                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
9565                }
9566
9567                // Try to cleanup memory
9568                if (bitmap != null) bitmap.recycle();
9569
9570                try {
9571                    bitmap = Bitmap.createBitmap(width, height, quality);
9572                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
9573                    if (autoScale) {
9574                        mDrawingCache = bitmap;
9575                    } else {
9576                        mUnscaledDrawingCache = bitmap;
9577                    }
9578                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
9579                } catch (OutOfMemoryError e) {
9580                    // If there is not enough memory to create the bitmap cache, just
9581                    // ignore the issue as bitmap caches are not required to draw the
9582                    // view hierarchy
9583                    if (autoScale) {
9584                        mDrawingCache = null;
9585                    } else {
9586                        mUnscaledDrawingCache = null;
9587                    }
9588                    mCachingFailed = true;
9589                    return;
9590                }
9591
9592                clear = drawingCacheBackgroundColor != 0;
9593            }
9594
9595            Canvas canvas;
9596            if (attachInfo != null) {
9597                canvas = attachInfo.mCanvas;
9598                if (canvas == null) {
9599                    canvas = new Canvas();
9600                }
9601                canvas.setBitmap(bitmap);
9602                // Temporarily clobber the cached Canvas in case one of our children
9603                // is also using a drawing cache. Without this, the children would
9604                // steal the canvas by attaching their own bitmap to it and bad, bad
9605                // thing would happen (invisible views, corrupted drawings, etc.)
9606                attachInfo.mCanvas = null;
9607            } else {
9608                // This case should hopefully never or seldom happen
9609                canvas = new Canvas(bitmap);
9610            }
9611
9612            if (clear) {
9613                bitmap.eraseColor(drawingCacheBackgroundColor);
9614            }
9615
9616            computeScroll();
9617            final int restoreCount = canvas.save();
9618
9619            if (autoScale && scalingRequired) {
9620                final float scale = attachInfo.mApplicationScale;
9621                canvas.scale(scale, scale);
9622            }
9623
9624            canvas.translate(-mScrollX, -mScrollY);
9625
9626            mPrivateFlags |= DRAWN;
9627            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
9628                    mLayerType != LAYER_TYPE_NONE) {
9629                mPrivateFlags |= DRAWING_CACHE_VALID;
9630            }
9631
9632            // Fast path for layouts with no backgrounds
9633            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9634                if (ViewDebug.TRACE_HIERARCHY) {
9635                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
9636                }
9637                mPrivateFlags &= ~DIRTY_MASK;
9638                dispatchDraw(canvas);
9639            } else {
9640                draw(canvas);
9641            }
9642
9643            canvas.restoreToCount(restoreCount);
9644
9645            if (attachInfo != null) {
9646                // Restore the cached Canvas for our siblings
9647                attachInfo.mCanvas = canvas;
9648            }
9649        }
9650    }
9651
9652    /**
9653     * Create a snapshot of the view into a bitmap.  We should probably make
9654     * some form of this public, but should think about the API.
9655     */
9656    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
9657        int width = mRight - mLeft;
9658        int height = mBottom - mTop;
9659
9660        final AttachInfo attachInfo = mAttachInfo;
9661        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
9662        width = (int) ((width * scale) + 0.5f);
9663        height = (int) ((height * scale) + 0.5f);
9664
9665        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
9666        if (bitmap == null) {
9667            throw new OutOfMemoryError();
9668        }
9669
9670        bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
9671
9672        Canvas canvas;
9673        if (attachInfo != null) {
9674            canvas = attachInfo.mCanvas;
9675            if (canvas == null) {
9676                canvas = new Canvas();
9677            }
9678            canvas.setBitmap(bitmap);
9679            // Temporarily clobber the cached Canvas in case one of our children
9680            // is also using a drawing cache. Without this, the children would
9681            // steal the canvas by attaching their own bitmap to it and bad, bad
9682            // things would happen (invisible views, corrupted drawings, etc.)
9683            attachInfo.mCanvas = null;
9684        } else {
9685            // This case should hopefully never or seldom happen
9686            canvas = new Canvas(bitmap);
9687        }
9688
9689        if ((backgroundColor & 0xff000000) != 0) {
9690            bitmap.eraseColor(backgroundColor);
9691        }
9692
9693        computeScroll();
9694        final int restoreCount = canvas.save();
9695        canvas.scale(scale, scale);
9696        canvas.translate(-mScrollX, -mScrollY);
9697
9698        // Temporarily remove the dirty mask
9699        int flags = mPrivateFlags;
9700        mPrivateFlags &= ~DIRTY_MASK;
9701
9702        // Fast path for layouts with no backgrounds
9703        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9704            dispatchDraw(canvas);
9705        } else {
9706            draw(canvas);
9707        }
9708
9709        mPrivateFlags = flags;
9710
9711        canvas.restoreToCount(restoreCount);
9712
9713        if (attachInfo != null) {
9714            // Restore the cached Canvas for our siblings
9715            attachInfo.mCanvas = canvas;
9716        }
9717
9718        return bitmap;
9719    }
9720
9721    /**
9722     * Indicates whether this View is currently in edit mode. A View is usually
9723     * in edit mode when displayed within a developer tool. For instance, if
9724     * this View is being drawn by a visual user interface builder, this method
9725     * should return true.
9726     *
9727     * Subclasses should check the return value of this method to provide
9728     * different behaviors if their normal behavior might interfere with the
9729     * host environment. For instance: the class spawns a thread in its
9730     * constructor, the drawing code relies on device-specific features, etc.
9731     *
9732     * This method is usually checked in the drawing code of custom widgets.
9733     *
9734     * @return True if this View is in edit mode, false otherwise.
9735     */
9736    public boolean isInEditMode() {
9737        return false;
9738    }
9739
9740    /**
9741     * If the View draws content inside its padding and enables fading edges,
9742     * it needs to support padding offsets. Padding offsets are added to the
9743     * fading edges to extend the length of the fade so that it covers pixels
9744     * drawn inside the padding.
9745     *
9746     * Subclasses of this class should override this method if they need
9747     * to draw content inside the padding.
9748     *
9749     * @return True if padding offset must be applied, false otherwise.
9750     *
9751     * @see #getLeftPaddingOffset()
9752     * @see #getRightPaddingOffset()
9753     * @see #getTopPaddingOffset()
9754     * @see #getBottomPaddingOffset()
9755     *
9756     * @since CURRENT
9757     */
9758    protected boolean isPaddingOffsetRequired() {
9759        return false;
9760    }
9761
9762    /**
9763     * Amount by which to extend the left fading region. Called only when
9764     * {@link #isPaddingOffsetRequired()} returns true.
9765     *
9766     * @return The left padding offset in pixels.
9767     *
9768     * @see #isPaddingOffsetRequired()
9769     *
9770     * @since CURRENT
9771     */
9772    protected int getLeftPaddingOffset() {
9773        return 0;
9774    }
9775
9776    /**
9777     * Amount by which to extend the right fading region. Called only when
9778     * {@link #isPaddingOffsetRequired()} returns true.
9779     *
9780     * @return The right padding offset in pixels.
9781     *
9782     * @see #isPaddingOffsetRequired()
9783     *
9784     * @since CURRENT
9785     */
9786    protected int getRightPaddingOffset() {
9787        return 0;
9788    }
9789
9790    /**
9791     * Amount by which to extend the top fading region. Called only when
9792     * {@link #isPaddingOffsetRequired()} returns true.
9793     *
9794     * @return The top padding offset in pixels.
9795     *
9796     * @see #isPaddingOffsetRequired()
9797     *
9798     * @since CURRENT
9799     */
9800    protected int getTopPaddingOffset() {
9801        return 0;
9802    }
9803
9804    /**
9805     * Amount by which to extend the bottom fading region. Called only when
9806     * {@link #isPaddingOffsetRequired()} returns true.
9807     *
9808     * @return The bottom padding offset in pixels.
9809     *
9810     * @see #isPaddingOffsetRequired()
9811     *
9812     * @since CURRENT
9813     */
9814    protected int getBottomPaddingOffset() {
9815        return 0;
9816    }
9817
9818    /**
9819     * <p>Indicates whether this view is attached to an hardware accelerated
9820     * window or not.</p>
9821     *
9822     * <p>Even if this method returns true, it does not mean that every call
9823     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
9824     * accelerated {@link android.graphics.Canvas}. For instance, if this view
9825     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
9826     * window is hardware accelerated,
9827     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
9828     * return false, and this method will return true.</p>
9829     *
9830     * @return True if the view is attached to a window and the window is
9831     *         hardware accelerated; false in any other case.
9832     */
9833    public boolean isHardwareAccelerated() {
9834        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
9835    }
9836
9837    /**
9838     * Manually render this view (and all of its children) to the given Canvas.
9839     * The view must have already done a full layout before this function is
9840     * called.  When implementing a view, implement
9841     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
9842     * If you do need to override this method, call the superclass version.
9843     *
9844     * @param canvas The Canvas to which the View is rendered.
9845     */
9846    public void draw(Canvas canvas) {
9847        if (ViewDebug.TRACE_HIERARCHY) {
9848            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
9849        }
9850
9851        final int privateFlags = mPrivateFlags;
9852        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
9853                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
9854        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
9855
9856        /*
9857         * Draw traversal performs several drawing steps which must be executed
9858         * in the appropriate order:
9859         *
9860         *      1. Draw the background
9861         *      2. If necessary, save the canvas' layers to prepare for fading
9862         *      3. Draw view's content
9863         *      4. Draw children
9864         *      5. If necessary, draw the fading edges and restore layers
9865         *      6. Draw decorations (scrollbars for instance)
9866         */
9867
9868        // Step 1, draw the background, if needed
9869        int saveCount;
9870
9871        if (!dirtyOpaque) {
9872            final Drawable background = mBGDrawable;
9873            if (background != null) {
9874                final int scrollX = mScrollX;
9875                final int scrollY = mScrollY;
9876
9877                if (mBackgroundSizeChanged) {
9878                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
9879                    mBackgroundSizeChanged = false;
9880                }
9881
9882                if ((scrollX | scrollY) == 0) {
9883                    background.draw(canvas);
9884                } else {
9885                    canvas.translate(scrollX, scrollY);
9886                    background.draw(canvas);
9887                    canvas.translate(-scrollX, -scrollY);
9888                }
9889            }
9890        }
9891
9892        // skip step 2 & 5 if possible (common case)
9893        final int viewFlags = mViewFlags;
9894        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
9895        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
9896        if (!verticalEdges && !horizontalEdges) {
9897            // Step 3, draw the content
9898            if (!dirtyOpaque) onDraw(canvas);
9899
9900            // Step 4, draw the children
9901            dispatchDraw(canvas);
9902
9903            // Step 6, draw decorations (scrollbars)
9904            onDrawScrollBars(canvas);
9905
9906            // we're done...
9907            return;
9908        }
9909
9910        /*
9911         * Here we do the full fledged routine...
9912         * (this is an uncommon case where speed matters less,
9913         * this is why we repeat some of the tests that have been
9914         * done above)
9915         */
9916
9917        boolean drawTop = false;
9918        boolean drawBottom = false;
9919        boolean drawLeft = false;
9920        boolean drawRight = false;
9921
9922        float topFadeStrength = 0.0f;
9923        float bottomFadeStrength = 0.0f;
9924        float leftFadeStrength = 0.0f;
9925        float rightFadeStrength = 0.0f;
9926
9927        // Step 2, save the canvas' layers
9928        int paddingLeft = mPaddingLeft;
9929        int paddingTop = mPaddingTop;
9930
9931        final boolean offsetRequired = isPaddingOffsetRequired();
9932        if (offsetRequired) {
9933            paddingLeft += getLeftPaddingOffset();
9934            paddingTop += getTopPaddingOffset();
9935        }
9936
9937        int left = mScrollX + paddingLeft;
9938        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
9939        int top = mScrollY + paddingTop;
9940        int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
9941
9942        if (offsetRequired) {
9943            right += getRightPaddingOffset();
9944            bottom += getBottomPaddingOffset();
9945        }
9946
9947        final ScrollabilityCache scrollabilityCache = mScrollCache;
9948        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
9949        int length = (int) fadeHeight;
9950
9951        // clip the fade length if top and bottom fades overlap
9952        // overlapping fades produce odd-looking artifacts
9953        if (verticalEdges && (top + length > bottom - length)) {
9954            length = (bottom - top) / 2;
9955        }
9956
9957        // also clip horizontal fades if necessary
9958        if (horizontalEdges && (left + length > right - length)) {
9959            length = (right - left) / 2;
9960        }
9961
9962        if (verticalEdges) {
9963            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
9964            drawTop = topFadeStrength * fadeHeight > 1.0f;
9965            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
9966            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
9967        }
9968
9969        if (horizontalEdges) {
9970            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
9971            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
9972            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
9973            drawRight = rightFadeStrength * fadeHeight > 1.0f;
9974        }
9975
9976        saveCount = canvas.getSaveCount();
9977
9978        int solidColor = getSolidColor();
9979        if (solidColor == 0) {
9980            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
9981
9982            if (drawTop) {
9983                canvas.saveLayer(left, top, right, top + length, null, flags);
9984            }
9985
9986            if (drawBottom) {
9987                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
9988            }
9989
9990            if (drawLeft) {
9991                canvas.saveLayer(left, top, left + length, bottom, null, flags);
9992            }
9993
9994            if (drawRight) {
9995                canvas.saveLayer(right - length, top, right, bottom, null, flags);
9996            }
9997        } else {
9998            scrollabilityCache.setFadeColor(solidColor);
9999        }
10000
10001        // Step 3, draw the content
10002        if (!dirtyOpaque) onDraw(canvas);
10003
10004        // Step 4, draw the children
10005        dispatchDraw(canvas);
10006
10007        // Step 5, draw the fade effect and restore layers
10008        final Paint p = scrollabilityCache.paint;
10009        final Matrix matrix = scrollabilityCache.matrix;
10010        final Shader fade = scrollabilityCache.shader;
10011
10012        if (drawTop) {
10013            matrix.setScale(1, fadeHeight * topFadeStrength);
10014            matrix.postTranslate(left, top);
10015            fade.setLocalMatrix(matrix);
10016            canvas.drawRect(left, top, right, top + length, p);
10017        }
10018
10019        if (drawBottom) {
10020            matrix.setScale(1, fadeHeight * bottomFadeStrength);
10021            matrix.postRotate(180);
10022            matrix.postTranslate(left, bottom);
10023            fade.setLocalMatrix(matrix);
10024            canvas.drawRect(left, bottom - length, right, bottom, p);
10025        }
10026
10027        if (drawLeft) {
10028            matrix.setScale(1, fadeHeight * leftFadeStrength);
10029            matrix.postRotate(-90);
10030            matrix.postTranslate(left, top);
10031            fade.setLocalMatrix(matrix);
10032            canvas.drawRect(left, top, left + length, bottom, p);
10033        }
10034
10035        if (drawRight) {
10036            matrix.setScale(1, fadeHeight * rightFadeStrength);
10037            matrix.postRotate(90);
10038            matrix.postTranslate(right, top);
10039            fade.setLocalMatrix(matrix);
10040            canvas.drawRect(right - length, top, right, bottom, p);
10041        }
10042
10043        canvas.restoreToCount(saveCount);
10044
10045        // Step 6, draw decorations (scrollbars)
10046        onDrawScrollBars(canvas);
10047    }
10048
10049    /**
10050     * Override this if your view is known to always be drawn on top of a solid color background,
10051     * and needs to draw fading edges. Returning a non-zero color enables the view system to
10052     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
10053     * should be set to 0xFF.
10054     *
10055     * @see #setVerticalFadingEdgeEnabled(boolean)
10056     * @see #setHorizontalFadingEdgeEnabled(boolean)
10057     *
10058     * @return The known solid color background for this view, or 0 if the color may vary
10059     */
10060    @ViewDebug.ExportedProperty(category = "drawing")
10061    public int getSolidColor() {
10062        return 0;
10063    }
10064
10065    /**
10066     * Build a human readable string representation of the specified view flags.
10067     *
10068     * @param flags the view flags to convert to a string
10069     * @return a String representing the supplied flags
10070     */
10071    private static String printFlags(int flags) {
10072        String output = "";
10073        int numFlags = 0;
10074        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
10075            output += "TAKES_FOCUS";
10076            numFlags++;
10077        }
10078
10079        switch (flags & VISIBILITY_MASK) {
10080        case INVISIBLE:
10081            if (numFlags > 0) {
10082                output += " ";
10083            }
10084            output += "INVISIBLE";
10085            // USELESS HERE numFlags++;
10086            break;
10087        case GONE:
10088            if (numFlags > 0) {
10089                output += " ";
10090            }
10091            output += "GONE";
10092            // USELESS HERE numFlags++;
10093            break;
10094        default:
10095            break;
10096        }
10097        return output;
10098    }
10099
10100    /**
10101     * Build a human readable string representation of the specified private
10102     * view flags.
10103     *
10104     * @param privateFlags the private view flags to convert to a string
10105     * @return a String representing the supplied flags
10106     */
10107    private static String printPrivateFlags(int privateFlags) {
10108        String output = "";
10109        int numFlags = 0;
10110
10111        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
10112            output += "WANTS_FOCUS";
10113            numFlags++;
10114        }
10115
10116        if ((privateFlags & FOCUSED) == FOCUSED) {
10117            if (numFlags > 0) {
10118                output += " ";
10119            }
10120            output += "FOCUSED";
10121            numFlags++;
10122        }
10123
10124        if ((privateFlags & SELECTED) == SELECTED) {
10125            if (numFlags > 0) {
10126                output += " ";
10127            }
10128            output += "SELECTED";
10129            numFlags++;
10130        }
10131
10132        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
10133            if (numFlags > 0) {
10134                output += " ";
10135            }
10136            output += "IS_ROOT_NAMESPACE";
10137            numFlags++;
10138        }
10139
10140        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
10141            if (numFlags > 0) {
10142                output += " ";
10143            }
10144            output += "HAS_BOUNDS";
10145            numFlags++;
10146        }
10147
10148        if ((privateFlags & DRAWN) == DRAWN) {
10149            if (numFlags > 0) {
10150                output += " ";
10151            }
10152            output += "DRAWN";
10153            // USELESS HERE numFlags++;
10154        }
10155        return output;
10156    }
10157
10158    /**
10159     * <p>Indicates whether or not this view's layout will be requested during
10160     * the next hierarchy layout pass.</p>
10161     *
10162     * @return true if the layout will be forced during next layout pass
10163     */
10164    public boolean isLayoutRequested() {
10165        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
10166    }
10167
10168    /**
10169     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
10170     * layout attribute and/or the inherited value from the parent.</p>
10171     *
10172     * @return true if the layout is right-to-left.
10173     */
10174    @ViewDebug.ExportedProperty(category = "layout")
10175    public boolean isLayoutRtl() {
10176        return (mPrivateFlags2 & RESOLVED_LAYOUT_RTL) == RESOLVED_LAYOUT_RTL;
10177    }
10178
10179    /**
10180     * Assign a size and position to a view and all of its
10181     * descendants
10182     *
10183     * <p>This is the second phase of the layout mechanism.
10184     * (The first is measuring). In this phase, each parent calls
10185     * layout on all of its children to position them.
10186     * This is typically done using the child measurements
10187     * that were stored in the measure pass().</p>
10188     *
10189     * <p>Derived classes should not override this method.
10190     * Derived classes with children should override
10191     * onLayout. In that method, they should
10192     * call layout on each of their children.</p>
10193     *
10194     * @param l Left position, relative to parent
10195     * @param t Top position, relative to parent
10196     * @param r Right position, relative to parent
10197     * @param b Bottom position, relative to parent
10198     */
10199    @SuppressWarnings({"unchecked"})
10200    public void layout(int l, int t, int r, int b) {
10201        int oldL = mLeft;
10202        int oldT = mTop;
10203        int oldB = mBottom;
10204        int oldR = mRight;
10205        boolean changed = setFrame(l, t, r, b);
10206        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
10207            if (ViewDebug.TRACE_HIERARCHY) {
10208                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
10209            }
10210
10211            onLayout(changed, l, t, r, b);
10212            mPrivateFlags &= ~LAYOUT_REQUIRED;
10213
10214            if (mOnLayoutChangeListeners != null) {
10215                ArrayList<OnLayoutChangeListener> listenersCopy =
10216                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
10217                int numListeners = listenersCopy.size();
10218                for (int i = 0; i < numListeners; ++i) {
10219                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
10220                }
10221            }
10222        }
10223        mPrivateFlags &= ~FORCE_LAYOUT;
10224    }
10225
10226    /**
10227     * Called from layout when this view should
10228     * assign a size and position to each of its children.
10229     *
10230     * Derived classes with children should override
10231     * this method and call layout on each of
10232     * their children.
10233     * @param changed This is a new size or position for this view
10234     * @param left Left position, relative to parent
10235     * @param top Top position, relative to parent
10236     * @param right Right position, relative to parent
10237     * @param bottom Bottom position, relative to parent
10238     */
10239    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
10240    }
10241
10242    /**
10243     * Assign a size and position to this view.
10244     *
10245     * This is called from layout.
10246     *
10247     * @param left Left position, relative to parent
10248     * @param top Top position, relative to parent
10249     * @param right Right position, relative to parent
10250     * @param bottom Bottom position, relative to parent
10251     * @return true if the new size and position are different than the
10252     *         previous ones
10253     * {@hide}
10254     */
10255    protected boolean setFrame(int left, int top, int right, int bottom) {
10256        boolean changed = false;
10257
10258        if (DBG) {
10259            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
10260                    + right + "," + bottom + ")");
10261        }
10262
10263        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
10264            changed = true;
10265
10266            // Remember our drawn bit
10267            int drawn = mPrivateFlags & DRAWN;
10268
10269            // Invalidate our old position
10270            invalidate(true);
10271
10272
10273            int oldWidth = mRight - mLeft;
10274            int oldHeight = mBottom - mTop;
10275
10276            mLeft = left;
10277            mTop = top;
10278            mRight = right;
10279            mBottom = bottom;
10280
10281            mPrivateFlags |= HAS_BOUNDS;
10282
10283            int newWidth = right - left;
10284            int newHeight = bottom - top;
10285
10286            if (newWidth != oldWidth || newHeight != oldHeight) {
10287                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
10288                    // A change in dimension means an auto-centered pivot point changes, too
10289                    mMatrixDirty = true;
10290                }
10291                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
10292            }
10293
10294            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
10295                // If we are visible, force the DRAWN bit to on so that
10296                // this invalidate will go through (at least to our parent).
10297                // This is because someone may have invalidated this view
10298                // before this call to setFrame came in, thereby clearing
10299                // the DRAWN bit.
10300                mPrivateFlags |= DRAWN;
10301                invalidate(true);
10302                // parent display list may need to be recreated based on a change in the bounds
10303                // of any child
10304                invalidateParentCaches();
10305            }
10306
10307            // Reset drawn bit to original value (invalidate turns it off)
10308            mPrivateFlags |= drawn;
10309
10310            mBackgroundSizeChanged = true;
10311        }
10312        return changed;
10313    }
10314
10315    /**
10316     * Finalize inflating a view from XML.  This is called as the last phase
10317     * of inflation, after all child views have been added.
10318     *
10319     * <p>Even if the subclass overrides onFinishInflate, they should always be
10320     * sure to call the super method, so that we get called.
10321     */
10322    protected void onFinishInflate() {
10323    }
10324
10325    /**
10326     * Returns the resources associated with this view.
10327     *
10328     * @return Resources object.
10329     */
10330    public Resources getResources() {
10331        return mResources;
10332    }
10333
10334    /**
10335     * Invalidates the specified Drawable.
10336     *
10337     * @param drawable the drawable to invalidate
10338     */
10339    public void invalidateDrawable(Drawable drawable) {
10340        if (verifyDrawable(drawable)) {
10341            final Rect dirty = drawable.getBounds();
10342            final int scrollX = mScrollX;
10343            final int scrollY = mScrollY;
10344
10345            invalidate(dirty.left + scrollX, dirty.top + scrollY,
10346                    dirty.right + scrollX, dirty.bottom + scrollY);
10347        }
10348    }
10349
10350    /**
10351     * Schedules an action on a drawable to occur at a specified time.
10352     *
10353     * @param who the recipient of the action
10354     * @param what the action to run on the drawable
10355     * @param when the time at which the action must occur. Uses the
10356     *        {@link SystemClock#uptimeMillis} timebase.
10357     */
10358    public void scheduleDrawable(Drawable who, Runnable what, long when) {
10359        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
10360            mAttachInfo.mHandler.postAtTime(what, who, when);
10361        }
10362    }
10363
10364    /**
10365     * Cancels a scheduled action on a drawable.
10366     *
10367     * @param who the recipient of the action
10368     * @param what the action to cancel
10369     */
10370    public void unscheduleDrawable(Drawable who, Runnable what) {
10371        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
10372            mAttachInfo.mHandler.removeCallbacks(what, who);
10373        }
10374    }
10375
10376    /**
10377     * Unschedule any events associated with the given Drawable.  This can be
10378     * used when selecting a new Drawable into a view, so that the previous
10379     * one is completely unscheduled.
10380     *
10381     * @param who The Drawable to unschedule.
10382     *
10383     * @see #drawableStateChanged
10384     */
10385    public void unscheduleDrawable(Drawable who) {
10386        if (mAttachInfo != null) {
10387            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
10388        }
10389    }
10390
10391     /**
10392     * Check if a given Drawable is in RTL layout direction.
10393     *
10394     * @param who the recipient of the action
10395     */
10396    public boolean isLayoutRtl(Drawable who) {
10397        return (who == mBGDrawable) && isLayoutRtl();
10398    }
10399
10400    /**
10401     * If your view subclass is displaying its own Drawable objects, it should
10402     * override this function and return true for any Drawable it is
10403     * displaying.  This allows animations for those drawables to be
10404     * scheduled.
10405     *
10406     * <p>Be sure to call through to the super class when overriding this
10407     * function.
10408     *
10409     * @param who The Drawable to verify.  Return true if it is one you are
10410     *            displaying, else return the result of calling through to the
10411     *            super class.
10412     *
10413     * @return boolean If true than the Drawable is being displayed in the
10414     *         view; else false and it is not allowed to animate.
10415     *
10416     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
10417     * @see #drawableStateChanged()
10418     */
10419    protected boolean verifyDrawable(Drawable who) {
10420        return who == mBGDrawable;
10421    }
10422
10423    /**
10424     * This function is called whenever the state of the view changes in such
10425     * a way that it impacts the state of drawables being shown.
10426     *
10427     * <p>Be sure to call through to the superclass when overriding this
10428     * function.
10429     *
10430     * @see Drawable#setState(int[])
10431     */
10432    protected void drawableStateChanged() {
10433        Drawable d = mBGDrawable;
10434        if (d != null && d.isStateful()) {
10435            d.setState(getDrawableState());
10436        }
10437    }
10438
10439    /**
10440     * Call this to force a view to update its drawable state. This will cause
10441     * drawableStateChanged to be called on this view. Views that are interested
10442     * in the new state should call getDrawableState.
10443     *
10444     * @see #drawableStateChanged
10445     * @see #getDrawableState
10446     */
10447    public void refreshDrawableState() {
10448        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
10449        drawableStateChanged();
10450
10451        ViewParent parent = mParent;
10452        if (parent != null) {
10453            parent.childDrawableStateChanged(this);
10454        }
10455    }
10456
10457    /**
10458     * Return an array of resource IDs of the drawable states representing the
10459     * current state of the view.
10460     *
10461     * @return The current drawable state
10462     *
10463     * @see Drawable#setState(int[])
10464     * @see #drawableStateChanged()
10465     * @see #onCreateDrawableState(int)
10466     */
10467    public final int[] getDrawableState() {
10468        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
10469            return mDrawableState;
10470        } else {
10471            mDrawableState = onCreateDrawableState(0);
10472            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
10473            return mDrawableState;
10474        }
10475    }
10476
10477    /**
10478     * Generate the new {@link android.graphics.drawable.Drawable} state for
10479     * this view. This is called by the view
10480     * system when the cached Drawable state is determined to be invalid.  To
10481     * retrieve the current state, you should use {@link #getDrawableState}.
10482     *
10483     * @param extraSpace if non-zero, this is the number of extra entries you
10484     * would like in the returned array in which you can place your own
10485     * states.
10486     *
10487     * @return Returns an array holding the current {@link Drawable} state of
10488     * the view.
10489     *
10490     * @see #mergeDrawableStates(int[], int[])
10491     */
10492    protected int[] onCreateDrawableState(int extraSpace) {
10493        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
10494                mParent instanceof View) {
10495            return ((View) mParent).onCreateDrawableState(extraSpace);
10496        }
10497
10498        int[] drawableState;
10499
10500        int privateFlags = mPrivateFlags;
10501
10502        int viewStateIndex = 0;
10503        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
10504        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
10505        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
10506        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
10507        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
10508        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
10509        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
10510                HardwareRenderer.isAvailable()) {
10511            // This is set if HW acceleration is requested, even if the current
10512            // process doesn't allow it.  This is just to allow app preview
10513            // windows to better match their app.
10514            viewStateIndex |= VIEW_STATE_ACCELERATED;
10515        }
10516        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
10517
10518        final int privateFlags2 = mPrivateFlags2;
10519        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
10520        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
10521
10522        drawableState = VIEW_STATE_SETS[viewStateIndex];
10523
10524        //noinspection ConstantIfStatement
10525        if (false) {
10526            Log.i("View", "drawableStateIndex=" + viewStateIndex);
10527            Log.i("View", toString()
10528                    + " pressed=" + ((privateFlags & PRESSED) != 0)
10529                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
10530                    + " fo=" + hasFocus()
10531                    + " sl=" + ((privateFlags & SELECTED) != 0)
10532                    + " wf=" + hasWindowFocus()
10533                    + ": " + Arrays.toString(drawableState));
10534        }
10535
10536        if (extraSpace == 0) {
10537            return drawableState;
10538        }
10539
10540        final int[] fullState;
10541        if (drawableState != null) {
10542            fullState = new int[drawableState.length + extraSpace];
10543            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
10544        } else {
10545            fullState = new int[extraSpace];
10546        }
10547
10548        return fullState;
10549    }
10550
10551    /**
10552     * Merge your own state values in <var>additionalState</var> into the base
10553     * state values <var>baseState</var> that were returned by
10554     * {@link #onCreateDrawableState(int)}.
10555     *
10556     * @param baseState The base state values returned by
10557     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
10558     * own additional state values.
10559     *
10560     * @param additionalState The additional state values you would like
10561     * added to <var>baseState</var>; this array is not modified.
10562     *
10563     * @return As a convenience, the <var>baseState</var> array you originally
10564     * passed into the function is returned.
10565     *
10566     * @see #onCreateDrawableState(int)
10567     */
10568    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
10569        final int N = baseState.length;
10570        int i = N - 1;
10571        while (i >= 0 && baseState[i] == 0) {
10572            i--;
10573        }
10574        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
10575        return baseState;
10576    }
10577
10578    /**
10579     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
10580     * on all Drawable objects associated with this view.
10581     */
10582    public void jumpDrawablesToCurrentState() {
10583        if (mBGDrawable != null) {
10584            mBGDrawable.jumpToCurrentState();
10585        }
10586    }
10587
10588    /**
10589     * Sets the background color for this view.
10590     * @param color the color of the background
10591     */
10592    @RemotableViewMethod
10593    public void setBackgroundColor(int color) {
10594        if (mBGDrawable instanceof ColorDrawable) {
10595            ((ColorDrawable) mBGDrawable).setColor(color);
10596        } else {
10597            setBackgroundDrawable(new ColorDrawable(color));
10598        }
10599    }
10600
10601    /**
10602     * Set the background to a given resource. The resource should refer to
10603     * a Drawable object or 0 to remove the background.
10604     * @param resid The identifier of the resource.
10605     * @attr ref android.R.styleable#View_background
10606     */
10607    @RemotableViewMethod
10608    public void setBackgroundResource(int resid) {
10609        if (resid != 0 && resid == mBackgroundResource) {
10610            return;
10611        }
10612
10613        Drawable d= null;
10614        if (resid != 0) {
10615            d = mResources.getDrawable(resid);
10616        }
10617        setBackgroundDrawable(d);
10618
10619        mBackgroundResource = resid;
10620    }
10621
10622    /**
10623     * Set the background to a given Drawable, or remove the background. If the
10624     * background has padding, this View's padding is set to the background's
10625     * padding. However, when a background is removed, this View's padding isn't
10626     * touched. If setting the padding is desired, please use
10627     * {@link #setPadding(int, int, int, int)}.
10628     *
10629     * @param d The Drawable to use as the background, or null to remove the
10630     *        background
10631     */
10632    public void setBackgroundDrawable(Drawable d) {
10633        boolean requestLayout = false;
10634
10635        mBackgroundResource = 0;
10636
10637        /*
10638         * Regardless of whether we're setting a new background or not, we want
10639         * to clear the previous drawable.
10640         */
10641        if (mBGDrawable != null) {
10642            mBGDrawable.setCallback(null);
10643            unscheduleDrawable(mBGDrawable);
10644        }
10645
10646        if (d != null) {
10647            Rect padding = sThreadLocal.get();
10648            if (padding == null) {
10649                padding = new Rect();
10650                sThreadLocal.set(padding);
10651            }
10652            if (d.getPadding(padding)) {
10653                setPadding(padding.left, padding.top, padding.right, padding.bottom);
10654            }
10655
10656            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
10657            // if it has a different minimum size, we should layout again
10658            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
10659                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
10660                requestLayout = true;
10661            }
10662
10663            d.setCallback(this);
10664            if (d.isStateful()) {
10665                d.setState(getDrawableState());
10666            }
10667            d.setVisible(getVisibility() == VISIBLE, false);
10668            mBGDrawable = d;
10669
10670            if ((mPrivateFlags & SKIP_DRAW) != 0) {
10671                mPrivateFlags &= ~SKIP_DRAW;
10672                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
10673                requestLayout = true;
10674            }
10675        } else {
10676            /* Remove the background */
10677            mBGDrawable = null;
10678
10679            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
10680                /*
10681                 * This view ONLY drew the background before and we're removing
10682                 * the background, so now it won't draw anything
10683                 * (hence we SKIP_DRAW)
10684                 */
10685                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
10686                mPrivateFlags |= SKIP_DRAW;
10687            }
10688
10689            /*
10690             * When the background is set, we try to apply its padding to this
10691             * View. When the background is removed, we don't touch this View's
10692             * padding. This is noted in the Javadocs. Hence, we don't need to
10693             * requestLayout(), the invalidate() below is sufficient.
10694             */
10695
10696            // The old background's minimum size could have affected this
10697            // View's layout, so let's requestLayout
10698            requestLayout = true;
10699        }
10700
10701        computeOpaqueFlags();
10702
10703        if (requestLayout) {
10704            requestLayout();
10705        }
10706
10707        mBackgroundSizeChanged = true;
10708        invalidate(true);
10709    }
10710
10711    /**
10712     * Gets the background drawable
10713     * @return The drawable used as the background for this view, if any.
10714     */
10715    public Drawable getBackground() {
10716        return mBGDrawable;
10717    }
10718
10719    /**
10720     * Sets the padding. The view may add on the space required to display
10721     * the scrollbars, depending on the style and visibility of the scrollbars.
10722     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
10723     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
10724     * from the values set in this call.
10725     *
10726     * @attr ref android.R.styleable#View_padding
10727     * @attr ref android.R.styleable#View_paddingBottom
10728     * @attr ref android.R.styleable#View_paddingLeft
10729     * @attr ref android.R.styleable#View_paddingRight
10730     * @attr ref android.R.styleable#View_paddingTop
10731     * @param left the left padding in pixels
10732     * @param top the top padding in pixels
10733     * @param right the right padding in pixels
10734     * @param bottom the bottom padding in pixels
10735     */
10736    public void setPadding(int left, int top, int right, int bottom) {
10737        boolean changed = false;
10738
10739        mUserPaddingLeft = left;
10740        mUserPaddingRight = right;
10741        mUserPaddingBottom = bottom;
10742
10743        final int viewFlags = mViewFlags;
10744
10745        // Common case is there are no scroll bars.
10746        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
10747            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
10748                // TODO Determine what to do with SCROLLBAR_POSITION_DEFAULT based on RTL settings.
10749                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
10750                        ? 0 : getVerticalScrollbarWidth();
10751                switch (mVerticalScrollbarPosition) {
10752                    case SCROLLBAR_POSITION_DEFAULT:
10753                    case SCROLLBAR_POSITION_RIGHT:
10754                        right += offset;
10755                        break;
10756                    case SCROLLBAR_POSITION_LEFT:
10757                        left += offset;
10758                        break;
10759                }
10760            }
10761            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
10762                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
10763                        ? 0 : getHorizontalScrollbarHeight();
10764            }
10765        }
10766
10767        if (mPaddingLeft != left) {
10768            changed = true;
10769            mPaddingLeft = left;
10770        }
10771        if (mPaddingTop != top) {
10772            changed = true;
10773            mPaddingTop = top;
10774        }
10775        if (mPaddingRight != right) {
10776            changed = true;
10777            mPaddingRight = right;
10778        }
10779        if (mPaddingBottom != bottom) {
10780            changed = true;
10781            mPaddingBottom = bottom;
10782        }
10783
10784        if (changed) {
10785            requestLayout();
10786        }
10787    }
10788
10789    /**
10790     * Returns the top padding of this view.
10791     *
10792     * @return the top padding in pixels
10793     */
10794    public int getPaddingTop() {
10795        return mPaddingTop;
10796    }
10797
10798    /**
10799     * Returns the bottom padding of this view. If there are inset and enabled
10800     * scrollbars, this value may include the space required to display the
10801     * scrollbars as well.
10802     *
10803     * @return the bottom padding in pixels
10804     */
10805    public int getPaddingBottom() {
10806        return mPaddingBottom;
10807    }
10808
10809    /**
10810     * Returns the left padding of this view. If there are inset and enabled
10811     * scrollbars, this value may include the space required to display the
10812     * scrollbars as well.
10813     *
10814     * @return the left padding in pixels
10815     */
10816    public int getPaddingLeft() {
10817        return mPaddingLeft;
10818    }
10819
10820    /**
10821     * Returns the right padding of this view. If there are inset and enabled
10822     * scrollbars, this value may include the space required to display the
10823     * scrollbars as well.
10824     *
10825     * @return the right padding in pixels
10826     */
10827    public int getPaddingRight() {
10828        return mPaddingRight;
10829    }
10830
10831    /**
10832     * Changes the selection state of this view. A view can be selected or not.
10833     * Note that selection is not the same as focus. Views are typically
10834     * selected in the context of an AdapterView like ListView or GridView;
10835     * the selected view is the view that is highlighted.
10836     *
10837     * @param selected true if the view must be selected, false otherwise
10838     */
10839    public void setSelected(boolean selected) {
10840        if (((mPrivateFlags & SELECTED) != 0) != selected) {
10841            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
10842            if (!selected) resetPressedState();
10843            invalidate(true);
10844            refreshDrawableState();
10845            dispatchSetSelected(selected);
10846        }
10847    }
10848
10849    /**
10850     * Dispatch setSelected to all of this View's children.
10851     *
10852     * @see #setSelected(boolean)
10853     *
10854     * @param selected The new selected state
10855     */
10856    protected void dispatchSetSelected(boolean selected) {
10857    }
10858
10859    /**
10860     * Indicates the selection state of this view.
10861     *
10862     * @return true if the view is selected, false otherwise
10863     */
10864    @ViewDebug.ExportedProperty
10865    public boolean isSelected() {
10866        return (mPrivateFlags & SELECTED) != 0;
10867    }
10868
10869    /**
10870     * Changes the activated state of this view. A view can be activated or not.
10871     * Note that activation is not the same as selection.  Selection is
10872     * a transient property, representing the view (hierarchy) the user is
10873     * currently interacting with.  Activation is a longer-term state that the
10874     * user can move views in and out of.  For example, in a list view with
10875     * single or multiple selection enabled, the views in the current selection
10876     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
10877     * here.)  The activated state is propagated down to children of the view it
10878     * is set on.
10879     *
10880     * @param activated true if the view must be activated, false otherwise
10881     */
10882    public void setActivated(boolean activated) {
10883        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
10884            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
10885            invalidate(true);
10886            refreshDrawableState();
10887            dispatchSetActivated(activated);
10888        }
10889    }
10890
10891    /**
10892     * Dispatch setActivated to all of this View's children.
10893     *
10894     * @see #setActivated(boolean)
10895     *
10896     * @param activated The new activated state
10897     */
10898    protected void dispatchSetActivated(boolean activated) {
10899    }
10900
10901    /**
10902     * Indicates the activation state of this view.
10903     *
10904     * @return true if the view is activated, false otherwise
10905     */
10906    @ViewDebug.ExportedProperty
10907    public boolean isActivated() {
10908        return (mPrivateFlags & ACTIVATED) != 0;
10909    }
10910
10911    /**
10912     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
10913     * observer can be used to get notifications when global events, like
10914     * layout, happen.
10915     *
10916     * The returned ViewTreeObserver observer is not guaranteed to remain
10917     * valid for the lifetime of this View. If the caller of this method keeps
10918     * a long-lived reference to ViewTreeObserver, it should always check for
10919     * the return value of {@link ViewTreeObserver#isAlive()}.
10920     *
10921     * @return The ViewTreeObserver for this view's hierarchy.
10922     */
10923    public ViewTreeObserver getViewTreeObserver() {
10924        if (mAttachInfo != null) {
10925            return mAttachInfo.mTreeObserver;
10926        }
10927        if (mFloatingTreeObserver == null) {
10928            mFloatingTreeObserver = new ViewTreeObserver();
10929        }
10930        return mFloatingTreeObserver;
10931    }
10932
10933    /**
10934     * <p>Finds the topmost view in the current view hierarchy.</p>
10935     *
10936     * @return the topmost view containing this view
10937     */
10938    public View getRootView() {
10939        if (mAttachInfo != null) {
10940            final View v = mAttachInfo.mRootView;
10941            if (v != null) {
10942                return v;
10943            }
10944        }
10945
10946        View parent = this;
10947
10948        while (parent.mParent != null && parent.mParent instanceof View) {
10949            parent = (View) parent.mParent;
10950        }
10951
10952        return parent;
10953    }
10954
10955    /**
10956     * <p>Computes the coordinates of this view on the screen. The argument
10957     * must be an array of two integers. After the method returns, the array
10958     * contains the x and y location in that order.</p>
10959     *
10960     * @param location an array of two integers in which to hold the coordinates
10961     */
10962    public void getLocationOnScreen(int[] location) {
10963        getLocationInWindow(location);
10964
10965        final AttachInfo info = mAttachInfo;
10966        if (info != null) {
10967            location[0] += info.mWindowLeft;
10968            location[1] += info.mWindowTop;
10969        }
10970    }
10971
10972    /**
10973     * <p>Computes the coordinates of this view in its window. The argument
10974     * must be an array of two integers. After the method returns, the array
10975     * contains the x and y location in that order.</p>
10976     *
10977     * @param location an array of two integers in which to hold the coordinates
10978     */
10979    public void getLocationInWindow(int[] location) {
10980        if (location == null || location.length < 2) {
10981            throw new IllegalArgumentException("location must be an array of "
10982                    + "two integers");
10983        }
10984
10985        location[0] = mLeft + (int) (mTranslationX + 0.5f);
10986        location[1] = mTop + (int) (mTranslationY + 0.5f);
10987
10988        ViewParent viewParent = mParent;
10989        while (viewParent instanceof View) {
10990            final View view = (View)viewParent;
10991            location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
10992            location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
10993            viewParent = view.mParent;
10994        }
10995
10996        if (viewParent instanceof ViewAncestor) {
10997            // *cough*
10998            final ViewAncestor vr = (ViewAncestor)viewParent;
10999            location[1] -= vr.mCurScrollY;
11000        }
11001    }
11002
11003    /**
11004     * {@hide}
11005     * @param id the id of the view to be found
11006     * @return the view of the specified id, null if cannot be found
11007     */
11008    protected View findViewTraversal(int id) {
11009        if (id == mID) {
11010            return this;
11011        }
11012        return null;
11013    }
11014
11015    /**
11016     * {@hide}
11017     * @param tag the tag of the view to be found
11018     * @return the view of specified tag, null if cannot be found
11019     */
11020    protected View findViewWithTagTraversal(Object tag) {
11021        if (tag != null && tag.equals(mTag)) {
11022            return this;
11023        }
11024        return null;
11025    }
11026
11027    /**
11028     * {@hide}
11029     * @param predicate The predicate to evaluate.
11030     * @return The first view that matches the predicate or null.
11031     */
11032    protected View findViewByPredicateTraversal(Predicate<View> predicate) {
11033        if (predicate.apply(this)) {
11034            return this;
11035        }
11036        return null;
11037    }
11038
11039    /**
11040     * Look for a child view with the given id.  If this view has the given
11041     * id, return this view.
11042     *
11043     * @param id The id to search for.
11044     * @return The view that has the given id in the hierarchy or null
11045     */
11046    public final View findViewById(int id) {
11047        if (id < 0) {
11048            return null;
11049        }
11050        return findViewTraversal(id);
11051    }
11052
11053    /**
11054     * Look for a child view with the given tag.  If this view has the given
11055     * tag, return this view.
11056     *
11057     * @param tag The tag to search for, using "tag.equals(getTag())".
11058     * @return The View that has the given tag in the hierarchy or null
11059     */
11060    public final View findViewWithTag(Object tag) {
11061        if (tag == null) {
11062            return null;
11063        }
11064        return findViewWithTagTraversal(tag);
11065    }
11066
11067    /**
11068     * {@hide}
11069     * Look for a child view that matches the specified predicate.
11070     * If this view matches the predicate, return this view.
11071     *
11072     * @param predicate The predicate to evaluate.
11073     * @return The first view that matches the predicate or null.
11074     */
11075    public final View findViewByPredicate(Predicate<View> predicate) {
11076        return findViewByPredicateTraversal(predicate);
11077    }
11078
11079    /**
11080     * Sets the identifier for this view. The identifier does not have to be
11081     * unique in this view's hierarchy. The identifier should be a positive
11082     * number.
11083     *
11084     * @see #NO_ID
11085     * @see #getId()
11086     * @see #findViewById(int)
11087     *
11088     * @param id a number used to identify the view
11089     *
11090     * @attr ref android.R.styleable#View_id
11091     */
11092    public void setId(int id) {
11093        mID = id;
11094    }
11095
11096    /**
11097     * {@hide}
11098     *
11099     * @param isRoot true if the view belongs to the root namespace, false
11100     *        otherwise
11101     */
11102    public void setIsRootNamespace(boolean isRoot) {
11103        if (isRoot) {
11104            mPrivateFlags |= IS_ROOT_NAMESPACE;
11105        } else {
11106            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
11107        }
11108    }
11109
11110    /**
11111     * {@hide}
11112     *
11113     * @return true if the view belongs to the root namespace, false otherwise
11114     */
11115    public boolean isRootNamespace() {
11116        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
11117    }
11118
11119    /**
11120     * Returns this view's identifier.
11121     *
11122     * @return a positive integer used to identify the view or {@link #NO_ID}
11123     *         if the view has no ID
11124     *
11125     * @see #setId(int)
11126     * @see #findViewById(int)
11127     * @attr ref android.R.styleable#View_id
11128     */
11129    @ViewDebug.CapturedViewProperty
11130    public int getId() {
11131        return mID;
11132    }
11133
11134    /**
11135     * Returns this view's tag.
11136     *
11137     * @return the Object stored in this view as a tag
11138     *
11139     * @see #setTag(Object)
11140     * @see #getTag(int)
11141     */
11142    @ViewDebug.ExportedProperty
11143    public Object getTag() {
11144        return mTag;
11145    }
11146
11147    /**
11148     * Sets the tag associated with this view. A tag can be used to mark
11149     * a view in its hierarchy and does not have to be unique within the
11150     * hierarchy. Tags can also be used to store data within a view without
11151     * resorting to another data structure.
11152     *
11153     * @param tag an Object to tag the view with
11154     *
11155     * @see #getTag()
11156     * @see #setTag(int, Object)
11157     */
11158    public void setTag(final Object tag) {
11159        mTag = tag;
11160    }
11161
11162    /**
11163     * Returns the tag associated with this view and the specified key.
11164     *
11165     * @param key The key identifying the tag
11166     *
11167     * @return the Object stored in this view as a tag
11168     *
11169     * @see #setTag(int, Object)
11170     * @see #getTag()
11171     */
11172    public Object getTag(int key) {
11173        SparseArray<Object> tags = null;
11174        synchronized (sTagsLock) {
11175            if (sTags != null) {
11176                tags = sTags.get(this);
11177            }
11178        }
11179
11180        if (tags != null) return tags.get(key);
11181        return null;
11182    }
11183
11184    /**
11185     * Sets a tag associated with this view and a key. A tag can be used
11186     * to mark a view in its hierarchy and does not have to be unique within
11187     * the hierarchy. Tags can also be used to store data within a view
11188     * without resorting to another data structure.
11189     *
11190     * The specified key should be an id declared in the resources of the
11191     * application to ensure it is unique (see the <a
11192     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
11193     * Keys identified as belonging to
11194     * the Android framework or not associated with any package will cause
11195     * an {@link IllegalArgumentException} to be thrown.
11196     *
11197     * @param key The key identifying the tag
11198     * @param tag An Object to tag the view with
11199     *
11200     * @throws IllegalArgumentException If they specified key is not valid
11201     *
11202     * @see #setTag(Object)
11203     * @see #getTag(int)
11204     */
11205    public void setTag(int key, final Object tag) {
11206        // If the package id is 0x00 or 0x01, it's either an undefined package
11207        // or a framework id
11208        if ((key >>> 24) < 2) {
11209            throw new IllegalArgumentException("The key must be an application-specific "
11210                    + "resource id.");
11211        }
11212
11213        setTagInternal(this, key, tag);
11214    }
11215
11216    /**
11217     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
11218     * framework id.
11219     *
11220     * @hide
11221     */
11222    public void setTagInternal(int key, Object tag) {
11223        if ((key >>> 24) != 0x1) {
11224            throw new IllegalArgumentException("The key must be a framework-specific "
11225                    + "resource id.");
11226        }
11227
11228        setTagInternal(this, key, tag);
11229    }
11230
11231    private static void setTagInternal(View view, int key, Object tag) {
11232        SparseArray<Object> tags = null;
11233        synchronized (sTagsLock) {
11234            if (sTags == null) {
11235                sTags = new WeakHashMap<View, SparseArray<Object>>();
11236            } else {
11237                tags = sTags.get(view);
11238            }
11239        }
11240
11241        if (tags == null) {
11242            tags = new SparseArray<Object>(2);
11243            synchronized (sTagsLock) {
11244                sTags.put(view, tags);
11245            }
11246        }
11247
11248        tags.put(key, tag);
11249    }
11250
11251    /**
11252     * @param consistency The type of consistency. See ViewDebug for more information.
11253     *
11254     * @hide
11255     */
11256    protected boolean dispatchConsistencyCheck(int consistency) {
11257        return onConsistencyCheck(consistency);
11258    }
11259
11260    /**
11261     * Method that subclasses should implement to check their consistency. The type of
11262     * consistency check is indicated by the bit field passed as a parameter.
11263     *
11264     * @param consistency The type of consistency. See ViewDebug for more information.
11265     *
11266     * @throws IllegalStateException if the view is in an inconsistent state.
11267     *
11268     * @hide
11269     */
11270    protected boolean onConsistencyCheck(int consistency) {
11271        boolean result = true;
11272
11273        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
11274        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
11275
11276        if (checkLayout) {
11277            if (getParent() == null) {
11278                result = false;
11279                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
11280                        "View " + this + " does not have a parent.");
11281            }
11282
11283            if (mAttachInfo == null) {
11284                result = false;
11285                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
11286                        "View " + this + " is not attached to a window.");
11287            }
11288        }
11289
11290        if (checkDrawing) {
11291            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
11292            // from their draw() method
11293
11294            if ((mPrivateFlags & DRAWN) != DRAWN &&
11295                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
11296                result = false;
11297                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
11298                        "View " + this + " was invalidated but its drawing cache is valid.");
11299            }
11300        }
11301
11302        return result;
11303    }
11304
11305    /**
11306     * Prints information about this view in the log output, with the tag
11307     * {@link #VIEW_LOG_TAG}.
11308     *
11309     * @hide
11310     */
11311    public void debug() {
11312        debug(0);
11313    }
11314
11315    /**
11316     * Prints information about this view in the log output, with the tag
11317     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
11318     * indentation defined by the <code>depth</code>.
11319     *
11320     * @param depth the indentation level
11321     *
11322     * @hide
11323     */
11324    protected void debug(int depth) {
11325        String output = debugIndent(depth - 1);
11326
11327        output += "+ " + this;
11328        int id = getId();
11329        if (id != -1) {
11330            output += " (id=" + id + ")";
11331        }
11332        Object tag = getTag();
11333        if (tag != null) {
11334            output += " (tag=" + tag + ")";
11335        }
11336        Log.d(VIEW_LOG_TAG, output);
11337
11338        if ((mPrivateFlags & FOCUSED) != 0) {
11339            output = debugIndent(depth) + " FOCUSED";
11340            Log.d(VIEW_LOG_TAG, output);
11341        }
11342
11343        output = debugIndent(depth);
11344        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
11345                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
11346                + "} ";
11347        Log.d(VIEW_LOG_TAG, output);
11348
11349        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
11350                || mPaddingBottom != 0) {
11351            output = debugIndent(depth);
11352            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
11353                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
11354            Log.d(VIEW_LOG_TAG, output);
11355        }
11356
11357        output = debugIndent(depth);
11358        output += "mMeasureWidth=" + mMeasuredWidth +
11359                " mMeasureHeight=" + mMeasuredHeight;
11360        Log.d(VIEW_LOG_TAG, output);
11361
11362        output = debugIndent(depth);
11363        if (mLayoutParams == null) {
11364            output += "BAD! no layout params";
11365        } else {
11366            output = mLayoutParams.debug(output);
11367        }
11368        Log.d(VIEW_LOG_TAG, output);
11369
11370        output = debugIndent(depth);
11371        output += "flags={";
11372        output += View.printFlags(mViewFlags);
11373        output += "}";
11374        Log.d(VIEW_LOG_TAG, output);
11375
11376        output = debugIndent(depth);
11377        output += "privateFlags={";
11378        output += View.printPrivateFlags(mPrivateFlags);
11379        output += "}";
11380        Log.d(VIEW_LOG_TAG, output);
11381    }
11382
11383    /**
11384     * Creates an string of whitespaces used for indentation.
11385     *
11386     * @param depth the indentation level
11387     * @return a String containing (depth * 2 + 3) * 2 white spaces
11388     *
11389     * @hide
11390     */
11391    protected static String debugIndent(int depth) {
11392        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
11393        for (int i = 0; i < (depth * 2) + 3; i++) {
11394            spaces.append(' ').append(' ');
11395        }
11396        return spaces.toString();
11397    }
11398
11399    /**
11400     * <p>Return the offset of the widget's text baseline from the widget's top
11401     * boundary. If this widget does not support baseline alignment, this
11402     * method returns -1. </p>
11403     *
11404     * @return the offset of the baseline within the widget's bounds or -1
11405     *         if baseline alignment is not supported
11406     */
11407    @ViewDebug.ExportedProperty(category = "layout")
11408    public int getBaseline() {
11409        return -1;
11410    }
11411
11412    /**
11413     * Call this when something has changed which has invalidated the
11414     * layout of this view. This will schedule a layout pass of the view
11415     * tree.
11416     */
11417    public void requestLayout() {
11418        if (ViewDebug.TRACE_HIERARCHY) {
11419            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
11420        }
11421
11422        mPrivateFlags |= FORCE_LAYOUT;
11423        mPrivateFlags |= INVALIDATED;
11424
11425        if (mParent != null && !mParent.isLayoutRequested()) {
11426            mParent.requestLayout();
11427        }
11428    }
11429
11430    /**
11431     * Forces this view to be laid out during the next layout pass.
11432     * This method does not call requestLayout() or forceLayout()
11433     * on the parent.
11434     */
11435    public void forceLayout() {
11436        mPrivateFlags |= FORCE_LAYOUT;
11437        mPrivateFlags |= INVALIDATED;
11438    }
11439
11440    /**
11441     * <p>
11442     * This is called to find out how big a view should be. The parent
11443     * supplies constraint information in the width and height parameters.
11444     * </p>
11445     *
11446     * <p>
11447     * The actual mesurement work of a view is performed in
11448     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
11449     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
11450     * </p>
11451     *
11452     *
11453     * @param widthMeasureSpec Horizontal space requirements as imposed by the
11454     *        parent
11455     * @param heightMeasureSpec Vertical space requirements as imposed by the
11456     *        parent
11457     *
11458     * @see #onMeasure(int, int)
11459     */
11460    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
11461        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
11462                widthMeasureSpec != mOldWidthMeasureSpec ||
11463                heightMeasureSpec != mOldHeightMeasureSpec) {
11464
11465            // first clears the measured dimension flag
11466            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
11467
11468            if (ViewDebug.TRACE_HIERARCHY) {
11469                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
11470            }
11471
11472            // measure ourselves, this should set the measured dimension flag back
11473            onMeasure(widthMeasureSpec, heightMeasureSpec);
11474
11475            // flag not set, setMeasuredDimension() was not invoked, we raise
11476            // an exception to warn the developer
11477            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
11478                throw new IllegalStateException("onMeasure() did not set the"
11479                        + " measured dimension by calling"
11480                        + " setMeasuredDimension()");
11481            }
11482
11483            mPrivateFlags |= LAYOUT_REQUIRED;
11484        }
11485
11486        mOldWidthMeasureSpec = widthMeasureSpec;
11487        mOldHeightMeasureSpec = heightMeasureSpec;
11488    }
11489
11490    /**
11491     * <p>
11492     * Measure the view and its content to determine the measured width and the
11493     * measured height. This method is invoked by {@link #measure(int, int)} and
11494     * should be overriden by subclasses to provide accurate and efficient
11495     * measurement of their contents.
11496     * </p>
11497     *
11498     * <p>
11499     * <strong>CONTRACT:</strong> When overriding this method, you
11500     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
11501     * measured width and height of this view. Failure to do so will trigger an
11502     * <code>IllegalStateException</code>, thrown by
11503     * {@link #measure(int, int)}. Calling the superclass'
11504     * {@link #onMeasure(int, int)} is a valid use.
11505     * </p>
11506     *
11507     * <p>
11508     * The base class implementation of measure defaults to the background size,
11509     * unless a larger size is allowed by the MeasureSpec. Subclasses should
11510     * override {@link #onMeasure(int, int)} to provide better measurements of
11511     * their content.
11512     * </p>
11513     *
11514     * <p>
11515     * If this method is overridden, it is the subclass's responsibility to make
11516     * sure the measured height and width are at least the view's minimum height
11517     * and width ({@link #getSuggestedMinimumHeight()} and
11518     * {@link #getSuggestedMinimumWidth()}).
11519     * </p>
11520     *
11521     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
11522     *                         The requirements are encoded with
11523     *                         {@link android.view.View.MeasureSpec}.
11524     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
11525     *                         The requirements are encoded with
11526     *                         {@link android.view.View.MeasureSpec}.
11527     *
11528     * @see #getMeasuredWidth()
11529     * @see #getMeasuredHeight()
11530     * @see #setMeasuredDimension(int, int)
11531     * @see #getSuggestedMinimumHeight()
11532     * @see #getSuggestedMinimumWidth()
11533     * @see android.view.View.MeasureSpec#getMode(int)
11534     * @see android.view.View.MeasureSpec#getSize(int)
11535     */
11536    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
11537        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
11538                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
11539    }
11540
11541    /**
11542     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
11543     * measured width and measured height. Failing to do so will trigger an
11544     * exception at measurement time.</p>
11545     *
11546     * @param measuredWidth The measured width of this view.  May be a complex
11547     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
11548     * {@link #MEASURED_STATE_TOO_SMALL}.
11549     * @param measuredHeight The measured height of this view.  May be a complex
11550     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
11551     * {@link #MEASURED_STATE_TOO_SMALL}.
11552     */
11553    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
11554        mMeasuredWidth = measuredWidth;
11555        mMeasuredHeight = measuredHeight;
11556
11557        mPrivateFlags |= MEASURED_DIMENSION_SET;
11558    }
11559
11560    /**
11561     * Merge two states as returned by {@link #getMeasuredState()}.
11562     * @param curState The current state as returned from a view or the result
11563     * of combining multiple views.
11564     * @param newState The new view state to combine.
11565     * @return Returns a new integer reflecting the combination of the two
11566     * states.
11567     */
11568    public static int combineMeasuredStates(int curState, int newState) {
11569        return curState | newState;
11570    }
11571
11572    /**
11573     * Version of {@link #resolveSizeAndState(int, int, int)}
11574     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
11575     */
11576    public static int resolveSize(int size, int measureSpec) {
11577        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
11578    }
11579
11580    /**
11581     * Utility to reconcile a desired size and state, with constraints imposed
11582     * by a MeasureSpec.  Will take the desired size, unless a different size
11583     * is imposed by the constraints.  The returned value is a compound integer,
11584     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
11585     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
11586     * size is smaller than the size the view wants to be.
11587     *
11588     * @param size How big the view wants to be
11589     * @param measureSpec Constraints imposed by the parent
11590     * @return Size information bit mask as defined by
11591     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
11592     */
11593    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
11594        int result = size;
11595        int specMode = MeasureSpec.getMode(measureSpec);
11596        int specSize =  MeasureSpec.getSize(measureSpec);
11597        switch (specMode) {
11598        case MeasureSpec.UNSPECIFIED:
11599            result = size;
11600            break;
11601        case MeasureSpec.AT_MOST:
11602            if (specSize < size) {
11603                result = specSize | MEASURED_STATE_TOO_SMALL;
11604            } else {
11605                result = size;
11606            }
11607            break;
11608        case MeasureSpec.EXACTLY:
11609            result = specSize;
11610            break;
11611        }
11612        return result | (childMeasuredState&MEASURED_STATE_MASK);
11613    }
11614
11615    /**
11616     * Utility to return a default size. Uses the supplied size if the
11617     * MeasureSpec imposed no contraints. Will get larger if allowed
11618     * by the MeasureSpec.
11619     *
11620     * @param size Default size for this view
11621     * @param measureSpec Constraints imposed by the parent
11622     * @return The size this view should be.
11623     */
11624    public static int getDefaultSize(int size, int measureSpec) {
11625        int result = size;
11626        int specMode = MeasureSpec.getMode(measureSpec);
11627        int specSize =  MeasureSpec.getSize(measureSpec);
11628
11629        switch (specMode) {
11630        case MeasureSpec.UNSPECIFIED:
11631            result = size;
11632            break;
11633        case MeasureSpec.AT_MOST:
11634        case MeasureSpec.EXACTLY:
11635            result = specSize;
11636            break;
11637        }
11638        return result;
11639    }
11640
11641    /**
11642     * Returns the suggested minimum height that the view should use. This
11643     * returns the maximum of the view's minimum height
11644     * and the background's minimum height
11645     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
11646     * <p>
11647     * When being used in {@link #onMeasure(int, int)}, the caller should still
11648     * ensure the returned height is within the requirements of the parent.
11649     *
11650     * @return The suggested minimum height of the view.
11651     */
11652    protected int getSuggestedMinimumHeight() {
11653        int suggestedMinHeight = mMinHeight;
11654
11655        if (mBGDrawable != null) {
11656            final int bgMinHeight = mBGDrawable.getMinimumHeight();
11657            if (suggestedMinHeight < bgMinHeight) {
11658                suggestedMinHeight = bgMinHeight;
11659            }
11660        }
11661
11662        return suggestedMinHeight;
11663    }
11664
11665    /**
11666     * Returns the suggested minimum width that the view should use. This
11667     * returns the maximum of the view's minimum width)
11668     * and the background's minimum width
11669     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
11670     * <p>
11671     * When being used in {@link #onMeasure(int, int)}, the caller should still
11672     * ensure the returned width is within the requirements of the parent.
11673     *
11674     * @return The suggested minimum width of the view.
11675     */
11676    protected int getSuggestedMinimumWidth() {
11677        int suggestedMinWidth = mMinWidth;
11678
11679        if (mBGDrawable != null) {
11680            final int bgMinWidth = mBGDrawable.getMinimumWidth();
11681            if (suggestedMinWidth < bgMinWidth) {
11682                suggestedMinWidth = bgMinWidth;
11683            }
11684        }
11685
11686        return suggestedMinWidth;
11687    }
11688
11689    /**
11690     * Sets the minimum height of the view. It is not guaranteed the view will
11691     * be able to achieve this minimum height (for example, if its parent layout
11692     * constrains it with less available height).
11693     *
11694     * @param minHeight The minimum height the view will try to be.
11695     */
11696    public void setMinimumHeight(int minHeight) {
11697        mMinHeight = minHeight;
11698    }
11699
11700    /**
11701     * Sets the minimum width of the view. It is not guaranteed the view will
11702     * be able to achieve this minimum width (for example, if its parent layout
11703     * constrains it with less available width).
11704     *
11705     * @param minWidth The minimum width the view will try to be.
11706     */
11707    public void setMinimumWidth(int minWidth) {
11708        mMinWidth = minWidth;
11709    }
11710
11711    /**
11712     * Get the animation currently associated with this view.
11713     *
11714     * @return The animation that is currently playing or
11715     *         scheduled to play for this view.
11716     */
11717    public Animation getAnimation() {
11718        return mCurrentAnimation;
11719    }
11720
11721    /**
11722     * Start the specified animation now.
11723     *
11724     * @param animation the animation to start now
11725     */
11726    public void startAnimation(Animation animation) {
11727        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
11728        setAnimation(animation);
11729        invalidateParentCaches();
11730        invalidate(true);
11731    }
11732
11733    /**
11734     * Cancels any animations for this view.
11735     */
11736    public void clearAnimation() {
11737        if (mCurrentAnimation != null) {
11738            mCurrentAnimation.detach();
11739        }
11740        mCurrentAnimation = null;
11741        invalidateParentIfNeeded();
11742    }
11743
11744    /**
11745     * Sets the next animation to play for this view.
11746     * If you want the animation to play immediately, use
11747     * startAnimation. This method provides allows fine-grained
11748     * control over the start time and invalidation, but you
11749     * must make sure that 1) the animation has a start time set, and
11750     * 2) the view will be invalidated when the animation is supposed to
11751     * start.
11752     *
11753     * @param animation The next animation, or null.
11754     */
11755    public void setAnimation(Animation animation) {
11756        mCurrentAnimation = animation;
11757        if (animation != null) {
11758            animation.reset();
11759        }
11760    }
11761
11762    /**
11763     * Invoked by a parent ViewGroup to notify the start of the animation
11764     * currently associated with this view. If you override this method,
11765     * always call super.onAnimationStart();
11766     *
11767     * @see #setAnimation(android.view.animation.Animation)
11768     * @see #getAnimation()
11769     */
11770    protected void onAnimationStart() {
11771        mPrivateFlags |= ANIMATION_STARTED;
11772    }
11773
11774    /**
11775     * Invoked by a parent ViewGroup to notify the end of the animation
11776     * currently associated with this view. If you override this method,
11777     * always call super.onAnimationEnd();
11778     *
11779     * @see #setAnimation(android.view.animation.Animation)
11780     * @see #getAnimation()
11781     */
11782    protected void onAnimationEnd() {
11783        mPrivateFlags &= ~ANIMATION_STARTED;
11784    }
11785
11786    /**
11787     * Invoked if there is a Transform that involves alpha. Subclass that can
11788     * draw themselves with the specified alpha should return true, and then
11789     * respect that alpha when their onDraw() is called. If this returns false
11790     * then the view may be redirected to draw into an offscreen buffer to
11791     * fulfill the request, which will look fine, but may be slower than if the
11792     * subclass handles it internally. The default implementation returns false.
11793     *
11794     * @param alpha The alpha (0..255) to apply to the view's drawing
11795     * @return true if the view can draw with the specified alpha.
11796     */
11797    protected boolean onSetAlpha(int alpha) {
11798        return false;
11799    }
11800
11801    /**
11802     * This is used by the RootView to perform an optimization when
11803     * the view hierarchy contains one or several SurfaceView.
11804     * SurfaceView is always considered transparent, but its children are not,
11805     * therefore all View objects remove themselves from the global transparent
11806     * region (passed as a parameter to this function).
11807     *
11808     * @param region The transparent region for this ViewAncestor (window).
11809     *
11810     * @return Returns true if the effective visibility of the view at this
11811     * point is opaque, regardless of the transparent region; returns false
11812     * if it is possible for underlying windows to be seen behind the view.
11813     *
11814     * {@hide}
11815     */
11816    public boolean gatherTransparentRegion(Region region) {
11817        final AttachInfo attachInfo = mAttachInfo;
11818        if (region != null && attachInfo != null) {
11819            final int pflags = mPrivateFlags;
11820            if ((pflags & SKIP_DRAW) == 0) {
11821                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
11822                // remove it from the transparent region.
11823                final int[] location = attachInfo.mTransparentLocation;
11824                getLocationInWindow(location);
11825                region.op(location[0], location[1], location[0] + mRight - mLeft,
11826                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
11827            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
11828                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
11829                // exists, so we remove the background drawable's non-transparent
11830                // parts from this transparent region.
11831                applyDrawableToTransparentRegion(mBGDrawable, region);
11832            }
11833        }
11834        return true;
11835    }
11836
11837    /**
11838     * Play a sound effect for this view.
11839     *
11840     * <p>The framework will play sound effects for some built in actions, such as
11841     * clicking, but you may wish to play these effects in your widget,
11842     * for instance, for internal navigation.
11843     *
11844     * <p>The sound effect will only be played if sound effects are enabled by the user, and
11845     * {@link #isSoundEffectsEnabled()} is true.
11846     *
11847     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
11848     */
11849    public void playSoundEffect(int soundConstant) {
11850        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
11851            return;
11852        }
11853        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
11854    }
11855
11856    /**
11857     * BZZZTT!!1!
11858     *
11859     * <p>Provide haptic feedback to the user for this view.
11860     *
11861     * <p>The framework will provide haptic feedback for some built in actions,
11862     * such as long presses, but you may wish to provide feedback for your
11863     * own widget.
11864     *
11865     * <p>The feedback will only be performed if
11866     * {@link #isHapticFeedbackEnabled()} is true.
11867     *
11868     * @param feedbackConstant One of the constants defined in
11869     * {@link HapticFeedbackConstants}
11870     */
11871    public boolean performHapticFeedback(int feedbackConstant) {
11872        return performHapticFeedback(feedbackConstant, 0);
11873    }
11874
11875    /**
11876     * BZZZTT!!1!
11877     *
11878     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
11879     *
11880     * @param feedbackConstant One of the constants defined in
11881     * {@link HapticFeedbackConstants}
11882     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
11883     */
11884    public boolean performHapticFeedback(int feedbackConstant, int flags) {
11885        if (mAttachInfo == null) {
11886            return false;
11887        }
11888        //noinspection SimplifiableIfStatement
11889        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
11890                && !isHapticFeedbackEnabled()) {
11891            return false;
11892        }
11893        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
11894                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
11895    }
11896
11897    /**
11898     * Request that the visibility of the status bar be changed.
11899     * @param visibility  Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
11900     */
11901    public void setSystemUiVisibility(int visibility) {
11902        if (visibility != mSystemUiVisibility) {
11903            mSystemUiVisibility = visibility;
11904            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11905                mParent.recomputeViewAttributes(this);
11906            }
11907        }
11908    }
11909
11910    /**
11911     * Returns the status bar visibility that this view has requested.
11912     * @return Either {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
11913     */
11914    public int getSystemUiVisibility() {
11915        return mSystemUiVisibility;
11916    }
11917
11918    /**
11919     * Set a listener to receive callbacks when the visibility of the system bar changes.
11920     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
11921     */
11922    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
11923        mOnSystemUiVisibilityChangeListener = l;
11924        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
11925            mParent.recomputeViewAttributes(this);
11926        }
11927    }
11928
11929    /**
11930     */
11931    public void dispatchSystemUiVisibilityChanged(int visibility) {
11932        if (mOnSystemUiVisibilityChangeListener != null) {
11933            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
11934                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
11935        }
11936    }
11937
11938    /**
11939     * Creates an image that the system displays during the drag and drop
11940     * operation. This is called a &quot;drag shadow&quot;. The default implementation
11941     * for a DragShadowBuilder based on a View returns an image that has exactly the same
11942     * appearance as the given View. The default also positions the center of the drag shadow
11943     * directly under the touch point. If no View is provided (the constructor with no parameters
11944     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
11945     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
11946     * default is an invisible drag shadow.
11947     * <p>
11948     * You are not required to use the View you provide to the constructor as the basis of the
11949     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
11950     * anything you want as the drag shadow.
11951     * </p>
11952     * <p>
11953     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
11954     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
11955     *  size and position of the drag shadow. It uses this data to construct a
11956     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
11957     *  so that your application can draw the shadow image in the Canvas.
11958     * </p>
11959     */
11960    public static class DragShadowBuilder {
11961        private final WeakReference<View> mView;
11962
11963        /**
11964         * Constructs a shadow image builder based on a View. By default, the resulting drag
11965         * shadow will have the same appearance and dimensions as the View, with the touch point
11966         * over the center of the View.
11967         * @param view A View. Any View in scope can be used.
11968         */
11969        public DragShadowBuilder(View view) {
11970            mView = new WeakReference<View>(view);
11971        }
11972
11973        /**
11974         * Construct a shadow builder object with no associated View.  This
11975         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
11976         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
11977         * to supply the drag shadow's dimensions and appearance without
11978         * reference to any View object. If they are not overridden, then the result is an
11979         * invisible drag shadow.
11980         */
11981        public DragShadowBuilder() {
11982            mView = new WeakReference<View>(null);
11983        }
11984
11985        /**
11986         * Returns the View object that had been passed to the
11987         * {@link #View.DragShadowBuilder(View)}
11988         * constructor.  If that View parameter was {@code null} or if the
11989         * {@link #View.DragShadowBuilder()}
11990         * constructor was used to instantiate the builder object, this method will return
11991         * null.
11992         *
11993         * @return The View object associate with this builder object.
11994         */
11995        @SuppressWarnings({"JavadocReference"})
11996        final public View getView() {
11997            return mView.get();
11998        }
11999
12000        /**
12001         * Provides the metrics for the shadow image. These include the dimensions of
12002         * the shadow image, and the point within that shadow that should
12003         * be centered under the touch location while dragging.
12004         * <p>
12005         * The default implementation sets the dimensions of the shadow to be the
12006         * same as the dimensions of the View itself and centers the shadow under
12007         * the touch point.
12008         * </p>
12009         *
12010         * @param shadowSize A {@link android.graphics.Point} containing the width and height
12011         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
12012         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
12013         * image.
12014         *
12015         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
12016         * shadow image that should be underneath the touch point during the drag and drop
12017         * operation. Your application must set {@link android.graphics.Point#x} to the
12018         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
12019         */
12020        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
12021            final View view = mView.get();
12022            if (view != null) {
12023                shadowSize.set(view.getWidth(), view.getHeight());
12024                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
12025            } else {
12026                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
12027            }
12028        }
12029
12030        /**
12031         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
12032         * based on the dimensions it received from the
12033         * {@link #onProvideShadowMetrics(Point, Point)} callback.
12034         *
12035         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
12036         */
12037        public void onDrawShadow(Canvas canvas) {
12038            final View view = mView.get();
12039            if (view != null) {
12040                view.draw(canvas);
12041            } else {
12042                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
12043            }
12044        }
12045    }
12046
12047    /**
12048     * Starts a drag and drop operation. When your application calls this method, it passes a
12049     * {@link android.view.View.DragShadowBuilder} object to the system. The
12050     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
12051     * to get metrics for the drag shadow, and then calls the object's
12052     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
12053     * <p>
12054     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
12055     *  drag events to all the View objects in your application that are currently visible. It does
12056     *  this either by calling the View object's drag listener (an implementation of
12057     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
12058     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
12059     *  Both are passed a {@link android.view.DragEvent} object that has a
12060     *  {@link android.view.DragEvent#getAction()} value of
12061     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
12062     * </p>
12063     * <p>
12064     * Your application can invoke startDrag() on any attached View object. The View object does not
12065     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
12066     * be related to the View the user selected for dragging.
12067     * </p>
12068     * @param data A {@link android.content.ClipData} object pointing to the data to be
12069     * transferred by the drag and drop operation.
12070     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
12071     * drag shadow.
12072     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
12073     * drop operation. This Object is put into every DragEvent object sent by the system during the
12074     * current drag.
12075     * <p>
12076     * myLocalState is a lightweight mechanism for the sending information from the dragged View
12077     * to the target Views. For example, it can contain flags that differentiate between a
12078     * a copy operation and a move operation.
12079     * </p>
12080     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
12081     * so the parameter should be set to 0.
12082     * @return {@code true} if the method completes successfully, or
12083     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
12084     * do a drag, and so no drag operation is in progress.
12085     */
12086    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
12087            Object myLocalState, int flags) {
12088        if (ViewDebug.DEBUG_DRAG) {
12089            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
12090        }
12091        boolean okay = false;
12092
12093        Point shadowSize = new Point();
12094        Point shadowTouchPoint = new Point();
12095        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
12096
12097        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
12098                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
12099            throw new IllegalStateException("Drag shadow dimensions must not be negative");
12100        }
12101
12102        if (ViewDebug.DEBUG_DRAG) {
12103            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
12104                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
12105        }
12106        Surface surface = new Surface();
12107        try {
12108            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
12109                    flags, shadowSize.x, shadowSize.y, surface);
12110            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
12111                    + " surface=" + surface);
12112            if (token != null) {
12113                Canvas canvas = surface.lockCanvas(null);
12114                try {
12115                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
12116                    shadowBuilder.onDrawShadow(canvas);
12117                } finally {
12118                    surface.unlockCanvasAndPost(canvas);
12119                }
12120
12121                final ViewAncestor root = getViewAncestor();
12122
12123                // Cache the local state object for delivery with DragEvents
12124                root.setLocalDragState(myLocalState);
12125
12126                // repurpose 'shadowSize' for the last touch point
12127                root.getLastTouchPoint(shadowSize);
12128
12129                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
12130                        shadowSize.x, shadowSize.y,
12131                        shadowTouchPoint.x, shadowTouchPoint.y, data);
12132                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
12133            }
12134        } catch (Exception e) {
12135            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
12136            surface.destroy();
12137        }
12138
12139        return okay;
12140    }
12141
12142    /**
12143     * Handles drag events sent by the system following a call to
12144     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
12145     *<p>
12146     * When the system calls this method, it passes a
12147     * {@link android.view.DragEvent} object. A call to
12148     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
12149     * in DragEvent. The method uses these to determine what is happening in the drag and drop
12150     * operation.
12151     * @param event The {@link android.view.DragEvent} sent by the system.
12152     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
12153     * in DragEvent, indicating the type of drag event represented by this object.
12154     * @return {@code true} if the method was successful, otherwise {@code false}.
12155     * <p>
12156     *  The method should return {@code true} in response to an action type of
12157     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
12158     *  operation.
12159     * </p>
12160     * <p>
12161     *  The method should also return {@code true} in response to an action type of
12162     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
12163     *  {@code false} if it didn't.
12164     * </p>
12165     */
12166    public boolean onDragEvent(DragEvent event) {
12167        return false;
12168    }
12169
12170    /**
12171     * Detects if this View is enabled and has a drag event listener.
12172     * If both are true, then it calls the drag event listener with the
12173     * {@link android.view.DragEvent} it received. If the drag event listener returns
12174     * {@code true}, then dispatchDragEvent() returns {@code true}.
12175     * <p>
12176     * For all other cases, the method calls the
12177     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
12178     * method and returns its result.
12179     * </p>
12180     * <p>
12181     * This ensures that a drag event is always consumed, even if the View does not have a drag
12182     * event listener. However, if the View has a listener and the listener returns true, then
12183     * onDragEvent() is not called.
12184     * </p>
12185     */
12186    public boolean dispatchDragEvent(DragEvent event) {
12187        //noinspection SimplifiableIfStatement
12188        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
12189                && mOnDragListener.onDrag(this, event)) {
12190            return true;
12191        }
12192        return onDragEvent(event);
12193    }
12194
12195    boolean canAcceptDrag() {
12196        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
12197    }
12198
12199    /**
12200     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
12201     * it is ever exposed at all.
12202     * @hide
12203     */
12204    public void onCloseSystemDialogs(String reason) {
12205    }
12206
12207    /**
12208     * Given a Drawable whose bounds have been set to draw into this view,
12209     * update a Region being computed for
12210     * {@link #gatherTransparentRegion(android.graphics.Region)} so
12211     * that any non-transparent parts of the Drawable are removed from the
12212     * given transparent region.
12213     *
12214     * @param dr The Drawable whose transparency is to be applied to the region.
12215     * @param region A Region holding the current transparency information,
12216     * where any parts of the region that are set are considered to be
12217     * transparent.  On return, this region will be modified to have the
12218     * transparency information reduced by the corresponding parts of the
12219     * Drawable that are not transparent.
12220     * {@hide}
12221     */
12222    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
12223        if (DBG) {
12224            Log.i("View", "Getting transparent region for: " + this);
12225        }
12226        final Region r = dr.getTransparentRegion();
12227        final Rect db = dr.getBounds();
12228        final AttachInfo attachInfo = mAttachInfo;
12229        if (r != null && attachInfo != null) {
12230            final int w = getRight()-getLeft();
12231            final int h = getBottom()-getTop();
12232            if (db.left > 0) {
12233                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
12234                r.op(0, 0, db.left, h, Region.Op.UNION);
12235            }
12236            if (db.right < w) {
12237                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
12238                r.op(db.right, 0, w, h, Region.Op.UNION);
12239            }
12240            if (db.top > 0) {
12241                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
12242                r.op(0, 0, w, db.top, Region.Op.UNION);
12243            }
12244            if (db.bottom < h) {
12245                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
12246                r.op(0, db.bottom, w, h, Region.Op.UNION);
12247            }
12248            final int[] location = attachInfo.mTransparentLocation;
12249            getLocationInWindow(location);
12250            r.translate(location[0], location[1]);
12251            region.op(r, Region.Op.INTERSECT);
12252        } else {
12253            region.op(db, Region.Op.DIFFERENCE);
12254        }
12255    }
12256
12257    private void checkForLongClick(int delayOffset) {
12258        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
12259            mHasPerformedLongPress = false;
12260
12261            if (mPendingCheckForLongPress == null) {
12262                mPendingCheckForLongPress = new CheckForLongPress();
12263            }
12264            mPendingCheckForLongPress.rememberWindowAttachCount();
12265            postDelayed(mPendingCheckForLongPress,
12266                    ViewConfiguration.getLongPressTimeout() - delayOffset);
12267        }
12268    }
12269
12270    /**
12271     * Inflate a view from an XML resource.  This convenience method wraps the {@link
12272     * LayoutInflater} class, which provides a full range of options for view inflation.
12273     *
12274     * @param context The Context object for your activity or application.
12275     * @param resource The resource ID to inflate
12276     * @param root A view group that will be the parent.  Used to properly inflate the
12277     * layout_* parameters.
12278     * @see LayoutInflater
12279     */
12280    public static View inflate(Context context, int resource, ViewGroup root) {
12281        LayoutInflater factory = LayoutInflater.from(context);
12282        return factory.inflate(resource, root);
12283    }
12284
12285    /**
12286     * Scroll the view with standard behavior for scrolling beyond the normal
12287     * content boundaries. Views that call this method should override
12288     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
12289     * results of an over-scroll operation.
12290     *
12291     * Views can use this method to handle any touch or fling-based scrolling.
12292     *
12293     * @param deltaX Change in X in pixels
12294     * @param deltaY Change in Y in pixels
12295     * @param scrollX Current X scroll value in pixels before applying deltaX
12296     * @param scrollY Current Y scroll value in pixels before applying deltaY
12297     * @param scrollRangeX Maximum content scroll range along the X axis
12298     * @param scrollRangeY Maximum content scroll range along the Y axis
12299     * @param maxOverScrollX Number of pixels to overscroll by in either direction
12300     *          along the X axis.
12301     * @param maxOverScrollY Number of pixels to overscroll by in either direction
12302     *          along the Y axis.
12303     * @param isTouchEvent true if this scroll operation is the result of a touch event.
12304     * @return true if scrolling was clamped to an over-scroll boundary along either
12305     *          axis, false otherwise.
12306     */
12307    @SuppressWarnings({"UnusedParameters"})
12308    protected boolean overScrollBy(int deltaX, int deltaY,
12309            int scrollX, int scrollY,
12310            int scrollRangeX, int scrollRangeY,
12311            int maxOverScrollX, int maxOverScrollY,
12312            boolean isTouchEvent) {
12313        final int overScrollMode = mOverScrollMode;
12314        final boolean canScrollHorizontal =
12315                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
12316        final boolean canScrollVertical =
12317                computeVerticalScrollRange() > computeVerticalScrollExtent();
12318        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
12319                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
12320        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
12321                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
12322
12323        int newScrollX = scrollX + deltaX;
12324        if (!overScrollHorizontal) {
12325            maxOverScrollX = 0;
12326        }
12327
12328        int newScrollY = scrollY + deltaY;
12329        if (!overScrollVertical) {
12330            maxOverScrollY = 0;
12331        }
12332
12333        // Clamp values if at the limits and record
12334        final int left = -maxOverScrollX;
12335        final int right = maxOverScrollX + scrollRangeX;
12336        final int top = -maxOverScrollY;
12337        final int bottom = maxOverScrollY + scrollRangeY;
12338
12339        boolean clampedX = false;
12340        if (newScrollX > right) {
12341            newScrollX = right;
12342            clampedX = true;
12343        } else if (newScrollX < left) {
12344            newScrollX = left;
12345            clampedX = true;
12346        }
12347
12348        boolean clampedY = false;
12349        if (newScrollY > bottom) {
12350            newScrollY = bottom;
12351            clampedY = true;
12352        } else if (newScrollY < top) {
12353            newScrollY = top;
12354            clampedY = true;
12355        }
12356
12357        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
12358
12359        return clampedX || clampedY;
12360    }
12361
12362    /**
12363     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
12364     * respond to the results of an over-scroll operation.
12365     *
12366     * @param scrollX New X scroll value in pixels
12367     * @param scrollY New Y scroll value in pixels
12368     * @param clampedX True if scrollX was clamped to an over-scroll boundary
12369     * @param clampedY True if scrollY was clamped to an over-scroll boundary
12370     */
12371    protected void onOverScrolled(int scrollX, int scrollY,
12372            boolean clampedX, boolean clampedY) {
12373        // Intentionally empty.
12374    }
12375
12376    /**
12377     * Returns the over-scroll mode for this view. The result will be
12378     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
12379     * (allow over-scrolling only if the view content is larger than the container),
12380     * or {@link #OVER_SCROLL_NEVER}.
12381     *
12382     * @return This view's over-scroll mode.
12383     */
12384    public int getOverScrollMode() {
12385        return mOverScrollMode;
12386    }
12387
12388    /**
12389     * Set the over-scroll mode for this view. Valid over-scroll modes are
12390     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
12391     * (allow over-scrolling only if the view content is larger than the container),
12392     * or {@link #OVER_SCROLL_NEVER}.
12393     *
12394     * Setting the over-scroll mode of a view will have an effect only if the
12395     * view is capable of scrolling.
12396     *
12397     * @param overScrollMode The new over-scroll mode for this view.
12398     */
12399    public void setOverScrollMode(int overScrollMode) {
12400        if (overScrollMode != OVER_SCROLL_ALWAYS &&
12401                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
12402                overScrollMode != OVER_SCROLL_NEVER) {
12403            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
12404        }
12405        mOverScrollMode = overScrollMode;
12406    }
12407
12408    /**
12409     * Gets a scale factor that determines the distance the view should scroll
12410     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
12411     * @return The vertical scroll scale factor.
12412     * @hide
12413     */
12414    protected float getVerticalScrollFactor() {
12415        if (mVerticalScrollFactor == 0) {
12416            TypedValue outValue = new TypedValue();
12417            if (!mContext.getTheme().resolveAttribute(
12418                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
12419                throw new IllegalStateException(
12420                        "Expected theme to define listPreferredItemHeight.");
12421            }
12422            mVerticalScrollFactor = outValue.getDimension(
12423                    mContext.getResources().getDisplayMetrics());
12424        }
12425        return mVerticalScrollFactor;
12426    }
12427
12428    /**
12429     * Gets a scale factor that determines the distance the view should scroll
12430     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
12431     * @return The horizontal scroll scale factor.
12432     * @hide
12433     */
12434    protected float getHorizontalScrollFactor() {
12435        // TODO: Should use something else.
12436        return getVerticalScrollFactor();
12437    }
12438
12439    /**
12440     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
12441     * Each MeasureSpec represents a requirement for either the width or the height.
12442     * A MeasureSpec is comprised of a size and a mode. There are three possible
12443     * modes:
12444     * <dl>
12445     * <dt>UNSPECIFIED</dt>
12446     * <dd>
12447     * The parent has not imposed any constraint on the child. It can be whatever size
12448     * it wants.
12449     * </dd>
12450     *
12451     * <dt>EXACTLY</dt>
12452     * <dd>
12453     * The parent has determined an exact size for the child. The child is going to be
12454     * given those bounds regardless of how big it wants to be.
12455     * </dd>
12456     *
12457     * <dt>AT_MOST</dt>
12458     * <dd>
12459     * The child can be as large as it wants up to the specified size.
12460     * </dd>
12461     * </dl>
12462     *
12463     * MeasureSpecs are implemented as ints to reduce object allocation. This class
12464     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
12465     */
12466    public static class MeasureSpec {
12467        private static final int MODE_SHIFT = 30;
12468        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
12469
12470        /**
12471         * Measure specification mode: The parent has not imposed any constraint
12472         * on the child. It can be whatever size it wants.
12473         */
12474        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
12475
12476        /**
12477         * Measure specification mode: The parent has determined an exact size
12478         * for the child. The child is going to be given those bounds regardless
12479         * of how big it wants to be.
12480         */
12481        public static final int EXACTLY     = 1 << MODE_SHIFT;
12482
12483        /**
12484         * Measure specification mode: The child can be as large as it wants up
12485         * to the specified size.
12486         */
12487        public static final int AT_MOST     = 2 << MODE_SHIFT;
12488
12489        /**
12490         * Creates a measure specification based on the supplied size and mode.
12491         *
12492         * The mode must always be one of the following:
12493         * <ul>
12494         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
12495         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
12496         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
12497         * </ul>
12498         *
12499         * @param size the size of the measure specification
12500         * @param mode the mode of the measure specification
12501         * @return the measure specification based on size and mode
12502         */
12503        public static int makeMeasureSpec(int size, int mode) {
12504            return size + mode;
12505        }
12506
12507        /**
12508         * Extracts the mode from the supplied measure specification.
12509         *
12510         * @param measureSpec the measure specification to extract the mode from
12511         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
12512         *         {@link android.view.View.MeasureSpec#AT_MOST} or
12513         *         {@link android.view.View.MeasureSpec#EXACTLY}
12514         */
12515        public static int getMode(int measureSpec) {
12516            return (measureSpec & MODE_MASK);
12517        }
12518
12519        /**
12520         * Extracts the size from the supplied measure specification.
12521         *
12522         * @param measureSpec the measure specification to extract the size from
12523         * @return the size in pixels defined in the supplied measure specification
12524         */
12525        public static int getSize(int measureSpec) {
12526            return (measureSpec & ~MODE_MASK);
12527        }
12528
12529        /**
12530         * Returns a String representation of the specified measure
12531         * specification.
12532         *
12533         * @param measureSpec the measure specification to convert to a String
12534         * @return a String with the following format: "MeasureSpec: MODE SIZE"
12535         */
12536        public static String toString(int measureSpec) {
12537            int mode = getMode(measureSpec);
12538            int size = getSize(measureSpec);
12539
12540            StringBuilder sb = new StringBuilder("MeasureSpec: ");
12541
12542            if (mode == UNSPECIFIED)
12543                sb.append("UNSPECIFIED ");
12544            else if (mode == EXACTLY)
12545                sb.append("EXACTLY ");
12546            else if (mode == AT_MOST)
12547                sb.append("AT_MOST ");
12548            else
12549                sb.append(mode).append(" ");
12550
12551            sb.append(size);
12552            return sb.toString();
12553        }
12554    }
12555
12556    class CheckForLongPress implements Runnable {
12557
12558        private int mOriginalWindowAttachCount;
12559
12560        public void run() {
12561            if (isPressed() && (mParent != null)
12562                    && mOriginalWindowAttachCount == mWindowAttachCount) {
12563                if (performLongClick()) {
12564                    mHasPerformedLongPress = true;
12565                }
12566            }
12567        }
12568
12569        public void rememberWindowAttachCount() {
12570            mOriginalWindowAttachCount = mWindowAttachCount;
12571        }
12572    }
12573
12574    private final class CheckForTap implements Runnable {
12575        public void run() {
12576            mPrivateFlags &= ~PREPRESSED;
12577            mPrivateFlags |= PRESSED;
12578            refreshDrawableState();
12579            checkForLongClick(ViewConfiguration.getTapTimeout());
12580        }
12581    }
12582
12583    private final class PerformClick implements Runnable {
12584        public void run() {
12585            performClick();
12586        }
12587    }
12588
12589    /** @hide */
12590    public void hackTurnOffWindowResizeAnim(boolean off) {
12591        mAttachInfo.mTurnOffWindowResizeAnim = off;
12592    }
12593
12594    /**
12595     * This method returns a ViewPropertyAnimator object, which can be used to animate
12596     * specific properties on this View.
12597     *
12598     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
12599     */
12600    public ViewPropertyAnimator animate() {
12601        if (mAnimator == null) {
12602            mAnimator = new ViewPropertyAnimator(this);
12603        }
12604        return mAnimator;
12605    }
12606
12607    /**
12608     * Interface definition for a callback to be invoked when a key event is
12609     * dispatched to this view. The callback will be invoked before the key
12610     * event is given to the view.
12611     */
12612    public interface OnKeyListener {
12613        /**
12614         * Called when a key is dispatched to a view. This allows listeners to
12615         * get a chance to respond before the target view.
12616         *
12617         * @param v The view the key has been dispatched to.
12618         * @param keyCode The code for the physical key that was pressed
12619         * @param event The KeyEvent object containing full information about
12620         *        the event.
12621         * @return True if the listener has consumed the event, false otherwise.
12622         */
12623        boolean onKey(View v, int keyCode, KeyEvent event);
12624    }
12625
12626    /**
12627     * Interface definition for a callback to be invoked when a touch event is
12628     * dispatched to this view. The callback will be invoked before the touch
12629     * event is given to the view.
12630     */
12631    public interface OnTouchListener {
12632        /**
12633         * Called when a touch event is dispatched to a view. This allows listeners to
12634         * get a chance to respond before the target view.
12635         *
12636         * @param v The view the touch event has been dispatched to.
12637         * @param event The MotionEvent object containing full information about
12638         *        the event.
12639         * @return True if the listener has consumed the event, false otherwise.
12640         */
12641        boolean onTouch(View v, MotionEvent event);
12642    }
12643
12644    /**
12645     * Interface definition for a callback to be invoked when a generic motion event is
12646     * dispatched to this view. The callback will be invoked before the generic motion
12647     * event is given to the view.
12648     */
12649    public interface OnGenericMotionListener {
12650        /**
12651         * Called when a generic motion event is dispatched to a view. This allows listeners to
12652         * get a chance to respond before the target view.
12653         *
12654         * @param v The view the generic motion event has been dispatched to.
12655         * @param event The MotionEvent object containing full information about
12656         *        the event.
12657         * @return True if the listener has consumed the event, false otherwise.
12658         */
12659        boolean onGenericMotion(View v, MotionEvent event);
12660    }
12661
12662    /**
12663     * Interface definition for a callback to be invoked when a view has been clicked and held.
12664     */
12665    public interface OnLongClickListener {
12666        /**
12667         * Called when a view has been clicked and held.
12668         *
12669         * @param v The view that was clicked and held.
12670         *
12671         * @return true if the callback consumed the long click, false otherwise.
12672         */
12673        boolean onLongClick(View v);
12674    }
12675
12676    /**
12677     * Interface definition for a callback to be invoked when a drag is being dispatched
12678     * to this view.  The callback will be invoked before the hosting view's own
12679     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
12680     * onDrag(event) behavior, it should return 'false' from this callback.
12681     */
12682    public interface OnDragListener {
12683        /**
12684         * Called when a drag event is dispatched to a view. This allows listeners
12685         * to get a chance to override base View behavior.
12686         *
12687         * @param v The View that received the drag event.
12688         * @param event The {@link android.view.DragEvent} object for the drag event.
12689         * @return {@code true} if the drag event was handled successfully, or {@code false}
12690         * if the drag event was not handled. Note that {@code false} will trigger the View
12691         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
12692         */
12693        boolean onDrag(View v, DragEvent event);
12694    }
12695
12696    /**
12697     * Interface definition for a callback to be invoked when the focus state of
12698     * a view changed.
12699     */
12700    public interface OnFocusChangeListener {
12701        /**
12702         * Called when the focus state of a view has changed.
12703         *
12704         * @param v The view whose state has changed.
12705         * @param hasFocus The new focus state of v.
12706         */
12707        void onFocusChange(View v, boolean hasFocus);
12708    }
12709
12710    /**
12711     * Interface definition for a callback to be invoked when a view is clicked.
12712     */
12713    public interface OnClickListener {
12714        /**
12715         * Called when a view has been clicked.
12716         *
12717         * @param v The view that was clicked.
12718         */
12719        void onClick(View v);
12720    }
12721
12722    /**
12723     * Interface definition for a callback to be invoked when the context menu
12724     * for this view is being built.
12725     */
12726    public interface OnCreateContextMenuListener {
12727        /**
12728         * Called when the context menu for this view is being built. It is not
12729         * safe to hold onto the menu after this method returns.
12730         *
12731         * @param menu The context menu that is being built
12732         * @param v The view for which the context menu is being built
12733         * @param menuInfo Extra information about the item for which the
12734         *            context menu should be shown. This information will vary
12735         *            depending on the class of v.
12736         */
12737        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
12738    }
12739
12740    /**
12741     * Interface definition for a callback to be invoked when the status bar changes
12742     * visibility.
12743     *
12744     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
12745     */
12746    public interface OnSystemUiVisibilityChangeListener {
12747        /**
12748         * Called when the status bar changes visibility because of a call to
12749         * {@link View#setSystemUiVisibility(int)}.
12750         *
12751         * @param visibility {@link #STATUS_BAR_VISIBLE} or {@link #STATUS_BAR_HIDDEN}.
12752         */
12753        public void onSystemUiVisibilityChange(int visibility);
12754    }
12755
12756    /**
12757     * Interface definition for a callback to be invoked when this view is attached
12758     * or detached from its window.
12759     */
12760    public interface OnAttachStateChangeListener {
12761        /**
12762         * Called when the view is attached to a window.
12763         * @param v The view that was attached
12764         */
12765        public void onViewAttachedToWindow(View v);
12766        /**
12767         * Called when the view is detached from a window.
12768         * @param v The view that was detached
12769         */
12770        public void onViewDetachedFromWindow(View v);
12771    }
12772
12773    private final class UnsetPressedState implements Runnable {
12774        public void run() {
12775            setPressed(false);
12776        }
12777    }
12778
12779    /**
12780     * Base class for derived classes that want to save and restore their own
12781     * state in {@link android.view.View#onSaveInstanceState()}.
12782     */
12783    public static class BaseSavedState extends AbsSavedState {
12784        /**
12785         * Constructor used when reading from a parcel. Reads the state of the superclass.
12786         *
12787         * @param source
12788         */
12789        public BaseSavedState(Parcel source) {
12790            super(source);
12791        }
12792
12793        /**
12794         * Constructor called by derived classes when creating their SavedState objects
12795         *
12796         * @param superState The state of the superclass of this view
12797         */
12798        public BaseSavedState(Parcelable superState) {
12799            super(superState);
12800        }
12801
12802        public static final Parcelable.Creator<BaseSavedState> CREATOR =
12803                new Parcelable.Creator<BaseSavedState>() {
12804            public BaseSavedState createFromParcel(Parcel in) {
12805                return new BaseSavedState(in);
12806            }
12807
12808            public BaseSavedState[] newArray(int size) {
12809                return new BaseSavedState[size];
12810            }
12811        };
12812    }
12813
12814    /**
12815     * A set of information given to a view when it is attached to its parent
12816     * window.
12817     */
12818    static class AttachInfo {
12819        interface Callbacks {
12820            void playSoundEffect(int effectId);
12821            boolean performHapticFeedback(int effectId, boolean always);
12822        }
12823
12824        /**
12825         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
12826         * to a Handler. This class contains the target (View) to invalidate and
12827         * the coordinates of the dirty rectangle.
12828         *
12829         * For performance purposes, this class also implements a pool of up to
12830         * POOL_LIMIT objects that get reused. This reduces memory allocations
12831         * whenever possible.
12832         */
12833        static class InvalidateInfo implements Poolable<InvalidateInfo> {
12834            private static final int POOL_LIMIT = 10;
12835            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
12836                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
12837                        public InvalidateInfo newInstance() {
12838                            return new InvalidateInfo();
12839                        }
12840
12841                        public void onAcquired(InvalidateInfo element) {
12842                        }
12843
12844                        public void onReleased(InvalidateInfo element) {
12845                        }
12846                    }, POOL_LIMIT)
12847            );
12848
12849            private InvalidateInfo mNext;
12850            private boolean mIsPooled;
12851
12852            View target;
12853
12854            int left;
12855            int top;
12856            int right;
12857            int bottom;
12858
12859            public void setNextPoolable(InvalidateInfo element) {
12860                mNext = element;
12861            }
12862
12863            public InvalidateInfo getNextPoolable() {
12864                return mNext;
12865            }
12866
12867            static InvalidateInfo acquire() {
12868                return sPool.acquire();
12869            }
12870
12871            void release() {
12872                sPool.release(this);
12873            }
12874
12875            public boolean isPooled() {
12876                return mIsPooled;
12877            }
12878
12879            public void setPooled(boolean isPooled) {
12880                mIsPooled = isPooled;
12881            }
12882        }
12883
12884        final IWindowSession mSession;
12885
12886        final IWindow mWindow;
12887
12888        final IBinder mWindowToken;
12889
12890        final Callbacks mRootCallbacks;
12891
12892        Canvas mHardwareCanvas;
12893
12894        /**
12895         * The top view of the hierarchy.
12896         */
12897        View mRootView;
12898
12899        IBinder mPanelParentWindowToken;
12900        Surface mSurface;
12901
12902        boolean mHardwareAccelerated;
12903        boolean mHardwareAccelerationRequested;
12904        HardwareRenderer mHardwareRenderer;
12905
12906        /**
12907         * Scale factor used by the compatibility mode
12908         */
12909        float mApplicationScale;
12910
12911        /**
12912         * Indicates whether the application is in compatibility mode
12913         */
12914        boolean mScalingRequired;
12915
12916        /**
12917         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
12918         */
12919        boolean mTurnOffWindowResizeAnim;
12920
12921        /**
12922         * Left position of this view's window
12923         */
12924        int mWindowLeft;
12925
12926        /**
12927         * Top position of this view's window
12928         */
12929        int mWindowTop;
12930
12931        /**
12932         * Indicates whether views need to use 32-bit drawing caches
12933         */
12934        boolean mUse32BitDrawingCache;
12935
12936        /**
12937         * For windows that are full-screen but using insets to layout inside
12938         * of the screen decorations, these are the current insets for the
12939         * content of the window.
12940         */
12941        final Rect mContentInsets = new Rect();
12942
12943        /**
12944         * For windows that are full-screen but using insets to layout inside
12945         * of the screen decorations, these are the current insets for the
12946         * actual visible parts of the window.
12947         */
12948        final Rect mVisibleInsets = new Rect();
12949
12950        /**
12951         * The internal insets given by this window.  This value is
12952         * supplied by the client (through
12953         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
12954         * be given to the window manager when changed to be used in laying
12955         * out windows behind it.
12956         */
12957        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
12958                = new ViewTreeObserver.InternalInsetsInfo();
12959
12960        /**
12961         * All views in the window's hierarchy that serve as scroll containers,
12962         * used to determine if the window can be resized or must be panned
12963         * to adjust for a soft input area.
12964         */
12965        final ArrayList<View> mScrollContainers = new ArrayList<View>();
12966
12967        final KeyEvent.DispatcherState mKeyDispatchState
12968                = new KeyEvent.DispatcherState();
12969
12970        /**
12971         * Indicates whether the view's window currently has the focus.
12972         */
12973        boolean mHasWindowFocus;
12974
12975        /**
12976         * The current visibility of the window.
12977         */
12978        int mWindowVisibility;
12979
12980        /**
12981         * Indicates the time at which drawing started to occur.
12982         */
12983        long mDrawingTime;
12984
12985        /**
12986         * Indicates whether or not ignoring the DIRTY_MASK flags.
12987         */
12988        boolean mIgnoreDirtyState;
12989
12990        /**
12991         * Indicates whether the view's window is currently in touch mode.
12992         */
12993        boolean mInTouchMode;
12994
12995        /**
12996         * Indicates that ViewAncestor should trigger a global layout change
12997         * the next time it performs a traversal
12998         */
12999        boolean mRecomputeGlobalAttributes;
13000
13001        /**
13002         * Set during a traveral if any views want to keep the screen on.
13003         */
13004        boolean mKeepScreenOn;
13005
13006        /**
13007         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
13008         */
13009        int mSystemUiVisibility;
13010
13011        /**
13012         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
13013         * attached.
13014         */
13015        boolean mHasSystemUiListeners;
13016
13017        /**
13018         * Set if the visibility of any views has changed.
13019         */
13020        boolean mViewVisibilityChanged;
13021
13022        /**
13023         * Set to true if a view has been scrolled.
13024         */
13025        boolean mViewScrollChanged;
13026
13027        /**
13028         * Global to the view hierarchy used as a temporary for dealing with
13029         * x/y points in the transparent region computations.
13030         */
13031        final int[] mTransparentLocation = new int[2];
13032
13033        /**
13034         * Global to the view hierarchy used as a temporary for dealing with
13035         * x/y points in the ViewGroup.invalidateChild implementation.
13036         */
13037        final int[] mInvalidateChildLocation = new int[2];
13038
13039
13040        /**
13041         * Global to the view hierarchy used as a temporary for dealing with
13042         * x/y location when view is transformed.
13043         */
13044        final float[] mTmpTransformLocation = new float[2];
13045
13046        /**
13047         * The view tree observer used to dispatch global events like
13048         * layout, pre-draw, touch mode change, etc.
13049         */
13050        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
13051
13052        /**
13053         * A Canvas used by the view hierarchy to perform bitmap caching.
13054         */
13055        Canvas mCanvas;
13056
13057        /**
13058         * A Handler supplied by a view's {@link android.view.ViewAncestor}. This
13059         * handler can be used to pump events in the UI events queue.
13060         */
13061        final Handler mHandler;
13062
13063        /**
13064         * Identifier for messages requesting the view to be invalidated.
13065         * Such messages should be sent to {@link #mHandler}.
13066         */
13067        static final int INVALIDATE_MSG = 0x1;
13068
13069        /**
13070         * Identifier for messages requesting the view to invalidate a region.
13071         * Such messages should be sent to {@link #mHandler}.
13072         */
13073        static final int INVALIDATE_RECT_MSG = 0x2;
13074
13075        /**
13076         * Temporary for use in computing invalidate rectangles while
13077         * calling up the hierarchy.
13078         */
13079        final Rect mTmpInvalRect = new Rect();
13080
13081        /**
13082         * Temporary for use in computing hit areas with transformed views
13083         */
13084        final RectF mTmpTransformRect = new RectF();
13085
13086        /**
13087         * Temporary list for use in collecting focusable descendents of a view.
13088         */
13089        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
13090
13091        /**
13092         * The id of the window for accessibility purposes.
13093         */
13094        int mAccessibilityWindowId = View.NO_ID;
13095
13096        /**
13097         * Creates a new set of attachment information with the specified
13098         * events handler and thread.
13099         *
13100         * @param handler the events handler the view must use
13101         */
13102        AttachInfo(IWindowSession session, IWindow window,
13103                Handler handler, Callbacks effectPlayer) {
13104            mSession = session;
13105            mWindow = window;
13106            mWindowToken = window.asBinder();
13107            mHandler = handler;
13108            mRootCallbacks = effectPlayer;
13109        }
13110    }
13111
13112    /**
13113     * <p>ScrollabilityCache holds various fields used by a View when scrolling
13114     * is supported. This avoids keeping too many unused fields in most
13115     * instances of View.</p>
13116     */
13117    private static class ScrollabilityCache implements Runnable {
13118
13119        /**
13120         * Scrollbars are not visible
13121         */
13122        public static final int OFF = 0;
13123
13124        /**
13125         * Scrollbars are visible
13126         */
13127        public static final int ON = 1;
13128
13129        /**
13130         * Scrollbars are fading away
13131         */
13132        public static final int FADING = 2;
13133
13134        public boolean fadeScrollBars;
13135
13136        public int fadingEdgeLength;
13137        public int scrollBarDefaultDelayBeforeFade;
13138        public int scrollBarFadeDuration;
13139
13140        public int scrollBarSize;
13141        public ScrollBarDrawable scrollBar;
13142        public float[] interpolatorValues;
13143        public View host;
13144
13145        public final Paint paint;
13146        public final Matrix matrix;
13147        public Shader shader;
13148
13149        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
13150
13151        private static final float[] OPAQUE = { 255 };
13152        private static final float[] TRANSPARENT = { 0.0f };
13153
13154        /**
13155         * When fading should start. This time moves into the future every time
13156         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
13157         */
13158        public long fadeStartTime;
13159
13160
13161        /**
13162         * The current state of the scrollbars: ON, OFF, or FADING
13163         */
13164        public int state = OFF;
13165
13166        private int mLastColor;
13167
13168        public ScrollabilityCache(ViewConfiguration configuration, View host) {
13169            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
13170            scrollBarSize = configuration.getScaledScrollBarSize();
13171            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
13172            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
13173
13174            paint = new Paint();
13175            matrix = new Matrix();
13176            // use use a height of 1, and then wack the matrix each time we
13177            // actually use it.
13178            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
13179
13180            paint.setShader(shader);
13181            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
13182            this.host = host;
13183        }
13184
13185        public void setFadeColor(int color) {
13186            if (color != 0 && color != mLastColor) {
13187                mLastColor = color;
13188                color |= 0xFF000000;
13189
13190                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
13191                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
13192
13193                paint.setShader(shader);
13194                // Restore the default transfer mode (src_over)
13195                paint.setXfermode(null);
13196            }
13197        }
13198
13199        public void run() {
13200            long now = AnimationUtils.currentAnimationTimeMillis();
13201            if (now >= fadeStartTime) {
13202
13203                // the animation fades the scrollbars out by changing
13204                // the opacity (alpha) from fully opaque to fully
13205                // transparent
13206                int nextFrame = (int) now;
13207                int framesCount = 0;
13208
13209                Interpolator interpolator = scrollBarInterpolator;
13210
13211                // Start opaque
13212                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
13213
13214                // End transparent
13215                nextFrame += scrollBarFadeDuration;
13216                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
13217
13218                state = FADING;
13219
13220                // Kick off the fade animation
13221                host.invalidate(true);
13222            }
13223        }
13224
13225    }
13226}
13227