View.java revision 53f2531ba7bc72489d03fd17b6ce29c811fad8b5
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 android.content.ClipData;
20import android.content.Context;
21import android.content.res.Configuration;
22import android.content.res.Resources;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Camera;
26import android.graphics.Canvas;
27import android.graphics.Interpolator;
28import android.graphics.LinearGradient;
29import android.graphics.Matrix;
30import android.graphics.Paint;
31import android.graphics.PixelFormat;
32import android.graphics.Point;
33import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.graphics.Shader;
39import android.graphics.drawable.ColorDrawable;
40import android.graphics.drawable.Drawable;
41import android.os.Handler;
42import android.os.IBinder;
43import android.os.Message;
44import android.os.Parcel;
45import android.os.Parcelable;
46import android.os.RemoteException;
47import android.os.SystemClock;
48import android.util.AttributeSet;
49import android.util.FloatProperty;
50import android.util.LocaleUtil;
51import android.util.Log;
52import android.util.Pool;
53import android.util.Poolable;
54import android.util.PoolableManager;
55import android.util.Pools;
56import android.util.Property;
57import android.util.SparseArray;
58import android.util.TypedValue;
59import android.view.ContextMenu.ContextMenuInfo;
60import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityEventSource;
62import android.view.accessibility.AccessibilityManager;
63import android.view.accessibility.AccessibilityNodeInfo;
64import android.view.animation.Animation;
65import android.view.animation.AnimationUtils;
66import android.view.inputmethod.EditorInfo;
67import android.view.inputmethod.InputConnection;
68import android.view.inputmethod.InputMethodManager;
69import android.widget.ScrollBarDrawable;
70
71import com.android.internal.R;
72import com.android.internal.util.Predicate;
73import com.android.internal.view.menu.MenuBuilder;
74
75import java.lang.ref.WeakReference;
76import java.lang.reflect.InvocationTargetException;
77import java.lang.reflect.Method;
78import java.util.ArrayList;
79import java.util.Arrays;
80import java.util.Locale;
81import java.util.WeakHashMap;
82import java.util.concurrent.CopyOnWriteArrayList;
83
84/**
85 * <p>
86 * This class represents the basic building block for user interface components. A View
87 * occupies a rectangular area on the screen and is responsible for drawing and
88 * event handling. View is the base class for <em>widgets</em>, which are
89 * used to create interactive UI components (buttons, text fields, etc.). The
90 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
91 * are invisible containers that hold other Views (or other ViewGroups) and define
92 * their layout properties.
93 * </p>
94 *
95 * <div class="special">
96 * <p>For an introduction to using this class to develop your
97 * application's user interface, read the Developer Guide documentation on
98 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
99 * include:
100 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
101 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
102 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
104 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
105 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
106 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
107 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
108 * </p>
109 * </div>
110 *
111 * <a name="Using"></a>
112 * <h3>Using Views</h3>
113 * <p>
114 * All of the views in a window are arranged in a single tree. You can add views
115 * either from code or by specifying a tree of views in one or more XML layout
116 * files. There are many specialized subclasses of views that act as controls or
117 * are capable of displaying text, images, or other content.
118 * </p>
119 * <p>
120 * Once you have created a tree of views, there are typically a few types of
121 * common operations you may wish to perform:
122 * <ul>
123 * <li><strong>Set properties:</strong> for example setting the text of a
124 * {@link android.widget.TextView}. The available properties and the methods
125 * that set them will vary among the different subclasses of views. Note that
126 * properties that are known at build time can be set in the XML layout
127 * files.</li>
128 * <li><strong>Set focus:</strong> The framework will handled moving focus in
129 * response to user input. To force focus to a specific view, call
130 * {@link #requestFocus}.</li>
131 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
132 * that will be notified when something interesting happens to the view. For
133 * example, all views will let you set a listener to be notified when the view
134 * gains or loses focus. You can register such a listener using
135 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
136 * Other view subclasses offer more specialized listeners. For example, a Button
137 * exposes a listener to notify clients when the button is clicked.</li>
138 * <li><strong>Set visibility:</strong> You can hide or show views using
139 * {@link #setVisibility(int)}.</li>
140 * </ul>
141 * </p>
142 * <p><em>
143 * Note: The Android framework is responsible for measuring, laying out and
144 * drawing views. You should not call methods that perform these actions on
145 * views yourself unless you are actually implementing a
146 * {@link android.view.ViewGroup}.
147 * </em></p>
148 *
149 * <a name="Lifecycle"></a>
150 * <h3>Implementing a Custom View</h3>
151 *
152 * <p>
153 * To implement a custom view, you will usually begin by providing overrides for
154 * some of the standard methods that the framework calls on all views. You do
155 * not need to override all of these methods. In fact, you can start by just
156 * overriding {@link #onDraw(android.graphics.Canvas)}.
157 * <table border="2" width="85%" align="center" cellpadding="5">
158 *     <thead>
159 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
160 *     </thead>
161 *
162 *     <tbody>
163 *     <tr>
164 *         <td rowspan="2">Creation</td>
165 *         <td>Constructors</td>
166 *         <td>There is a form of the constructor that are called when the view
167 *         is created from code and a form that is called when the view is
168 *         inflated from a layout file. The second form should parse and apply
169 *         any attributes defined in the layout file.
170 *         </td>
171 *     </tr>
172 *     <tr>
173 *         <td><code>{@link #onFinishInflate()}</code></td>
174 *         <td>Called after a view and all of its children has been inflated
175 *         from XML.</td>
176 *     </tr>
177 *
178 *     <tr>
179 *         <td rowspan="3">Layout</td>
180 *         <td><code>{@link #onMeasure(int, int)}</code></td>
181 *         <td>Called to determine the size requirements for this view and all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
187 *         <td>Called when this view should assign a size and position to all
188 *         of its children.
189 *         </td>
190 *     </tr>
191 *     <tr>
192 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
193 *         <td>Called when the size of this view has changed.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td>Drawing</td>
199 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
200 *         <td>Called when the view should render its content.
201 *         </td>
202 *     </tr>
203 *
204 *     <tr>
205 *         <td rowspan="4">Event processing</td>
206 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
207 *         <td>Called when a new key event occurs.
208 *         </td>
209 *     </tr>
210 *     <tr>
211 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
212 *         <td>Called when a key up event occurs.
213 *         </td>
214 *     </tr>
215 *     <tr>
216 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
217 *         <td>Called when a trackball motion event occurs.
218 *         </td>
219 *     </tr>
220 *     <tr>
221 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
222 *         <td>Called when a touch screen motion event occurs.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td rowspan="2">Focus</td>
228 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
229 *         <td>Called when the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
235 *         <td>Called when the window containing the view gains or loses focus.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td rowspan="3">Attaching</td>
241 *         <td><code>{@link #onAttachedToWindow()}</code></td>
242 *         <td>Called when the view is attached to a window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onDetachedFromWindow}</code></td>
248 *         <td>Called when the view is detached from its window.
249 *         </td>
250 *     </tr>
251 *
252 *     <tr>
253 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
254 *         <td>Called when the visibility of the window containing the view
255 *         has changed.
256 *         </td>
257 *     </tr>
258 *     </tbody>
259 *
260 * </table>
261 * </p>
262 *
263 * <a name="IDs"></a>
264 * <h3>IDs</h3>
265 * Views may have an integer id associated with them. These ids are typically
266 * assigned in the layout XML files, and are used to find specific views within
267 * the view tree. A common pattern is to:
268 * <ul>
269 * <li>Define a Button in the layout file and assign it a unique ID.
270 * <pre>
271 * &lt;Button
272 *     android:id="@+id/my_button"
273 *     android:layout_width="wrap_content"
274 *     android:layout_height="wrap_content"
275 *     android:text="@string/my_button_text"/&gt;
276 * </pre></li>
277 * <li>From the onCreate method of an Activity, find the Button
278 * <pre class="prettyprint">
279 *      Button myButton = (Button) findViewById(R.id.my_button);
280 * </pre></li>
281 * </ul>
282 * <p>
283 * View IDs need not be unique throughout the tree, but it is good practice to
284 * ensure that they are at least unique within the part of the tree you are
285 * searching.
286 * </p>
287 *
288 * <a name="Position"></a>
289 * <h3>Position</h3>
290 * <p>
291 * The geometry of a view is that of a rectangle. A view has a location,
292 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
293 * two dimensions, expressed as a width and a height. The unit for location
294 * and dimensions is the pixel.
295 * </p>
296 *
297 * <p>
298 * It is possible to retrieve the location of a view by invoking the methods
299 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
300 * coordinate of the rectangle representing the view. The latter returns the
301 * top, or Y, coordinate of the rectangle representing the view. These methods
302 * both return the location of the view relative to its parent. For instance,
303 * when getLeft() returns 20, that means the view is located 20 pixels to the
304 * right of the left edge of its direct parent.
305 * </p>
306 *
307 * <p>
308 * In addition, several convenience methods are offered to avoid unnecessary
309 * computations, namely {@link #getRight()} and {@link #getBottom()}.
310 * These methods return the coordinates of the right and bottom edges of the
311 * rectangle representing the view. For instance, calling {@link #getRight()}
312 * is similar to the following computation: <code>getLeft() + getWidth()</code>
313 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
314 * </p>
315 *
316 * <a name="SizePaddingMargins"></a>
317 * <h3>Size, padding and margins</h3>
318 * <p>
319 * The size of a view is expressed with a width and a height. A view actually
320 * possess two pairs of width and height values.
321 * </p>
322 *
323 * <p>
324 * The first pair is known as <em>measured width</em> and
325 * <em>measured height</em>. These dimensions define how big a view wants to be
326 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
327 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
328 * and {@link #getMeasuredHeight()}.
329 * </p>
330 *
331 * <p>
332 * The second pair is simply known as <em>width</em> and <em>height</em>, or
333 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
334 * dimensions define the actual size of the view on screen, at drawing time and
335 * after layout. These values may, but do not have to, be different from the
336 * measured width and height. The width and height can be obtained by calling
337 * {@link #getWidth()} and {@link #getHeight()}.
338 * </p>
339 *
340 * <p>
341 * To measure its dimensions, a view takes into account its padding. The padding
342 * is expressed in pixels for the left, top, right and bottom parts of the view.
343 * Padding can be used to offset the content of the view by a specific amount of
344 * pixels. For instance, a left padding of 2 will push the view's content by
345 * 2 pixels to the right of the left edge. Padding can be set using the
346 * {@link #setPadding(int, int, int, int)} method and queried by calling
347 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
348 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
349 * </p>
350 *
351 * <p>
352 * Even though a view can define a padding, it does not provide any support for
353 * margins. However, view groups provide such a support. Refer to
354 * {@link android.view.ViewGroup} and
355 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
356 * </p>
357 *
358 * <a name="Layout"></a>
359 * <h3>Layout</h3>
360 * <p>
361 * Layout is a two pass process: a measure pass and a layout pass. The measuring
362 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
363 * of the view tree. Each view pushes dimension specifications down the tree
364 * during the recursion. At the end of the measure pass, every view has stored
365 * its measurements. The second pass happens in
366 * {@link #layout(int,int,int,int)} and is also top-down. During
367 * this pass each parent is responsible for positioning all of its children
368 * using the sizes computed in the measure pass.
369 * </p>
370 *
371 * <p>
372 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
373 * {@link #getMeasuredHeight()} values must be set, along with those for all of
374 * that view's descendants. A view's measured width and measured height values
375 * must respect the constraints imposed by the view's parents. This guarantees
376 * that at the end of the measure pass, all parents accept all of their
377 * children's measurements. A parent view may call measure() more than once on
378 * its children. For example, the parent may measure each child once with
379 * unspecified dimensions to find out how big they want to be, then call
380 * measure() on them again with actual numbers if the sum of all the children's
381 * unconstrained sizes is too big or too small.
382 * </p>
383 *
384 * <p>
385 * The measure pass uses two classes to communicate dimensions. The
386 * {@link MeasureSpec} class is used by views to tell their parents how they
387 * want to be measured and positioned. The base LayoutParams class just
388 * describes how big the view wants to be for both width and height. For each
389 * dimension, it can specify one of:
390 * <ul>
391 * <li> an exact number
392 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
393 * (minus padding)
394 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
395 * enclose its content (plus padding).
396 * </ul>
397 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
398 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
399 * an X and Y value.
400 * </p>
401 *
402 * <p>
403 * MeasureSpecs are used to push requirements down the tree from parent to
404 * child. A MeasureSpec can be in one of three modes:
405 * <ul>
406 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
407 * of a child view. For example, a LinearLayout may call measure() on its child
408 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
409 * tall the child view wants to be given a width of 240 pixels.
410 * <li>EXACTLY: This is used by the parent to impose an exact size on the
411 * child. The child must use this size, and guarantee that all of its
412 * descendants will fit within this size.
413 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
414 * child. The child must gurantee that it and all of its descendants will fit
415 * within this size.
416 * </ul>
417 * </p>
418 *
419 * <p>
420 * To intiate a layout, call {@link #requestLayout}. This method is typically
421 * called by a view on itself when it believes that is can no longer fit within
422 * its current bounds.
423 * </p>
424 *
425 * <a name="Drawing"></a>
426 * <h3>Drawing</h3>
427 * <p>
428 * Drawing is handled by walking the tree and rendering each view that
429 * intersects the the invalid region. Because the tree is traversed in-order,
430 * this means that parents will draw before (i.e., behind) their children, with
431 * siblings drawn in the order they appear in the tree.
432 * If you set a background drawable for a View, then the View will draw it for you
433 * before calling back to its <code>onDraw()</code> method.
434 * </p>
435 *
436 * <p>
437 * Note that the framework will not draw views that are not in the invalid region.
438 * </p>
439 *
440 * <p>
441 * To force a view to draw, call {@link #invalidate()}.
442 * </p>
443 *
444 * <a name="EventHandlingThreading"></a>
445 * <h3>Event Handling and Threading</h3>
446 * <p>
447 * The basic cycle of a view is as follows:
448 * <ol>
449 * <li>An event comes in and is dispatched to the appropriate view. The view
450 * handles the event and notifies any listeners.</li>
451 * <li>If in the course of processing the event, the view's bounds may need
452 * to be changed, the view will call {@link #requestLayout()}.</li>
453 * <li>Similarly, if in the course of processing the event the view's appearance
454 * may need to be changed, the view will call {@link #invalidate()}.</li>
455 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
456 * the framework will take care of measuring, laying out, and drawing the tree
457 * as appropriate.</li>
458 * </ol>
459 * </p>
460 *
461 * <p><em>Note: The entire view tree is single threaded. You must always be on
462 * the UI thread when calling any method on any view.</em>
463 * If you are doing work on other threads and want to update the state of a view
464 * from that thread, you should use a {@link Handler}.
465 * </p>
466 *
467 * <a name="FocusHandling"></a>
468 * <h3>Focus Handling</h3>
469 * <p>
470 * The framework will handle routine focus movement in response to user input.
471 * This includes changing the focus as views are removed or hidden, or as new
472 * views become available. Views indicate their willingness to take focus
473 * through the {@link #isFocusable} method. To change whether a view can take
474 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
475 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
476 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
477 * </p>
478 * <p>
479 * Focus movement is based on an algorithm which finds the nearest neighbor in a
480 * given direction. In rare cases, the default algorithm may not match the
481 * intended behavior of the developer. In these situations, you can provide
482 * explicit overrides by using these XML attributes in the layout file:
483 * <pre>
484 * nextFocusDown
485 * nextFocusLeft
486 * nextFocusRight
487 * nextFocusUp
488 * </pre>
489 * </p>
490 *
491 *
492 * <p>
493 * To get a particular view to take focus, call {@link #requestFocus()}.
494 * </p>
495 *
496 * <a name="TouchMode"></a>
497 * <h3>Touch Mode</h3>
498 * <p>
499 * When a user is navigating a user interface via directional keys such as a D-pad, it is
500 * necessary to give focus to actionable items such as buttons so the user can see
501 * what will take input.  If the device has touch capabilities, however, and the user
502 * begins interacting with the interface by touching it, it is no longer necessary to
503 * always highlight, or give focus to, a particular view.  This motivates a mode
504 * for interaction named 'touch mode'.
505 * </p>
506 * <p>
507 * For a touch capable device, once the user touches the screen, the device
508 * will enter touch mode.  From this point onward, only views for which
509 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
510 * Other views that are touchable, like buttons, will not take focus when touched; they will
511 * only fire the on click listeners.
512 * </p>
513 * <p>
514 * Any time a user hits a directional key, such as a D-pad direction, the view device will
515 * exit touch mode, and find a view to take focus, so that the user may resume interacting
516 * with the user interface without touching the screen again.
517 * </p>
518 * <p>
519 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
520 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
521 * </p>
522 *
523 * <a name="Scrolling"></a>
524 * <h3>Scrolling</h3>
525 * <p>
526 * The framework provides basic support for views that wish to internally
527 * scroll their content. This includes keeping track of the X and Y scroll
528 * offset as well as mechanisms for drawing scrollbars. See
529 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
530 * {@link #awakenScrollBars()} for more details.
531 * </p>
532 *
533 * <a name="Tags"></a>
534 * <h3>Tags</h3>
535 * <p>
536 * Unlike IDs, tags are not used to identify views. Tags are essentially an
537 * extra piece of information that can be associated with a view. They are most
538 * often used as a convenience to store data related to views in the views
539 * themselves rather than by putting them in a separate structure.
540 * </p>
541 *
542 * <a name="Animation"></a>
543 * <h3>Animation</h3>
544 * <p>
545 * You can attach an {@link Animation} object to a view using
546 * {@link #setAnimation(Animation)} or
547 * {@link #startAnimation(Animation)}. The animation can alter the scale,
548 * rotation, translation and alpha of a view over time. If the animation is
549 * attached to a view that has children, the animation will affect the entire
550 * subtree rooted by that node. When an animation is started, the framework will
551 * take care of redrawing the appropriate views until the animation completes.
552 * </p>
553 * <p>
554 * Starting with Android 3.0, the preferred way of animating views is to use the
555 * {@link android.animation} package APIs.
556 * </p>
557 *
558 * <a name="Security"></a>
559 * <h3>Security</h3>
560 * <p>
561 * Sometimes it is essential that an application be able to verify that an action
562 * is being performed with the full knowledge and consent of the user, such as
563 * granting a permission request, making a purchase or clicking on an advertisement.
564 * Unfortunately, a malicious application could try to spoof the user into
565 * performing these actions, unaware, by concealing the intended purpose of the view.
566 * As a remedy, the framework offers a touch filtering mechanism that can be used to
567 * improve the security of views that provide access to sensitive functionality.
568 * </p><p>
569 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
570 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
571 * will discard touches that are received whenever the view's window is obscured by
572 * another visible window.  As a result, the view will not receive touches whenever a
573 * toast, dialog or other window appears above the view's window.
574 * </p><p>
575 * For more fine-grained control over security, consider overriding the
576 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
577 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
578 * </p>
579 *
580 * @attr ref android.R.styleable#View_alpha
581 * @attr ref android.R.styleable#View_background
582 * @attr ref android.R.styleable#View_clickable
583 * @attr ref android.R.styleable#View_contentDescription
584 * @attr ref android.R.styleable#View_drawingCacheQuality
585 * @attr ref android.R.styleable#View_duplicateParentState
586 * @attr ref android.R.styleable#View_id
587 * @attr ref android.R.styleable#View_fadingEdge
588 * @attr ref android.R.styleable#View_fadingEdgeLength
589 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
590 * @attr ref android.R.styleable#View_fitsSystemWindows
591 * @attr ref android.R.styleable#View_isScrollContainer
592 * @attr ref android.R.styleable#View_focusable
593 * @attr ref android.R.styleable#View_focusableInTouchMode
594 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
595 * @attr ref android.R.styleable#View_keepScreenOn
596 * @attr ref android.R.styleable#View_layerType
597 * @attr ref android.R.styleable#View_longClickable
598 * @attr ref android.R.styleable#View_minHeight
599 * @attr ref android.R.styleable#View_minWidth
600 * @attr ref android.R.styleable#View_nextFocusDown
601 * @attr ref android.R.styleable#View_nextFocusLeft
602 * @attr ref android.R.styleable#View_nextFocusRight
603 * @attr ref android.R.styleable#View_nextFocusUp
604 * @attr ref android.R.styleable#View_onClick
605 * @attr ref android.R.styleable#View_padding
606 * @attr ref android.R.styleable#View_paddingBottom
607 * @attr ref android.R.styleable#View_paddingLeft
608 * @attr ref android.R.styleable#View_paddingRight
609 * @attr ref android.R.styleable#View_paddingTop
610 * @attr ref android.R.styleable#View_saveEnabled
611 * @attr ref android.R.styleable#View_rotation
612 * @attr ref android.R.styleable#View_rotationX
613 * @attr ref android.R.styleable#View_rotationY
614 * @attr ref android.R.styleable#View_scaleX
615 * @attr ref android.R.styleable#View_scaleY
616 * @attr ref android.R.styleable#View_scrollX
617 * @attr ref android.R.styleable#View_scrollY
618 * @attr ref android.R.styleable#View_scrollbarSize
619 * @attr ref android.R.styleable#View_scrollbarStyle
620 * @attr ref android.R.styleable#View_scrollbars
621 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
622 * @attr ref android.R.styleable#View_scrollbarFadeDuration
623 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
624 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
625 * @attr ref android.R.styleable#View_scrollbarThumbVertical
626 * @attr ref android.R.styleable#View_scrollbarTrackVertical
627 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
628 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
629 * @attr ref android.R.styleable#View_soundEffectsEnabled
630 * @attr ref android.R.styleable#View_tag
631 * @attr ref android.R.styleable#View_transformPivotX
632 * @attr ref android.R.styleable#View_transformPivotY
633 * @attr ref android.R.styleable#View_translationX
634 * @attr ref android.R.styleable#View_translationY
635 * @attr ref android.R.styleable#View_visibility
636 *
637 * @see android.view.ViewGroup
638 */
639public class View implements Drawable.Callback2, KeyEvent.Callback, AccessibilityEventSource {
640    private static final boolean DBG = false;
641
642    /**
643     * The logging tag used by this class with android.util.Log.
644     */
645    protected static final String VIEW_LOG_TAG = "View";
646
647    /**
648     * Used to mark a View that has no ID.
649     */
650    public static final int NO_ID = -1;
651
652    /**
653     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
654     * calling setFlags.
655     */
656    private static final int NOT_FOCUSABLE = 0x00000000;
657
658    /**
659     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
660     * setFlags.
661     */
662    private static final int FOCUSABLE = 0x00000001;
663
664    /**
665     * Mask for use with setFlags indicating bits used for focus.
666     */
667    private static final int FOCUSABLE_MASK = 0x00000001;
668
669    /**
670     * This view will adjust its padding to fit sytem windows (e.g. status bar)
671     */
672    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
673
674    /**
675     * This view is visible.
676     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
677     * android:visibility}.
678     */
679    public static final int VISIBLE = 0x00000000;
680
681    /**
682     * This view is invisible, but it still takes up space for layout purposes.
683     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
684     * android:visibility}.
685     */
686    public static final int INVISIBLE = 0x00000004;
687
688    /**
689     * This view is invisible, and it doesn't take any space for layout
690     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
691     * android:visibility}.
692     */
693    public static final int GONE = 0x00000008;
694
695    /**
696     * Mask for use with setFlags indicating bits used for visibility.
697     * {@hide}
698     */
699    static final int VISIBILITY_MASK = 0x0000000C;
700
701    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
702
703    /**
704     * This view is enabled. Intrepretation varies by subclass.
705     * Use with ENABLED_MASK when calling setFlags.
706     * {@hide}
707     */
708    static final int ENABLED = 0x00000000;
709
710    /**
711     * This view is disabled. Intrepretation varies by subclass.
712     * Use with ENABLED_MASK when calling setFlags.
713     * {@hide}
714     */
715    static final int DISABLED = 0x00000020;
716
717   /**
718    * Mask for use with setFlags indicating bits used for indicating whether
719    * this view is enabled
720    * {@hide}
721    */
722    static final int ENABLED_MASK = 0x00000020;
723
724    /**
725     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
726     * called and further optimizations will be performed. It is okay to have
727     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
728     * {@hide}
729     */
730    static final int WILL_NOT_DRAW = 0x00000080;
731
732    /**
733     * Mask for use with setFlags indicating bits used for indicating whether
734     * this view is will draw
735     * {@hide}
736     */
737    static final int DRAW_MASK = 0x00000080;
738
739    /**
740     * <p>This view doesn't show scrollbars.</p>
741     * {@hide}
742     */
743    static final int SCROLLBARS_NONE = 0x00000000;
744
745    /**
746     * <p>This view shows horizontal scrollbars.</p>
747     * {@hide}
748     */
749    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
750
751    /**
752     * <p>This view shows vertical scrollbars.</p>
753     * {@hide}
754     */
755    static final int SCROLLBARS_VERTICAL = 0x00000200;
756
757    /**
758     * <p>Mask for use with setFlags indicating bits used for indicating which
759     * scrollbars are enabled.</p>
760     * {@hide}
761     */
762    static final int SCROLLBARS_MASK = 0x00000300;
763
764    /**
765     * Indicates that the view should filter touches when its window is obscured.
766     * Refer to the class comments for more information about this security feature.
767     * {@hide}
768     */
769    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
770
771    // note flag value 0x00000800 is now available for next flags...
772
773    /**
774     * <p>This view doesn't show fading edges.</p>
775     * {@hide}
776     */
777    static final int FADING_EDGE_NONE = 0x00000000;
778
779    /**
780     * <p>This view shows horizontal fading edges.</p>
781     * {@hide}
782     */
783    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
784
785    /**
786     * <p>This view shows vertical fading edges.</p>
787     * {@hide}
788     */
789    static final int FADING_EDGE_VERTICAL = 0x00002000;
790
791    /**
792     * <p>Mask for use with setFlags indicating bits used for indicating which
793     * fading edges are enabled.</p>
794     * {@hide}
795     */
796    static final int FADING_EDGE_MASK = 0x00003000;
797
798    /**
799     * <p>Indicates this view can be clicked. When clickable, a View reacts
800     * to clicks by notifying the OnClickListener.<p>
801     * {@hide}
802     */
803    static final int CLICKABLE = 0x00004000;
804
805    /**
806     * <p>Indicates this view is caching its drawing into a bitmap.</p>
807     * {@hide}
808     */
809    static final int DRAWING_CACHE_ENABLED = 0x00008000;
810
811    /**
812     * <p>Indicates that no icicle should be saved for this view.<p>
813     * {@hide}
814     */
815    static final int SAVE_DISABLED = 0x000010000;
816
817    /**
818     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
819     * property.</p>
820     * {@hide}
821     */
822    static final int SAVE_DISABLED_MASK = 0x000010000;
823
824    /**
825     * <p>Indicates that no drawing cache should ever be created for this view.<p>
826     * {@hide}
827     */
828    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
829
830    /**
831     * <p>Indicates this view can take / keep focus when int touch mode.</p>
832     * {@hide}
833     */
834    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
835
836    /**
837     * <p>Enables low quality mode for the drawing cache.</p>
838     */
839    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
840
841    /**
842     * <p>Enables high quality mode for the drawing cache.</p>
843     */
844    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
845
846    /**
847     * <p>Enables automatic quality mode for the drawing cache.</p>
848     */
849    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
850
851    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
852            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
853    };
854
855    /**
856     * <p>Mask for use with setFlags indicating bits used for the cache
857     * quality property.</p>
858     * {@hide}
859     */
860    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
861
862    /**
863     * <p>
864     * Indicates this view can be long clicked. When long clickable, a View
865     * reacts to long clicks by notifying the OnLongClickListener or showing a
866     * context menu.
867     * </p>
868     * {@hide}
869     */
870    static final int LONG_CLICKABLE = 0x00200000;
871
872    /**
873     * <p>Indicates that this view gets its drawable states from its direct parent
874     * and ignores its original internal states.</p>
875     *
876     * @hide
877     */
878    static final int DUPLICATE_PARENT_STATE = 0x00400000;
879
880    /**
881     * The scrollbar style to display the scrollbars inside the content area,
882     * without increasing the padding. The scrollbars will be overlaid with
883     * translucency on the view's content.
884     */
885    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
886
887    /**
888     * The scrollbar style to display the scrollbars inside the padded area,
889     * increasing the padding of the view. The scrollbars will not overlap the
890     * content area of the view.
891     */
892    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
893
894    /**
895     * The scrollbar style to display the scrollbars at the edge of the view,
896     * without increasing the padding. The scrollbars will be overlaid with
897     * translucency.
898     */
899    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
900
901    /**
902     * The scrollbar style to display the scrollbars at the edge of the view,
903     * increasing the padding of the view. The scrollbars will only overlap the
904     * background, if any.
905     */
906    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
907
908    /**
909     * Mask to check if the scrollbar style is overlay or inset.
910     * {@hide}
911     */
912    static final int SCROLLBARS_INSET_MASK = 0x01000000;
913
914    /**
915     * Mask to check if the scrollbar style is inside or outside.
916     * {@hide}
917     */
918    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
919
920    /**
921     * Mask for scrollbar style.
922     * {@hide}
923     */
924    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
925
926    /**
927     * View flag indicating that the screen should remain on while the
928     * window containing this view is visible to the user.  This effectively
929     * takes care of automatically setting the WindowManager's
930     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
931     */
932    public static final int KEEP_SCREEN_ON = 0x04000000;
933
934    /**
935     * View flag indicating whether this view should have sound effects enabled
936     * for events such as clicking and touching.
937     */
938    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
939
940    /**
941     * View flag indicating whether this view should have haptic feedback
942     * enabled for events such as long presses.
943     */
944    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
945
946    /**
947     * <p>Indicates that the view hierarchy should stop saving state when
948     * it reaches this view.  If state saving is initiated immediately at
949     * the view, it will be allowed.
950     * {@hide}
951     */
952    static final int PARENT_SAVE_DISABLED = 0x20000000;
953
954    /**
955     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
956     * {@hide}
957     */
958    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
959
960    /**
961     * Horizontal direction of this view is from Left to Right.
962     * Use with {@link #setLayoutDirection}.
963     * {@hide}
964     */
965    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
966
967    /**
968     * Horizontal direction of this view is from Right to Left.
969     * Use with {@link #setLayoutDirection}.
970     * {@hide}
971     */
972    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
973
974    /**
975     * Horizontal direction of this view is inherited from its parent.
976     * Use with {@link #setLayoutDirection}.
977     * {@hide}
978     */
979    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
980
981    /**
982     * Horizontal direction of this view is from deduced from the default language
983     * script for the locale. Use with {@link #setLayoutDirection}.
984     * {@hide}
985     */
986    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
987
988    /**
989     * Mask for use with setFlags indicating bits used for horizontalDirection.
990     * {@hide}
991     */
992    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
993
994    /*
995     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
996     * flag value.
997     * {@hide}
998     */
999    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
1000        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
1001
1002    /**
1003     * Default horizontalDirection.
1004     * {@hide}
1005     */
1006    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1007
1008    /**
1009     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1010     * should add all focusable Views regardless if they are focusable in touch mode.
1011     */
1012    public static final int FOCUSABLES_ALL = 0x00000000;
1013
1014    /**
1015     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1016     * should add only Views focusable in touch mode.
1017     */
1018    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1019
1020    /**
1021     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1022     * item.
1023     */
1024    public static final int FOCUS_BACKWARD = 0x00000001;
1025
1026    /**
1027     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1028     * item.
1029     */
1030    public static final int FOCUS_FORWARD = 0x00000002;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus to the left.
1034     */
1035    public static final int FOCUS_LEFT = 0x00000011;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus up.
1039     */
1040    public static final int FOCUS_UP = 0x00000021;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus to the right.
1044     */
1045    public static final int FOCUS_RIGHT = 0x00000042;
1046
1047    /**
1048     * Use with {@link #focusSearch(int)}. Move focus down.
1049     */
1050    public static final int FOCUS_DOWN = 0x00000082;
1051
1052    /**
1053     * Bits of {@link #getMeasuredWidthAndState()} and
1054     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1055     */
1056    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1057
1058    /**
1059     * Bits of {@link #getMeasuredWidthAndState()} and
1060     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1061     */
1062    public static final int MEASURED_STATE_MASK = 0xff000000;
1063
1064    /**
1065     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1066     * for functions that combine both width and height into a single int,
1067     * such as {@link #getMeasuredState()} and the childState argument of
1068     * {@link #resolveSizeAndState(int, int, int)}.
1069     */
1070    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1071
1072    /**
1073     * Bit of {@link #getMeasuredWidthAndState()} and
1074     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1075     * is smaller that the space the view would like to have.
1076     */
1077    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1078
1079    /**
1080     * Base View state sets
1081     */
1082    // Singles
1083    /**
1084     * Indicates the view has no states set. States are used with
1085     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1086     * view depending on its state.
1087     *
1088     * @see android.graphics.drawable.Drawable
1089     * @see #getDrawableState()
1090     */
1091    protected static final int[] EMPTY_STATE_SET;
1092    /**
1093     * Indicates the view is enabled. States are used with
1094     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1095     * view depending on its state.
1096     *
1097     * @see android.graphics.drawable.Drawable
1098     * @see #getDrawableState()
1099     */
1100    protected static final int[] ENABLED_STATE_SET;
1101    /**
1102     * Indicates the view is focused. States are used with
1103     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1104     * view depending on its state.
1105     *
1106     * @see android.graphics.drawable.Drawable
1107     * @see #getDrawableState()
1108     */
1109    protected static final int[] FOCUSED_STATE_SET;
1110    /**
1111     * Indicates the view is selected. States are used with
1112     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1113     * view depending on its state.
1114     *
1115     * @see android.graphics.drawable.Drawable
1116     * @see #getDrawableState()
1117     */
1118    protected static final int[] SELECTED_STATE_SET;
1119    /**
1120     * Indicates the view is pressed. States are used with
1121     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1122     * view depending on its state.
1123     *
1124     * @see android.graphics.drawable.Drawable
1125     * @see #getDrawableState()
1126     * @hide
1127     */
1128    protected static final int[] PRESSED_STATE_SET;
1129    /**
1130     * Indicates the view's window has focus. States are used with
1131     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1132     * view depending on its state.
1133     *
1134     * @see android.graphics.drawable.Drawable
1135     * @see #getDrawableState()
1136     */
1137    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1138    // Doubles
1139    /**
1140     * Indicates the view is enabled and has the focus.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #FOCUSED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and selected.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #SELECTED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_SELECTED_STATE_SET;
1153    /**
1154     * Indicates the view is enabled and that its window has focus.
1155     *
1156     * @see #ENABLED_STATE_SET
1157     * @see #WINDOW_FOCUSED_STATE_SET
1158     */
1159    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1160    /**
1161     * Indicates the view is focused and selected.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #SELECTED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1167    /**
1168     * Indicates the view has the focus and that its window has the focus.
1169     *
1170     * @see #FOCUSED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1174    /**
1175     * Indicates the view is selected and that its window has the focus.
1176     *
1177     * @see #SELECTED_STATE_SET
1178     * @see #WINDOW_FOCUSED_STATE_SET
1179     */
1180    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1181    // Triples
1182    /**
1183     * Indicates the view is enabled, focused and selected.
1184     *
1185     * @see #ENABLED_STATE_SET
1186     * @see #FOCUSED_STATE_SET
1187     * @see #SELECTED_STATE_SET
1188     */
1189    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1190    /**
1191     * Indicates the view is enabled, focused and its window has the focus.
1192     *
1193     * @see #ENABLED_STATE_SET
1194     * @see #FOCUSED_STATE_SET
1195     * @see #WINDOW_FOCUSED_STATE_SET
1196     */
1197    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1198    /**
1199     * Indicates the view is enabled, selected and its window has the focus.
1200     *
1201     * @see #ENABLED_STATE_SET
1202     * @see #SELECTED_STATE_SET
1203     * @see #WINDOW_FOCUSED_STATE_SET
1204     */
1205    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1206    /**
1207     * Indicates the view is focused, selected and its window has the focus.
1208     *
1209     * @see #FOCUSED_STATE_SET
1210     * @see #SELECTED_STATE_SET
1211     * @see #WINDOW_FOCUSED_STATE_SET
1212     */
1213    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1214    /**
1215     * Indicates the view is enabled, focused, selected and its window
1216     * has the focus.
1217     *
1218     * @see #ENABLED_STATE_SET
1219     * @see #FOCUSED_STATE_SET
1220     * @see #SELECTED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and its window has the focus.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #WINDOW_FOCUSED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed and selected.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     */
1237    protected static final int[] PRESSED_SELECTED_STATE_SET;
1238    /**
1239     * Indicates the view is pressed, selected and its window has the focus.
1240     *
1241     * @see #PRESSED_STATE_SET
1242     * @see #SELECTED_STATE_SET
1243     * @see #WINDOW_FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed and focused.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     */
1252    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1253    /**
1254     * Indicates the view is pressed, focused and its window has the focus.
1255     *
1256     * @see #PRESSED_STATE_SET
1257     * @see #FOCUSED_STATE_SET
1258     * @see #WINDOW_FOCUSED_STATE_SET
1259     */
1260    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1261    /**
1262     * Indicates the view is pressed, focused and selected.
1263     *
1264     * @see #PRESSED_STATE_SET
1265     * @see #SELECTED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     */
1268    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1269    /**
1270     * Indicates the view is pressed, focused, selected and its window has the focus.
1271     *
1272     * @see #PRESSED_STATE_SET
1273     * @see #FOCUSED_STATE_SET
1274     * @see #SELECTED_STATE_SET
1275     * @see #WINDOW_FOCUSED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed and enabled.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     */
1284    protected static final int[] PRESSED_ENABLED_STATE_SET;
1285    /**
1286     * Indicates the view is pressed, enabled and its window has the focus.
1287     *
1288     * @see #PRESSED_STATE_SET
1289     * @see #ENABLED_STATE_SET
1290     * @see #WINDOW_FOCUSED_STATE_SET
1291     */
1292    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1293    /**
1294     * Indicates the view is pressed, enabled and selected.
1295     *
1296     * @see #PRESSED_STATE_SET
1297     * @see #ENABLED_STATE_SET
1298     * @see #SELECTED_STATE_SET
1299     */
1300    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1301    /**
1302     * Indicates the view is pressed, enabled, selected and its window has the
1303     * focus.
1304     *
1305     * @see #PRESSED_STATE_SET
1306     * @see #ENABLED_STATE_SET
1307     * @see #SELECTED_STATE_SET
1308     * @see #WINDOW_FOCUSED_STATE_SET
1309     */
1310    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1311    /**
1312     * Indicates the view is pressed, enabled and focused.
1313     *
1314     * @see #PRESSED_STATE_SET
1315     * @see #ENABLED_STATE_SET
1316     * @see #FOCUSED_STATE_SET
1317     */
1318    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1319    /**
1320     * Indicates the view is pressed, enabled, focused and its window has the
1321     * focus.
1322     *
1323     * @see #PRESSED_STATE_SET
1324     * @see #ENABLED_STATE_SET
1325     * @see #FOCUSED_STATE_SET
1326     * @see #WINDOW_FOCUSED_STATE_SET
1327     */
1328    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1329    /**
1330     * Indicates the view is pressed, enabled, focused and selected.
1331     *
1332     * @see #PRESSED_STATE_SET
1333     * @see #ENABLED_STATE_SET
1334     * @see #SELECTED_STATE_SET
1335     * @see #FOCUSED_STATE_SET
1336     */
1337    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1338    /**
1339     * Indicates the view is pressed, enabled, focused, selected and its window
1340     * has the focus.
1341     *
1342     * @see #PRESSED_STATE_SET
1343     * @see #ENABLED_STATE_SET
1344     * @see #SELECTED_STATE_SET
1345     * @see #FOCUSED_STATE_SET
1346     * @see #WINDOW_FOCUSED_STATE_SET
1347     */
1348    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1349
1350    /**
1351     * The order here is very important to {@link #getDrawableState()}
1352     */
1353    private static final int[][] VIEW_STATE_SETS;
1354
1355    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1356    static final int VIEW_STATE_SELECTED = 1 << 1;
1357    static final int VIEW_STATE_FOCUSED = 1 << 2;
1358    static final int VIEW_STATE_ENABLED = 1 << 3;
1359    static final int VIEW_STATE_PRESSED = 1 << 4;
1360    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1361    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1362    static final int VIEW_STATE_HOVERED = 1 << 7;
1363    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1364    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1365
1366    static final int[] VIEW_STATE_IDS = new int[] {
1367        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1368        R.attr.state_selected,          VIEW_STATE_SELECTED,
1369        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1370        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1371        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1372        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1373        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1374        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1375        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1376        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1377    };
1378
1379    static {
1380        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1381            throw new IllegalStateException(
1382                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1383        }
1384        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1385        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1386            int viewState = R.styleable.ViewDrawableStates[i];
1387            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1388                if (VIEW_STATE_IDS[j] == viewState) {
1389                    orderedIds[i * 2] = viewState;
1390                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1391                }
1392            }
1393        }
1394        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1395        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1396        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1397            int numBits = Integer.bitCount(i);
1398            int[] set = new int[numBits];
1399            int pos = 0;
1400            for (int j = 0; j < orderedIds.length; j += 2) {
1401                if ((i & orderedIds[j+1]) != 0) {
1402                    set[pos++] = orderedIds[j];
1403                }
1404            }
1405            VIEW_STATE_SETS[i] = set;
1406        }
1407
1408        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1409        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1410        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1411        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1413        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1414        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1416        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1417                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1418        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1419                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1420                | VIEW_STATE_FOCUSED];
1421        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1422        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1426        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1431        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1432                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1433                | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1439                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1440
1441        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1442        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1446        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1451        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1452                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1453                | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1459                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1462        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1463                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1464                | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1470                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1473                | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1476                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1482                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1483                | VIEW_STATE_PRESSED];
1484    }
1485
1486    /**
1487     * Temporary Rect currently for use in setBackground().  This will probably
1488     * be extended in the future to hold our own class with more than just
1489     * a Rect. :)
1490     */
1491    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1492
1493    /**
1494     * Map used to store views' tags.
1495     */
1496    private static WeakHashMap<View, SparseArray<Object>> sTags;
1497
1498    /**
1499     * Lock used to access sTags.
1500     */
1501    private static final Object sTagsLock = new Object();
1502
1503    /**
1504     * The next available accessiiblity id.
1505     */
1506    private static int sNextAccessibilityViewId;
1507
1508    /**
1509     * The animation currently associated with this view.
1510     * @hide
1511     */
1512    protected Animation mCurrentAnimation = null;
1513
1514    /**
1515     * Width as measured during measure pass.
1516     * {@hide}
1517     */
1518    @ViewDebug.ExportedProperty(category = "measurement")
1519    int mMeasuredWidth;
1520
1521    /**
1522     * Height as measured during measure pass.
1523     * {@hide}
1524     */
1525    @ViewDebug.ExportedProperty(category = "measurement")
1526    int mMeasuredHeight;
1527
1528    /**
1529     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1530     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1531     * its display list. This flag, used only when hw accelerated, allows us to clear the
1532     * flag while retaining this information until it's needed (at getDisplayList() time and
1533     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1534     *
1535     * {@hide}
1536     */
1537    boolean mRecreateDisplayList = false;
1538
1539    /**
1540     * The view's identifier.
1541     * {@hide}
1542     *
1543     * @see #setId(int)
1544     * @see #getId()
1545     */
1546    @ViewDebug.ExportedProperty(resolveId = true)
1547    int mID = NO_ID;
1548
1549    /**
1550     * The stable ID of this view for accessibility porposes.
1551     */
1552    int mAccessibilityViewId = NO_ID;
1553
1554    /**
1555     * The view's tag.
1556     * {@hide}
1557     *
1558     * @see #setTag(Object)
1559     * @see #getTag()
1560     */
1561    protected Object mTag;
1562
1563    // for mPrivateFlags:
1564    /** {@hide} */
1565    static final int WANTS_FOCUS                    = 0x00000001;
1566    /** {@hide} */
1567    static final int FOCUSED                        = 0x00000002;
1568    /** {@hide} */
1569    static final int SELECTED                       = 0x00000004;
1570    /** {@hide} */
1571    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1572    /** {@hide} */
1573    static final int HAS_BOUNDS                     = 0x00000010;
1574    /** {@hide} */
1575    static final int DRAWN                          = 0x00000020;
1576    /**
1577     * When this flag is set, this view is running an animation on behalf of its
1578     * children and should therefore not cancel invalidate requests, even if they
1579     * lie outside of this view's bounds.
1580     *
1581     * {@hide}
1582     */
1583    static final int DRAW_ANIMATION                 = 0x00000040;
1584    /** {@hide} */
1585    static final int SKIP_DRAW                      = 0x00000080;
1586    /** {@hide} */
1587    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1588    /** {@hide} */
1589    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1590    /** {@hide} */
1591    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1592    /** {@hide} */
1593    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1594    /** {@hide} */
1595    static final int FORCE_LAYOUT                   = 0x00001000;
1596    /** {@hide} */
1597    static final int LAYOUT_REQUIRED                = 0x00002000;
1598
1599    private static final int PRESSED                = 0x00004000;
1600
1601    /** {@hide} */
1602    static final int DRAWING_CACHE_VALID            = 0x00008000;
1603    /**
1604     * Flag used to indicate that this view should be drawn once more (and only once
1605     * more) after its animation has completed.
1606     * {@hide}
1607     */
1608    static final int ANIMATION_STARTED              = 0x00010000;
1609
1610    private static final int SAVE_STATE_CALLED      = 0x00020000;
1611
1612    /**
1613     * Indicates that the View returned true when onSetAlpha() was called and that
1614     * the alpha must be restored.
1615     * {@hide}
1616     */
1617    static final int ALPHA_SET                      = 0x00040000;
1618
1619    /**
1620     * Set by {@link #setScrollContainer(boolean)}.
1621     */
1622    static final int SCROLL_CONTAINER               = 0x00080000;
1623
1624    /**
1625     * Set by {@link #setScrollContainer(boolean)}.
1626     */
1627    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1628
1629    /**
1630     * View flag indicating whether this view was invalidated (fully or partially.)
1631     *
1632     * @hide
1633     */
1634    static final int DIRTY                          = 0x00200000;
1635
1636    /**
1637     * View flag indicating whether this view was invalidated by an opaque
1638     * invalidate request.
1639     *
1640     * @hide
1641     */
1642    static final int DIRTY_OPAQUE                   = 0x00400000;
1643
1644    /**
1645     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1646     *
1647     * @hide
1648     */
1649    static final int DIRTY_MASK                     = 0x00600000;
1650
1651    /**
1652     * Indicates whether the background is opaque.
1653     *
1654     * @hide
1655     */
1656    static final int OPAQUE_BACKGROUND              = 0x00800000;
1657
1658    /**
1659     * Indicates whether the scrollbars are opaque.
1660     *
1661     * @hide
1662     */
1663    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1664
1665    /**
1666     * Indicates whether the view is opaque.
1667     *
1668     * @hide
1669     */
1670    static final int OPAQUE_MASK                    = 0x01800000;
1671
1672    /**
1673     * Indicates a prepressed state;
1674     * the short time between ACTION_DOWN and recognizing
1675     * a 'real' press. Prepressed is used to recognize quick taps
1676     * even when they are shorter than ViewConfiguration.getTapTimeout().
1677     *
1678     * @hide
1679     */
1680    private static final int PREPRESSED             = 0x02000000;
1681
1682    /**
1683     * Indicates whether the view is temporarily detached.
1684     *
1685     * @hide
1686     */
1687    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1688
1689    /**
1690     * Indicates that we should awaken scroll bars once attached
1691     *
1692     * @hide
1693     */
1694    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1695
1696    /**
1697     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1698     * @hide
1699     */
1700    private static final int HOVERED              = 0x10000000;
1701
1702    /**
1703     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1704     * for transform operations
1705     *
1706     * @hide
1707     */
1708    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1709
1710    /** {@hide} */
1711    static final int ACTIVATED                    = 0x40000000;
1712
1713    /**
1714     * Indicates that this view was specifically invalidated, not just dirtied because some
1715     * child view was invalidated. The flag is used to determine when we need to recreate
1716     * a view's display list (as opposed to just returning a reference to its existing
1717     * display list).
1718     *
1719     * @hide
1720     */
1721    static final int INVALIDATED                  = 0x80000000;
1722
1723    /* Masks for mPrivateFlags2 */
1724
1725    /**
1726     * Indicates that this view has reported that it can accept the current drag's content.
1727     * Cleared when the drag operation concludes.
1728     * @hide
1729     */
1730    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1731
1732    /**
1733     * Indicates that this view is currently directly under the drag location in a
1734     * drag-and-drop operation involving content that it can accept.  Cleared when
1735     * the drag exits the view, or when the drag operation concludes.
1736     * @hide
1737     */
1738    static final int DRAG_HOVERED                 = 0x00000002;
1739
1740    /**
1741     * Indicates whether the view layout direction has been resolved and drawn to the
1742     * right-to-left direction.
1743     *
1744     * @hide
1745     */
1746    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1747
1748    /**
1749     * Indicates whether the view layout direction has been resolved.
1750     *
1751     * @hide
1752     */
1753    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1754
1755
1756    /* End of masks for mPrivateFlags2 */
1757
1758    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1759
1760    /**
1761     * Always allow a user to over-scroll this view, provided it is a
1762     * view that can scroll.
1763     *
1764     * @see #getOverScrollMode()
1765     * @see #setOverScrollMode(int)
1766     */
1767    public static final int OVER_SCROLL_ALWAYS = 0;
1768
1769    /**
1770     * Allow a user to over-scroll this view only if the content is large
1771     * enough to meaningfully scroll, provided it is a view that can scroll.
1772     *
1773     * @see #getOverScrollMode()
1774     * @see #setOverScrollMode(int)
1775     */
1776    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1777
1778    /**
1779     * Never allow a user to over-scroll this view.
1780     *
1781     * @see #getOverScrollMode()
1782     * @see #setOverScrollMode(int)
1783     */
1784    public static final int OVER_SCROLL_NEVER = 2;
1785
1786    /**
1787     * View has requested the system UI (status bar) to be visible (the default).
1788     *
1789     * @see #setSystemUiVisibility(int)
1790     */
1791    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1792
1793    /**
1794     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1795     *
1796     * This is for use in games, book readers, video players, or any other "immersive" application
1797     * where the usual system chrome is deemed too distracting.
1798     *
1799     * In low profile mode, the status bar and/or navigation icons may dim.
1800     *
1801     * @see #setSystemUiVisibility(int)
1802     */
1803    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1804
1805    /**
1806     * View has requested that the system navigation be temporarily hidden.
1807     *
1808     * This is an even less obtrusive state than that called for by
1809     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1810     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1811     * those to disappear. This is useful (in conjunction with the
1812     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1813     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1814     * window flags) for displaying content using every last pixel on the display.
1815     *
1816     * There is a limitation: because navigation controls are so important, the least user
1817     * interaction will cause them to reappear immediately.
1818     *
1819     * @see #setSystemUiVisibility(int)
1820     */
1821    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1822
1823    /**
1824     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1825     */
1826    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1827
1828    /**
1829     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1830     */
1831    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1832
1833    /**
1834     * @hide
1835     *
1836     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1837     * out of the public fields to keep the undefined bits out of the developer's way.
1838     *
1839     * Flag to make the status bar not expandable.  Unless you also
1840     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1841     */
1842    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1843
1844    /**
1845     * @hide
1846     *
1847     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1848     * out of the public fields to keep the undefined bits out of the developer's way.
1849     *
1850     * Flag to hide notification icons and scrolling ticker text.
1851     */
1852    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1853
1854    /**
1855     * @hide
1856     *
1857     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1858     * out of the public fields to keep the undefined bits out of the developer's way.
1859     *
1860     * Flag to disable incoming notification alerts.  This will not block
1861     * icons, but it will block sound, vibrating and other visual or aural notifications.
1862     */
1863    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1864
1865    /**
1866     * @hide
1867     *
1868     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1869     * out of the public fields to keep the undefined bits out of the developer's way.
1870     *
1871     * Flag to hide only the scrolling ticker.  Note that
1872     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1873     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1874     */
1875    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1876
1877    /**
1878     * @hide
1879     *
1880     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1881     * out of the public fields to keep the undefined bits out of the developer's way.
1882     *
1883     * Flag to hide the center system info area.
1884     */
1885    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1886
1887    /**
1888     * @hide
1889     *
1890     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1891     * out of the public fields to keep the undefined bits out of the developer's way.
1892     *
1893     * Flag to hide only the navigation buttons.  Don't use this
1894     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1895     *
1896     * THIS DOES NOT DISABLE THE BACK BUTTON
1897     */
1898    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1899
1900    /**
1901     * @hide
1902     *
1903     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1904     * out of the public fields to keep the undefined bits out of the developer's way.
1905     *
1906     * Flag to hide only the back button.  Don't use this
1907     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1908     */
1909    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1910
1911    /**
1912     * @hide
1913     *
1914     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1915     * out of the public fields to keep the undefined bits out of the developer's way.
1916     *
1917     * Flag to hide only the clock.  You might use this if your activity has
1918     * its own clock making the status bar's clock redundant.
1919     */
1920    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1921
1922    /**
1923     * @hide
1924     */
1925    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1926
1927    /**
1928     * Controls the over-scroll mode for this view.
1929     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1930     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1931     * and {@link #OVER_SCROLL_NEVER}.
1932     */
1933    private int mOverScrollMode;
1934
1935    /**
1936     * The parent this view is attached to.
1937     * {@hide}
1938     *
1939     * @see #getParent()
1940     */
1941    protected ViewParent mParent;
1942
1943    /**
1944     * {@hide}
1945     */
1946    AttachInfo mAttachInfo;
1947
1948    /**
1949     * {@hide}
1950     */
1951    @ViewDebug.ExportedProperty(flagMapping = {
1952        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1953                name = "FORCE_LAYOUT"),
1954        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1955                name = "LAYOUT_REQUIRED"),
1956        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1957            name = "DRAWING_CACHE_INVALID", outputIf = false),
1958        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1959        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1960        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1961        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1962    })
1963    int mPrivateFlags;
1964    int mPrivateFlags2;
1965
1966    /**
1967     * This view's request for the visibility of the status bar.
1968     * @hide
1969     */
1970    @ViewDebug.ExportedProperty(flagMapping = {
1971        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
1972                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
1973                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
1974        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1975                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1976                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
1977        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
1978                                equals = SYSTEM_UI_FLAG_VISIBLE,
1979                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
1980    })
1981    int mSystemUiVisibility;
1982
1983    /**
1984     * Count of how many windows this view has been attached to.
1985     */
1986    int mWindowAttachCount;
1987
1988    /**
1989     * The layout parameters associated with this view and used by the parent
1990     * {@link android.view.ViewGroup} to determine how this view should be
1991     * laid out.
1992     * {@hide}
1993     */
1994    protected ViewGroup.LayoutParams mLayoutParams;
1995
1996    /**
1997     * The view flags hold various views states.
1998     * {@hide}
1999     */
2000    @ViewDebug.ExportedProperty
2001    int mViewFlags;
2002
2003    /**
2004     * The transform matrix for the View. This transform is calculated internally
2005     * based on the rotation, scaleX, and scaleY properties. The identity matrix
2006     * is used by default. Do *not* use this variable directly; instead call
2007     * getMatrix(), which will automatically recalculate the matrix if necessary
2008     * to get the correct matrix based on the latest rotation and scale properties.
2009     */
2010    private final Matrix mMatrix = new Matrix();
2011
2012    /**
2013     * The transform matrix for the View. This transform is calculated internally
2014     * based on the rotation, scaleX, and scaleY properties. The identity matrix
2015     * is used by default. Do *not* use this variable directly; instead call
2016     * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2017     * to get the correct matrix based on the latest rotation and scale properties.
2018     */
2019    private Matrix mInverseMatrix;
2020
2021    /**
2022     * An internal variable that tracks whether we need to recalculate the
2023     * transform matrix, based on whether the rotation or scaleX/Y properties
2024     * have changed since the matrix was last calculated.
2025     */
2026    boolean mMatrixDirty = false;
2027
2028    /**
2029     * An internal variable that tracks whether we need to recalculate the
2030     * transform matrix, based on whether the rotation or scaleX/Y properties
2031     * have changed since the matrix was last calculated.
2032     */
2033    private boolean mInverseMatrixDirty = true;
2034
2035    /**
2036     * A variable that tracks whether we need to recalculate the
2037     * transform matrix, based on whether the rotation or scaleX/Y properties
2038     * have changed since the matrix was last calculated. This variable
2039     * is only valid after a call to updateMatrix() or to a function that
2040     * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2041     */
2042    private boolean mMatrixIsIdentity = true;
2043
2044    /**
2045     * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2046     */
2047    private Camera mCamera = null;
2048
2049    /**
2050     * This matrix is used when computing the matrix for 3D rotations.
2051     */
2052    private Matrix matrix3D = null;
2053
2054    /**
2055     * These prev values are used to recalculate a centered pivot point when necessary. The
2056     * pivot point is only used in matrix operations (when rotation, scale, or translation are
2057     * set), so thes values are only used then as well.
2058     */
2059    private int mPrevWidth = -1;
2060    private int mPrevHeight = -1;
2061
2062    private boolean mLastIsOpaque;
2063
2064    /**
2065     * Convenience value to check for float values that are close enough to zero to be considered
2066     * zero.
2067     */
2068    private static final float NONZERO_EPSILON = .001f;
2069
2070    /**
2071     * The degrees rotation around the vertical axis through the pivot point.
2072     */
2073    @ViewDebug.ExportedProperty
2074    float mRotationY = 0f;
2075
2076    /**
2077     * The degrees rotation around the horizontal axis through the pivot point.
2078     */
2079    @ViewDebug.ExportedProperty
2080    float mRotationX = 0f;
2081
2082    /**
2083     * The degrees rotation around the pivot point.
2084     */
2085    @ViewDebug.ExportedProperty
2086    float mRotation = 0f;
2087
2088    /**
2089     * The amount of translation of the object away from its left property (post-layout).
2090     */
2091    @ViewDebug.ExportedProperty
2092    float mTranslationX = 0f;
2093
2094    /**
2095     * The amount of translation of the object away from its top property (post-layout).
2096     */
2097    @ViewDebug.ExportedProperty
2098    float mTranslationY = 0f;
2099
2100    /**
2101     * The amount of scale in the x direction around the pivot point. A
2102     * value of 1 means no scaling is applied.
2103     */
2104    @ViewDebug.ExportedProperty
2105    float mScaleX = 1f;
2106
2107    /**
2108     * The amount of scale in the y direction around the pivot point. A
2109     * value of 1 means no scaling is applied.
2110     */
2111    @ViewDebug.ExportedProperty
2112    float mScaleY = 1f;
2113
2114    /**
2115     * The amount of scale in the x direction around the pivot point. A
2116     * value of 1 means no scaling is applied.
2117     */
2118    @ViewDebug.ExportedProperty
2119    float mPivotX = 0f;
2120
2121    /**
2122     * The amount of scale in the y direction around the pivot point. A
2123     * value of 1 means no scaling is applied.
2124     */
2125    @ViewDebug.ExportedProperty
2126    float mPivotY = 0f;
2127
2128    /**
2129     * The opacity of the View. This is a value from 0 to 1, where 0 means
2130     * completely transparent and 1 means completely opaque.
2131     */
2132    @ViewDebug.ExportedProperty
2133    float mAlpha = 1f;
2134
2135    /**
2136     * The distance in pixels from the left edge of this view's parent
2137     * to the left edge of this view.
2138     * {@hide}
2139     */
2140    @ViewDebug.ExportedProperty(category = "layout")
2141    protected int mLeft;
2142    /**
2143     * The distance in pixels from the left edge of this view's parent
2144     * to the right edge of this view.
2145     * {@hide}
2146     */
2147    @ViewDebug.ExportedProperty(category = "layout")
2148    protected int mRight;
2149    /**
2150     * The distance in pixels from the top edge of this view's parent
2151     * to the top edge of this view.
2152     * {@hide}
2153     */
2154    @ViewDebug.ExportedProperty(category = "layout")
2155    protected int mTop;
2156    /**
2157     * The distance in pixels from the top edge of this view's parent
2158     * to the bottom edge of this view.
2159     * {@hide}
2160     */
2161    @ViewDebug.ExportedProperty(category = "layout")
2162    protected int mBottom;
2163
2164    /**
2165     * The offset, in pixels, by which the content of this view is scrolled
2166     * horizontally.
2167     * {@hide}
2168     */
2169    @ViewDebug.ExportedProperty(category = "scrolling")
2170    protected int mScrollX;
2171    /**
2172     * The offset, in pixels, by which the content of this view is scrolled
2173     * vertically.
2174     * {@hide}
2175     */
2176    @ViewDebug.ExportedProperty(category = "scrolling")
2177    protected int mScrollY;
2178
2179    /**
2180     * The left padding in pixels, that is the distance in pixels between the
2181     * left edge of this view and the left edge of its content.
2182     * {@hide}
2183     */
2184    @ViewDebug.ExportedProperty(category = "padding")
2185    protected int mPaddingLeft;
2186    /**
2187     * The right padding in pixels, that is the distance in pixels between the
2188     * right edge of this view and the right edge of its content.
2189     * {@hide}
2190     */
2191    @ViewDebug.ExportedProperty(category = "padding")
2192    protected int mPaddingRight;
2193    /**
2194     * The top padding in pixels, that is the distance in pixels between the
2195     * top edge of this view and the top edge of its content.
2196     * {@hide}
2197     */
2198    @ViewDebug.ExportedProperty(category = "padding")
2199    protected int mPaddingTop;
2200    /**
2201     * The bottom padding in pixels, that is the distance in pixels between the
2202     * bottom edge of this view and the bottom edge of its content.
2203     * {@hide}
2204     */
2205    @ViewDebug.ExportedProperty(category = "padding")
2206    protected int mPaddingBottom;
2207
2208    /**
2209     * Briefly describes the view and is primarily used for accessibility support.
2210     */
2211    private CharSequence mContentDescription;
2212
2213    /**
2214     * Cache the paddingRight set by the user to append to the scrollbar's size.
2215     *
2216     * @hide
2217     */
2218    @ViewDebug.ExportedProperty(category = "padding")
2219    protected int mUserPaddingRight;
2220
2221    /**
2222     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2223     *
2224     * @hide
2225     */
2226    @ViewDebug.ExportedProperty(category = "padding")
2227    protected int mUserPaddingBottom;
2228
2229    /**
2230     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2231     *
2232     * @hide
2233     */
2234    @ViewDebug.ExportedProperty(category = "padding")
2235    protected int mUserPaddingLeft;
2236
2237    /**
2238     * Cache if the user padding is relative.
2239     *
2240     */
2241    @ViewDebug.ExportedProperty(category = "padding")
2242    boolean mUserPaddingRelative;
2243
2244    /**
2245     * Cache the paddingStart set by the user to append to the scrollbar's size.
2246     *
2247     */
2248    @ViewDebug.ExportedProperty(category = "padding")
2249    int mUserPaddingStart;
2250
2251    /**
2252     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2253     *
2254     */
2255    @ViewDebug.ExportedProperty(category = "padding")
2256    int mUserPaddingEnd;
2257
2258    /**
2259     * @hide
2260     */
2261    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2262    /**
2263     * @hide
2264     */
2265    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2266
2267    private Resources mResources = null;
2268
2269    private Drawable mBGDrawable;
2270
2271    private int mBackgroundResource;
2272    private boolean mBackgroundSizeChanged;
2273
2274    /**
2275     * Listener used to dispatch focus change events.
2276     * This field should be made private, so it is hidden from the SDK.
2277     * {@hide}
2278     */
2279    protected OnFocusChangeListener mOnFocusChangeListener;
2280
2281    /**
2282     * Listeners for layout change events.
2283     */
2284    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2285
2286    /**
2287     * Listeners for attach events.
2288     */
2289    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2290
2291    /**
2292     * Listener used to dispatch click events.
2293     * This field should be made private, so it is hidden from the SDK.
2294     * {@hide}
2295     */
2296    protected OnClickListener mOnClickListener;
2297
2298    /**
2299     * Listener used to dispatch long click events.
2300     * This field should be made private, so it is hidden from the SDK.
2301     * {@hide}
2302     */
2303    protected OnLongClickListener mOnLongClickListener;
2304
2305    /**
2306     * Listener used to build the context menu.
2307     * This field should be made private, so it is hidden from the SDK.
2308     * {@hide}
2309     */
2310    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2311
2312    private OnKeyListener mOnKeyListener;
2313
2314    private OnTouchListener mOnTouchListener;
2315
2316    private OnHoverListener mOnHoverListener;
2317
2318    private OnGenericMotionListener mOnGenericMotionListener;
2319
2320    private OnDragListener mOnDragListener;
2321
2322    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2323
2324    /**
2325     * The application environment this view lives in.
2326     * This field should be made private, so it is hidden from the SDK.
2327     * {@hide}
2328     */
2329    protected Context mContext;
2330
2331    private ScrollabilityCache mScrollCache;
2332
2333    private int[] mDrawableState = null;
2334
2335    /**
2336     * Set to true when drawing cache is enabled and cannot be created.
2337     *
2338     * @hide
2339     */
2340    public boolean mCachingFailed;
2341
2342    private Bitmap mDrawingCache;
2343    private Bitmap mUnscaledDrawingCache;
2344    private HardwareLayer mHardwareLayer;
2345    DisplayList mDisplayList;
2346
2347    /**
2348     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2349     * the user may specify which view to go to next.
2350     */
2351    private int mNextFocusLeftId = View.NO_ID;
2352
2353    /**
2354     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2355     * the user may specify which view to go to next.
2356     */
2357    private int mNextFocusRightId = View.NO_ID;
2358
2359    /**
2360     * When this view has focus and the next focus is {@link #FOCUS_UP},
2361     * the user may specify which view to go to next.
2362     */
2363    private int mNextFocusUpId = View.NO_ID;
2364
2365    /**
2366     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2367     * the user may specify which view to go to next.
2368     */
2369    private int mNextFocusDownId = View.NO_ID;
2370
2371    /**
2372     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2373     * the user may specify which view to go to next.
2374     */
2375    int mNextFocusForwardId = View.NO_ID;
2376
2377    private CheckForLongPress mPendingCheckForLongPress;
2378    private CheckForTap mPendingCheckForTap = null;
2379    private PerformClick mPerformClick;
2380    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2381
2382    private UnsetPressedState mUnsetPressedState;
2383
2384    /**
2385     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2386     * up event while a long press is invoked as soon as the long press duration is reached, so
2387     * a long press could be performed before the tap is checked, in which case the tap's action
2388     * should not be invoked.
2389     */
2390    private boolean mHasPerformedLongPress;
2391
2392    /**
2393     * The minimum height of the view. We'll try our best to have the height
2394     * of this view to at least this amount.
2395     */
2396    @ViewDebug.ExportedProperty(category = "measurement")
2397    private int mMinHeight;
2398
2399    /**
2400     * The minimum width of the view. We'll try our best to have the width
2401     * of this view to at least this amount.
2402     */
2403    @ViewDebug.ExportedProperty(category = "measurement")
2404    private int mMinWidth;
2405
2406    /**
2407     * The delegate to handle touch events that are physically in this view
2408     * but should be handled by another view.
2409     */
2410    private TouchDelegate mTouchDelegate = null;
2411
2412    /**
2413     * Solid color to use as a background when creating the drawing cache. Enables
2414     * the cache to use 16 bit bitmaps instead of 32 bit.
2415     */
2416    private int mDrawingCacheBackgroundColor = 0;
2417
2418    /**
2419     * Special tree observer used when mAttachInfo is null.
2420     */
2421    private ViewTreeObserver mFloatingTreeObserver;
2422
2423    /**
2424     * Cache the touch slop from the context that created the view.
2425     */
2426    private int mTouchSlop;
2427
2428    /**
2429     * Object that handles automatic animation of view properties.
2430     */
2431    private ViewPropertyAnimator mAnimator = null;
2432
2433    /**
2434     * Flag indicating that a drag can cross window boundaries.  When
2435     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2436     * with this flag set, all visible applications will be able to participate
2437     * in the drag operation and receive the dragged content.
2438     *
2439     * @hide
2440     */
2441    public static final int DRAG_FLAG_GLOBAL = 1;
2442
2443    /**
2444     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2445     */
2446    private float mVerticalScrollFactor;
2447
2448    /**
2449     * Position of the vertical scroll bar.
2450     */
2451    private int mVerticalScrollbarPosition;
2452
2453    /**
2454     * Position the scroll bar at the default position as determined by the system.
2455     */
2456    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2457
2458    /**
2459     * Position the scroll bar along the left edge.
2460     */
2461    public static final int SCROLLBAR_POSITION_LEFT = 1;
2462
2463    /**
2464     * Position the scroll bar along the right edge.
2465     */
2466    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2467
2468    /**
2469     * Indicates that the view does not have a layer.
2470     *
2471     * @see #getLayerType()
2472     * @see #setLayerType(int, android.graphics.Paint)
2473     * @see #LAYER_TYPE_SOFTWARE
2474     * @see #LAYER_TYPE_HARDWARE
2475     */
2476    public static final int LAYER_TYPE_NONE = 0;
2477
2478    /**
2479     * <p>Indicates that the view has a software layer. A software layer is backed
2480     * by a bitmap and causes the view to be rendered using Android's software
2481     * rendering pipeline, even if hardware acceleration is enabled.</p>
2482     *
2483     * <p>Software layers have various usages:</p>
2484     * <p>When the application is not using hardware acceleration, a software layer
2485     * is useful to apply a specific color filter and/or blending mode and/or
2486     * translucency to a view and all its children.</p>
2487     * <p>When the application is using hardware acceleration, a software layer
2488     * is useful to render drawing primitives not supported by the hardware
2489     * accelerated pipeline. It can also be used to cache a complex view tree
2490     * into a texture and reduce the complexity of drawing operations. For instance,
2491     * when animating a complex view tree with a translation, a software layer can
2492     * be used to render the view tree only once.</p>
2493     * <p>Software layers should be avoided when the affected view tree updates
2494     * often. Every update will require to re-render the software layer, which can
2495     * potentially be slow (particularly when hardware acceleration is turned on
2496     * since the layer will have to be uploaded into a hardware texture after every
2497     * update.)</p>
2498     *
2499     * @see #getLayerType()
2500     * @see #setLayerType(int, android.graphics.Paint)
2501     * @see #LAYER_TYPE_NONE
2502     * @see #LAYER_TYPE_HARDWARE
2503     */
2504    public static final int LAYER_TYPE_SOFTWARE = 1;
2505
2506    /**
2507     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2508     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2509     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2510     * rendering pipeline, but only if hardware acceleration is turned on for the
2511     * view hierarchy. When hardware acceleration is turned off, hardware layers
2512     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2513     *
2514     * <p>A hardware layer is useful to apply a specific color filter and/or
2515     * blending mode and/or translucency to a view and all its children.</p>
2516     * <p>A hardware layer can be used to cache a complex view tree into a
2517     * texture and reduce the complexity of drawing operations. For instance,
2518     * when animating a complex view tree with a translation, a hardware layer can
2519     * be used to render the view tree only once.</p>
2520     * <p>A hardware layer can also be used to increase the rendering quality when
2521     * rotation transformations are applied on a view. It can also be used to
2522     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2523     *
2524     * @see #getLayerType()
2525     * @see #setLayerType(int, android.graphics.Paint)
2526     * @see #LAYER_TYPE_NONE
2527     * @see #LAYER_TYPE_SOFTWARE
2528     */
2529    public static final int LAYER_TYPE_HARDWARE = 2;
2530
2531    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2532            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2533            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2534            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2535    })
2536    int mLayerType = LAYER_TYPE_NONE;
2537    Paint mLayerPaint;
2538    Rect mLocalDirtyRect;
2539
2540    /**
2541     * Set to true when the view is sending hover accessibility events because it
2542     * is the innermost hovered view.
2543     */
2544    private boolean mSendingHoverAccessibilityEvents;
2545
2546    /**
2547     * Text direction is inherited thru {@link ViewGroup}
2548     * @hide
2549     */
2550    public static final int TEXT_DIRECTION_INHERIT = 0;
2551
2552    /**
2553     * Text direction is using "first strong algorithm". The first strong directional character
2554     * determines the paragraph direction. If there is no strong directional character, the
2555     * paragraph direction is the view's resolved ayout direction.
2556     *
2557     * @hide
2558     */
2559    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2560
2561    /**
2562     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2563     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2564     * If there are neither, the paragraph direction is the view's resolved layout direction.
2565     *
2566     * @hide
2567     */
2568    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2569
2570    /**
2571     * Text direction is the same as the one held by a 60% majority of the characters. If there is
2572     * no majority then the paragraph direction is the resolved layout direction of the View.
2573     *
2574     * @hide
2575     */
2576    public static final int TEXT_DIRECTION_CHAR_COUNT = 3;
2577
2578    /**
2579     * Text direction is forced to LTR.
2580     *
2581     * @hide
2582     */
2583    public static final int TEXT_DIRECTION_LTR = 4;
2584
2585    /**
2586     * Text direction is forced to RTL.
2587     *
2588     * @hide
2589     */
2590    public static final int TEXT_DIRECTION_RTL = 5;
2591
2592    /**
2593     * Default text direction is inherited
2594     */
2595    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2596
2597    /**
2598     * Default threshold for "char count" heuristic.
2599     */
2600    protected static float DEFAULT_TEXT_DIRECTION_CHAR_COUNT_THRESHOLD = 0.6f;
2601
2602    /**
2603     * The text direction that has been defined by {@link #setTextDirection(int)}.
2604     *
2605     * {@hide}
2606     */
2607    @ViewDebug.ExportedProperty(category = "text", mapping = {
2608            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2609            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2610            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2611            @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"),
2612            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2613            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2614    })
2615    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2616
2617    /**
2618     * The resolved text direction.  This needs resolution if the value is
2619     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if that is
2620     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2621     * chain of the view.
2622     *
2623     * {@hide}
2624     */
2625    @ViewDebug.ExportedProperty(category = "text", mapping = {
2626            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2627            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2628            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2629            @ViewDebug.IntToString(from = TEXT_DIRECTION_CHAR_COUNT, to = "CHAR_COUNT"),
2630            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2631            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2632    })
2633    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2634
2635    /**
2636     * Consistency verifier for debugging purposes.
2637     * @hide
2638     */
2639    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2640            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2641                    new InputEventConsistencyVerifier(this, 0) : null;
2642
2643    /**
2644     * Simple constructor to use when creating a view from code.
2645     *
2646     * @param context The Context the view is running in, through which it can
2647     *        access the current theme, resources, etc.
2648     */
2649    public View(Context context) {
2650        mContext = context;
2651        mResources = context != null ? context.getResources() : null;
2652        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2653        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2654        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2655        mUserPaddingStart = -1;
2656        mUserPaddingEnd = -1;
2657        mUserPaddingRelative = false;
2658    }
2659
2660    /**
2661     * Constructor that is called when inflating a view from XML. This is called
2662     * when a view is being constructed from an XML file, supplying attributes
2663     * that were specified in the XML file. This version uses a default style of
2664     * 0, so the only attribute values applied are those in the Context's Theme
2665     * and the given AttributeSet.
2666     *
2667     * <p>
2668     * The method onFinishInflate() will be called after all children have been
2669     * added.
2670     *
2671     * @param context The Context the view is running in, through which it can
2672     *        access the current theme, resources, etc.
2673     * @param attrs The attributes of the XML tag that is inflating the view.
2674     * @see #View(Context, AttributeSet, int)
2675     */
2676    public View(Context context, AttributeSet attrs) {
2677        this(context, attrs, 0);
2678    }
2679
2680    /**
2681     * Perform inflation from XML and apply a class-specific base style. This
2682     * constructor of View allows subclasses to use their own base style when
2683     * they are inflating. For example, a Button class's constructor would call
2684     * this version of the super class constructor and supply
2685     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2686     * the theme's button style to modify all of the base view attributes (in
2687     * particular its background) as well as the Button class's attributes.
2688     *
2689     * @param context The Context the view is running in, through which it can
2690     *        access the current theme, resources, etc.
2691     * @param attrs The attributes of the XML tag that is inflating the view.
2692     * @param defStyle The default style to apply to this view. If 0, no style
2693     *        will be applied (beyond what is included in the theme). This may
2694     *        either be an attribute resource, whose value will be retrieved
2695     *        from the current theme, or an explicit style resource.
2696     * @see #View(Context, AttributeSet)
2697     */
2698    public View(Context context, AttributeSet attrs, int defStyle) {
2699        this(context);
2700
2701        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2702                defStyle, 0);
2703
2704        Drawable background = null;
2705
2706        int leftPadding = -1;
2707        int topPadding = -1;
2708        int rightPadding = -1;
2709        int bottomPadding = -1;
2710        int startPadding = -1;
2711        int endPadding = -1;
2712
2713        int padding = -1;
2714
2715        int viewFlagValues = 0;
2716        int viewFlagMasks = 0;
2717
2718        boolean setScrollContainer = false;
2719
2720        int x = 0;
2721        int y = 0;
2722
2723        float tx = 0;
2724        float ty = 0;
2725        float rotation = 0;
2726        float rotationX = 0;
2727        float rotationY = 0;
2728        float sx = 1f;
2729        float sy = 1f;
2730        boolean transformSet = false;
2731
2732        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2733
2734        int overScrollMode = mOverScrollMode;
2735        final int N = a.getIndexCount();
2736        for (int i = 0; i < N; i++) {
2737            int attr = a.getIndex(i);
2738            switch (attr) {
2739                case com.android.internal.R.styleable.View_background:
2740                    background = a.getDrawable(attr);
2741                    break;
2742                case com.android.internal.R.styleable.View_padding:
2743                    padding = a.getDimensionPixelSize(attr, -1);
2744                    break;
2745                 case com.android.internal.R.styleable.View_paddingLeft:
2746                    leftPadding = a.getDimensionPixelSize(attr, -1);
2747                    break;
2748                case com.android.internal.R.styleable.View_paddingTop:
2749                    topPadding = a.getDimensionPixelSize(attr, -1);
2750                    break;
2751                case com.android.internal.R.styleable.View_paddingRight:
2752                    rightPadding = a.getDimensionPixelSize(attr, -1);
2753                    break;
2754                case com.android.internal.R.styleable.View_paddingBottom:
2755                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2756                    break;
2757                case com.android.internal.R.styleable.View_paddingStart:
2758                    startPadding = a.getDimensionPixelSize(attr, -1);
2759                    break;
2760                case com.android.internal.R.styleable.View_paddingEnd:
2761                    endPadding = a.getDimensionPixelSize(attr, -1);
2762                    break;
2763                case com.android.internal.R.styleable.View_scrollX:
2764                    x = a.getDimensionPixelOffset(attr, 0);
2765                    break;
2766                case com.android.internal.R.styleable.View_scrollY:
2767                    y = a.getDimensionPixelOffset(attr, 0);
2768                    break;
2769                case com.android.internal.R.styleable.View_alpha:
2770                    setAlpha(a.getFloat(attr, 1f));
2771                    break;
2772                case com.android.internal.R.styleable.View_transformPivotX:
2773                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2774                    break;
2775                case com.android.internal.R.styleable.View_transformPivotY:
2776                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2777                    break;
2778                case com.android.internal.R.styleable.View_translationX:
2779                    tx = a.getDimensionPixelOffset(attr, 0);
2780                    transformSet = true;
2781                    break;
2782                case com.android.internal.R.styleable.View_translationY:
2783                    ty = a.getDimensionPixelOffset(attr, 0);
2784                    transformSet = true;
2785                    break;
2786                case com.android.internal.R.styleable.View_rotation:
2787                    rotation = a.getFloat(attr, 0);
2788                    transformSet = true;
2789                    break;
2790                case com.android.internal.R.styleable.View_rotationX:
2791                    rotationX = a.getFloat(attr, 0);
2792                    transformSet = true;
2793                    break;
2794                case com.android.internal.R.styleable.View_rotationY:
2795                    rotationY = a.getFloat(attr, 0);
2796                    transformSet = true;
2797                    break;
2798                case com.android.internal.R.styleable.View_scaleX:
2799                    sx = a.getFloat(attr, 1f);
2800                    transformSet = true;
2801                    break;
2802                case com.android.internal.R.styleable.View_scaleY:
2803                    sy = a.getFloat(attr, 1f);
2804                    transformSet = true;
2805                    break;
2806                case com.android.internal.R.styleable.View_id:
2807                    mID = a.getResourceId(attr, NO_ID);
2808                    break;
2809                case com.android.internal.R.styleable.View_tag:
2810                    mTag = a.getText(attr);
2811                    break;
2812                case com.android.internal.R.styleable.View_fitsSystemWindows:
2813                    if (a.getBoolean(attr, false)) {
2814                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2815                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2816                    }
2817                    break;
2818                case com.android.internal.R.styleable.View_focusable:
2819                    if (a.getBoolean(attr, false)) {
2820                        viewFlagValues |= FOCUSABLE;
2821                        viewFlagMasks |= FOCUSABLE_MASK;
2822                    }
2823                    break;
2824                case com.android.internal.R.styleable.View_focusableInTouchMode:
2825                    if (a.getBoolean(attr, false)) {
2826                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2827                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2828                    }
2829                    break;
2830                case com.android.internal.R.styleable.View_clickable:
2831                    if (a.getBoolean(attr, false)) {
2832                        viewFlagValues |= CLICKABLE;
2833                        viewFlagMasks |= CLICKABLE;
2834                    }
2835                    break;
2836                case com.android.internal.R.styleable.View_longClickable:
2837                    if (a.getBoolean(attr, false)) {
2838                        viewFlagValues |= LONG_CLICKABLE;
2839                        viewFlagMasks |= LONG_CLICKABLE;
2840                    }
2841                    break;
2842                case com.android.internal.R.styleable.View_saveEnabled:
2843                    if (!a.getBoolean(attr, true)) {
2844                        viewFlagValues |= SAVE_DISABLED;
2845                        viewFlagMasks |= SAVE_DISABLED_MASK;
2846                    }
2847                    break;
2848                case com.android.internal.R.styleable.View_duplicateParentState:
2849                    if (a.getBoolean(attr, false)) {
2850                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2851                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2852                    }
2853                    break;
2854                case com.android.internal.R.styleable.View_visibility:
2855                    final int visibility = a.getInt(attr, 0);
2856                    if (visibility != 0) {
2857                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2858                        viewFlagMasks |= VISIBILITY_MASK;
2859                    }
2860                    break;
2861                case com.android.internal.R.styleable.View_layoutDirection:
2862                    // Clear any HORIZONTAL_DIRECTION flag already set
2863                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2864                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2865                    final int layoutDirection = a.getInt(attr, -1);
2866                    if (layoutDirection != -1) {
2867                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2868                    } else {
2869                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2870                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2871                    }
2872                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2873                    break;
2874                case com.android.internal.R.styleable.View_drawingCacheQuality:
2875                    final int cacheQuality = a.getInt(attr, 0);
2876                    if (cacheQuality != 0) {
2877                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2878                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2879                    }
2880                    break;
2881                case com.android.internal.R.styleable.View_contentDescription:
2882                    mContentDescription = a.getString(attr);
2883                    break;
2884                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2885                    if (!a.getBoolean(attr, true)) {
2886                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2887                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2888                    }
2889                    break;
2890                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2891                    if (!a.getBoolean(attr, true)) {
2892                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2893                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2894                    }
2895                    break;
2896                case R.styleable.View_scrollbars:
2897                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2898                    if (scrollbars != SCROLLBARS_NONE) {
2899                        viewFlagValues |= scrollbars;
2900                        viewFlagMasks |= SCROLLBARS_MASK;
2901                        initializeScrollbars(a);
2902                    }
2903                    break;
2904                case R.styleable.View_fadingEdge:
2905                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2906                    if (fadingEdge != FADING_EDGE_NONE) {
2907                        viewFlagValues |= fadingEdge;
2908                        viewFlagMasks |= FADING_EDGE_MASK;
2909                        initializeFadingEdge(a);
2910                    }
2911                    break;
2912                case R.styleable.View_scrollbarStyle:
2913                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2914                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2915                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2916                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2917                    }
2918                    break;
2919                case R.styleable.View_isScrollContainer:
2920                    setScrollContainer = true;
2921                    if (a.getBoolean(attr, false)) {
2922                        setScrollContainer(true);
2923                    }
2924                    break;
2925                case com.android.internal.R.styleable.View_keepScreenOn:
2926                    if (a.getBoolean(attr, false)) {
2927                        viewFlagValues |= KEEP_SCREEN_ON;
2928                        viewFlagMasks |= KEEP_SCREEN_ON;
2929                    }
2930                    break;
2931                case R.styleable.View_filterTouchesWhenObscured:
2932                    if (a.getBoolean(attr, false)) {
2933                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2934                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2935                    }
2936                    break;
2937                case R.styleable.View_nextFocusLeft:
2938                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2939                    break;
2940                case R.styleable.View_nextFocusRight:
2941                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2942                    break;
2943                case R.styleable.View_nextFocusUp:
2944                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2945                    break;
2946                case R.styleable.View_nextFocusDown:
2947                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2948                    break;
2949                case R.styleable.View_nextFocusForward:
2950                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2951                    break;
2952                case R.styleable.View_minWidth:
2953                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2954                    break;
2955                case R.styleable.View_minHeight:
2956                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2957                    break;
2958                case R.styleable.View_onClick:
2959                    if (context.isRestricted()) {
2960                        throw new IllegalStateException("The android:onClick attribute cannot "
2961                                + "be used within a restricted context");
2962                    }
2963
2964                    final String handlerName = a.getString(attr);
2965                    if (handlerName != null) {
2966                        setOnClickListener(new OnClickListener() {
2967                            private Method mHandler;
2968
2969                            public void onClick(View v) {
2970                                if (mHandler == null) {
2971                                    try {
2972                                        mHandler = getContext().getClass().getMethod(handlerName,
2973                                                View.class);
2974                                    } catch (NoSuchMethodException e) {
2975                                        int id = getId();
2976                                        String idText = id == NO_ID ? "" : " with id '"
2977                                                + getContext().getResources().getResourceEntryName(
2978                                                    id) + "'";
2979                                        throw new IllegalStateException("Could not find a method " +
2980                                                handlerName + "(View) in the activity "
2981                                                + getContext().getClass() + " for onClick handler"
2982                                                + " on view " + View.this.getClass() + idText, e);
2983                                    }
2984                                }
2985
2986                                try {
2987                                    mHandler.invoke(getContext(), View.this);
2988                                } catch (IllegalAccessException e) {
2989                                    throw new IllegalStateException("Could not execute non "
2990                                            + "public method of the activity", e);
2991                                } catch (InvocationTargetException e) {
2992                                    throw new IllegalStateException("Could not execute "
2993                                            + "method of the activity", e);
2994                                }
2995                            }
2996                        });
2997                    }
2998                    break;
2999                case R.styleable.View_overScrollMode:
3000                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3001                    break;
3002                case R.styleable.View_verticalScrollbarPosition:
3003                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3004                    break;
3005                case R.styleable.View_layerType:
3006                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3007                    break;
3008                case R.styleable.View_textDirection:
3009                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3010                    break;
3011            }
3012        }
3013
3014        setOverScrollMode(overScrollMode);
3015
3016        if (background != null) {
3017            setBackgroundDrawable(background);
3018        }
3019
3020        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3021
3022        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3023        // layout direction). Those cached values will be used later during padding resolution.
3024        mUserPaddingStart = startPadding;
3025        mUserPaddingEnd = endPadding;
3026
3027        if (padding >= 0) {
3028            leftPadding = padding;
3029            topPadding = padding;
3030            rightPadding = padding;
3031            bottomPadding = padding;
3032        }
3033
3034        // If the user specified the padding (either with android:padding or
3035        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3036        // use the default padding or the padding from the background drawable
3037        // (stored at this point in mPadding*)
3038        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3039                topPadding >= 0 ? topPadding : mPaddingTop,
3040                rightPadding >= 0 ? rightPadding : mPaddingRight,
3041                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3042
3043        if (viewFlagMasks != 0) {
3044            setFlags(viewFlagValues, viewFlagMasks);
3045        }
3046
3047        // Needs to be called after mViewFlags is set
3048        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3049            recomputePadding();
3050        }
3051
3052        if (x != 0 || y != 0) {
3053            scrollTo(x, y);
3054        }
3055
3056        if (transformSet) {
3057            setTranslationX(tx);
3058            setTranslationY(ty);
3059            setRotation(rotation);
3060            setRotationX(rotationX);
3061            setRotationY(rotationY);
3062            setScaleX(sx);
3063            setScaleY(sy);
3064        }
3065
3066        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3067            setScrollContainer(true);
3068        }
3069
3070        computeOpaqueFlags();
3071
3072        a.recycle();
3073    }
3074
3075    /**
3076     * Non-public constructor for use in testing
3077     */
3078    View() {
3079    }
3080
3081    /**
3082     * <p>
3083     * Initializes the fading edges from a given set of styled attributes. This
3084     * method should be called by subclasses that need fading edges and when an
3085     * instance of these subclasses is created programmatically rather than
3086     * being inflated from XML. This method is automatically called when the XML
3087     * is inflated.
3088     * </p>
3089     *
3090     * @param a the styled attributes set to initialize the fading edges from
3091     */
3092    protected void initializeFadingEdge(TypedArray a) {
3093        initScrollCache();
3094
3095        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3096                R.styleable.View_fadingEdgeLength,
3097                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3098    }
3099
3100    /**
3101     * Returns the size of the vertical faded edges used to indicate that more
3102     * content in this view is visible.
3103     *
3104     * @return The size in pixels of the vertical faded edge or 0 if vertical
3105     *         faded edges are not enabled for this view.
3106     * @attr ref android.R.styleable#View_fadingEdgeLength
3107     */
3108    public int getVerticalFadingEdgeLength() {
3109        if (isVerticalFadingEdgeEnabled()) {
3110            ScrollabilityCache cache = mScrollCache;
3111            if (cache != null) {
3112                return cache.fadingEdgeLength;
3113            }
3114        }
3115        return 0;
3116    }
3117
3118    /**
3119     * Set the size of the faded edge used to indicate that more content in this
3120     * view is available.  Will not change whether the fading edge is enabled; use
3121     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3122     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3123     * for the vertical or horizontal fading edges.
3124     *
3125     * @param length The size in pixels of the faded edge used to indicate that more
3126     *        content in this view is visible.
3127     */
3128    public void setFadingEdgeLength(int length) {
3129        initScrollCache();
3130        mScrollCache.fadingEdgeLength = length;
3131    }
3132
3133    /**
3134     * Returns the size of the horizontal faded edges used to indicate that more
3135     * content in this view is visible.
3136     *
3137     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3138     *         faded edges are not enabled for this view.
3139     * @attr ref android.R.styleable#View_fadingEdgeLength
3140     */
3141    public int getHorizontalFadingEdgeLength() {
3142        if (isHorizontalFadingEdgeEnabled()) {
3143            ScrollabilityCache cache = mScrollCache;
3144            if (cache != null) {
3145                return cache.fadingEdgeLength;
3146            }
3147        }
3148        return 0;
3149    }
3150
3151    /**
3152     * Returns the width of the vertical scrollbar.
3153     *
3154     * @return The width in pixels of the vertical scrollbar or 0 if there
3155     *         is no vertical scrollbar.
3156     */
3157    public int getVerticalScrollbarWidth() {
3158        ScrollabilityCache cache = mScrollCache;
3159        if (cache != null) {
3160            ScrollBarDrawable scrollBar = cache.scrollBar;
3161            if (scrollBar != null) {
3162                int size = scrollBar.getSize(true);
3163                if (size <= 0) {
3164                    size = cache.scrollBarSize;
3165                }
3166                return size;
3167            }
3168            return 0;
3169        }
3170        return 0;
3171    }
3172
3173    /**
3174     * Returns the height of the horizontal scrollbar.
3175     *
3176     * @return The height in pixels of the horizontal scrollbar or 0 if
3177     *         there is no horizontal scrollbar.
3178     */
3179    protected int getHorizontalScrollbarHeight() {
3180        ScrollabilityCache cache = mScrollCache;
3181        if (cache != null) {
3182            ScrollBarDrawable scrollBar = cache.scrollBar;
3183            if (scrollBar != null) {
3184                int size = scrollBar.getSize(false);
3185                if (size <= 0) {
3186                    size = cache.scrollBarSize;
3187                }
3188                return size;
3189            }
3190            return 0;
3191        }
3192        return 0;
3193    }
3194
3195    /**
3196     * <p>
3197     * Initializes the scrollbars from a given set of styled attributes. This
3198     * method should be called by subclasses that need scrollbars and when an
3199     * instance of these subclasses is created programmatically rather than
3200     * being inflated from XML. This method is automatically called when the XML
3201     * is inflated.
3202     * </p>
3203     *
3204     * @param a the styled attributes set to initialize the scrollbars from
3205     */
3206    protected void initializeScrollbars(TypedArray a) {
3207        initScrollCache();
3208
3209        final ScrollabilityCache scrollabilityCache = mScrollCache;
3210
3211        if (scrollabilityCache.scrollBar == null) {
3212            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3213        }
3214
3215        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3216
3217        if (!fadeScrollbars) {
3218            scrollabilityCache.state = ScrollabilityCache.ON;
3219        }
3220        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3221
3222
3223        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3224                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3225                        .getScrollBarFadeDuration());
3226        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3227                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3228                ViewConfiguration.getScrollDefaultDelay());
3229
3230
3231        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3232                com.android.internal.R.styleable.View_scrollbarSize,
3233                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3234
3235        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3236        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3237
3238        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3239        if (thumb != null) {
3240            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3241        }
3242
3243        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3244                false);
3245        if (alwaysDraw) {
3246            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3247        }
3248
3249        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3250        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3251
3252        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3253        if (thumb != null) {
3254            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3255        }
3256
3257        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3258                false);
3259        if (alwaysDraw) {
3260            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3261        }
3262
3263        // Re-apply user/background padding so that scrollbar(s) get added
3264        resolvePadding();
3265    }
3266
3267    /**
3268     * <p>
3269     * Initalizes the scrollability cache if necessary.
3270     * </p>
3271     */
3272    private void initScrollCache() {
3273        if (mScrollCache == null) {
3274            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3275        }
3276    }
3277
3278    /**
3279     * Set the position of the vertical scroll bar. Should be one of
3280     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3281     * {@link #SCROLLBAR_POSITION_RIGHT}.
3282     *
3283     * @param position Where the vertical scroll bar should be positioned.
3284     */
3285    public void setVerticalScrollbarPosition(int position) {
3286        if (mVerticalScrollbarPosition != position) {
3287            mVerticalScrollbarPosition = position;
3288            computeOpaqueFlags();
3289            resolvePadding();
3290        }
3291    }
3292
3293    /**
3294     * @return The position where the vertical scroll bar will show, if applicable.
3295     * @see #setVerticalScrollbarPosition(int)
3296     */
3297    public int getVerticalScrollbarPosition() {
3298        return mVerticalScrollbarPosition;
3299    }
3300
3301    /**
3302     * Register a callback to be invoked when focus of this view changed.
3303     *
3304     * @param l The callback that will run.
3305     */
3306    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3307        mOnFocusChangeListener = l;
3308    }
3309
3310    /**
3311     * Add a listener that will be called when the bounds of the view change due to
3312     * layout processing.
3313     *
3314     * @param listener The listener that will be called when layout bounds change.
3315     */
3316    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3317        if (mOnLayoutChangeListeners == null) {
3318            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3319        }
3320        mOnLayoutChangeListeners.add(listener);
3321    }
3322
3323    /**
3324     * Remove a listener for layout changes.
3325     *
3326     * @param listener The listener for layout bounds change.
3327     */
3328    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3329        if (mOnLayoutChangeListeners == null) {
3330            return;
3331        }
3332        mOnLayoutChangeListeners.remove(listener);
3333    }
3334
3335    /**
3336     * Add a listener for attach state changes.
3337     *
3338     * This listener will be called whenever this view is attached or detached
3339     * from a window. Remove the listener using
3340     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3341     *
3342     * @param listener Listener to attach
3343     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3344     */
3345    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3346        if (mOnAttachStateChangeListeners == null) {
3347            mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3348        }
3349        mOnAttachStateChangeListeners.add(listener);
3350    }
3351
3352    /**
3353     * Remove a listener for attach state changes. The listener will receive no further
3354     * notification of window attach/detach events.
3355     *
3356     * @param listener Listener to remove
3357     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3358     */
3359    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3360        if (mOnAttachStateChangeListeners == null) {
3361            return;
3362        }
3363        mOnAttachStateChangeListeners.remove(listener);
3364    }
3365
3366    /**
3367     * Returns the focus-change callback registered for this view.
3368     *
3369     * @return The callback, or null if one is not registered.
3370     */
3371    public OnFocusChangeListener getOnFocusChangeListener() {
3372        return mOnFocusChangeListener;
3373    }
3374
3375    /**
3376     * Register a callback to be invoked when this view is clicked. If this view is not
3377     * clickable, it becomes clickable.
3378     *
3379     * @param l The callback that will run
3380     *
3381     * @see #setClickable(boolean)
3382     */
3383    public void setOnClickListener(OnClickListener l) {
3384        if (!isClickable()) {
3385            setClickable(true);
3386        }
3387        mOnClickListener = l;
3388    }
3389
3390    /**
3391     * Register a callback to be invoked when this view is clicked and held. If this view is not
3392     * long clickable, it becomes long clickable.
3393     *
3394     * @param l The callback that will run
3395     *
3396     * @see #setLongClickable(boolean)
3397     */
3398    public void setOnLongClickListener(OnLongClickListener l) {
3399        if (!isLongClickable()) {
3400            setLongClickable(true);
3401        }
3402        mOnLongClickListener = l;
3403    }
3404
3405    /**
3406     * Register a callback to be invoked when the context menu for this view is
3407     * being built. If this view is not long clickable, it becomes long clickable.
3408     *
3409     * @param l The callback that will run
3410     *
3411     */
3412    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3413        if (!isLongClickable()) {
3414            setLongClickable(true);
3415        }
3416        mOnCreateContextMenuListener = l;
3417    }
3418
3419    /**
3420     * Call this view's OnClickListener, if it is defined.
3421     *
3422     * @return True there was an assigned OnClickListener that was called, false
3423     *         otherwise is returned.
3424     */
3425    public boolean performClick() {
3426        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3427
3428        if (mOnClickListener != null) {
3429            playSoundEffect(SoundEffectConstants.CLICK);
3430            mOnClickListener.onClick(this);
3431            return true;
3432        }
3433
3434        return false;
3435    }
3436
3437    /**
3438     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3439     * OnLongClickListener did not consume the event.
3440     *
3441     * @return True if one of the above receivers consumed the event, false otherwise.
3442     */
3443    public boolean performLongClick() {
3444        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3445
3446        boolean handled = false;
3447        if (mOnLongClickListener != null) {
3448            handled = mOnLongClickListener.onLongClick(View.this);
3449        }
3450        if (!handled) {
3451            handled = showContextMenu();
3452        }
3453        if (handled) {
3454            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3455        }
3456        return handled;
3457    }
3458
3459    /**
3460     * Performs button-related actions during a touch down event.
3461     *
3462     * @param event The event.
3463     * @return True if the down was consumed.
3464     *
3465     * @hide
3466     */
3467    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3468        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3469            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3470                return true;
3471            }
3472        }
3473        return false;
3474    }
3475
3476    /**
3477     * Bring up the context menu for this view.
3478     *
3479     * @return Whether a context menu was displayed.
3480     */
3481    public boolean showContextMenu() {
3482        return getParent().showContextMenuForChild(this);
3483    }
3484
3485    /**
3486     * Bring up the context menu for this view, referring to the item under the specified point.
3487     *
3488     * @param x The referenced x coordinate.
3489     * @param y The referenced y coordinate.
3490     * @param metaState The keyboard modifiers that were pressed.
3491     * @return Whether a context menu was displayed.
3492     *
3493     * @hide
3494     */
3495    public boolean showContextMenu(float x, float y, int metaState) {
3496        return showContextMenu();
3497    }
3498
3499    /**
3500     * Start an action mode.
3501     *
3502     * @param callback Callback that will control the lifecycle of the action mode
3503     * @return The new action mode if it is started, null otherwise
3504     *
3505     * @see ActionMode
3506     */
3507    public ActionMode startActionMode(ActionMode.Callback callback) {
3508        return getParent().startActionModeForChild(this, callback);
3509    }
3510
3511    /**
3512     * Register a callback to be invoked when a key is pressed in this view.
3513     * @param l the key listener to attach to this view
3514     */
3515    public void setOnKeyListener(OnKeyListener l) {
3516        mOnKeyListener = l;
3517    }
3518
3519    /**
3520     * Register a callback to be invoked when a touch event is sent to this view.
3521     * @param l the touch listener to attach to this view
3522     */
3523    public void setOnTouchListener(OnTouchListener l) {
3524        mOnTouchListener = l;
3525    }
3526
3527    /**
3528     * Register a callback to be invoked when a generic motion event is sent to this view.
3529     * @param l the generic motion listener to attach to this view
3530     */
3531    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3532        mOnGenericMotionListener = l;
3533    }
3534
3535    /**
3536     * Register a callback to be invoked when a hover event is sent to this view.
3537     * @param l the hover listener to attach to this view
3538     */
3539    public void setOnHoverListener(OnHoverListener l) {
3540        mOnHoverListener = l;
3541    }
3542
3543    /**
3544     * Register a drag event listener callback object for this View. The parameter is
3545     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3546     * View, the system calls the
3547     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3548     * @param l An implementation of {@link android.view.View.OnDragListener}.
3549     */
3550    public void setOnDragListener(OnDragListener l) {
3551        mOnDragListener = l;
3552    }
3553
3554    /**
3555     * Give this view focus. This will cause
3556     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3557     *
3558     * Note: this does not check whether this {@link View} should get focus, it just
3559     * gives it focus no matter what.  It should only be called internally by framework
3560     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3561     *
3562     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3563     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3564     *        focus moved when requestFocus() is called. It may not always
3565     *        apply, in which case use the default View.FOCUS_DOWN.
3566     * @param previouslyFocusedRect The rectangle of the view that had focus
3567     *        prior in this View's coordinate system.
3568     */
3569    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3570        if (DBG) {
3571            System.out.println(this + " requestFocus()");
3572        }
3573
3574        if ((mPrivateFlags & FOCUSED) == 0) {
3575            mPrivateFlags |= FOCUSED;
3576
3577            if (mParent != null) {
3578                mParent.requestChildFocus(this, this);
3579            }
3580
3581            onFocusChanged(true, direction, previouslyFocusedRect);
3582            refreshDrawableState();
3583        }
3584    }
3585
3586    /**
3587     * Request that a rectangle of this view be visible on the screen,
3588     * scrolling if necessary just enough.
3589     *
3590     * <p>A View should call this if it maintains some notion of which part
3591     * of its content is interesting.  For example, a text editing view
3592     * should call this when its cursor moves.
3593     *
3594     * @param rectangle The rectangle.
3595     * @return Whether any parent scrolled.
3596     */
3597    public boolean requestRectangleOnScreen(Rect rectangle) {
3598        return requestRectangleOnScreen(rectangle, false);
3599    }
3600
3601    /**
3602     * Request that a rectangle of this view be visible on the screen,
3603     * scrolling if necessary just enough.
3604     *
3605     * <p>A View should call this if it maintains some notion of which part
3606     * of its content is interesting.  For example, a text editing view
3607     * should call this when its cursor moves.
3608     *
3609     * <p>When <code>immediate</code> is set to true, scrolling will not be
3610     * animated.
3611     *
3612     * @param rectangle The rectangle.
3613     * @param immediate True to forbid animated scrolling, false otherwise
3614     * @return Whether any parent scrolled.
3615     */
3616    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3617        View child = this;
3618        ViewParent parent = mParent;
3619        boolean scrolled = false;
3620        while (parent != null) {
3621            scrolled |= parent.requestChildRectangleOnScreen(child,
3622                    rectangle, immediate);
3623
3624            // offset rect so next call has the rectangle in the
3625            // coordinate system of its direct child.
3626            rectangle.offset(child.getLeft(), child.getTop());
3627            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3628
3629            if (!(parent instanceof View)) {
3630                break;
3631            }
3632
3633            child = (View) parent;
3634            parent = child.getParent();
3635        }
3636        return scrolled;
3637    }
3638
3639    /**
3640     * Called when this view wants to give up focus. This will cause
3641     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3642     */
3643    public void clearFocus() {
3644        if (DBG) {
3645            System.out.println(this + " clearFocus()");
3646        }
3647
3648        if ((mPrivateFlags & FOCUSED) != 0) {
3649            mPrivateFlags &= ~FOCUSED;
3650
3651            if (mParent != null) {
3652                mParent.clearChildFocus(this);
3653            }
3654
3655            onFocusChanged(false, 0, null);
3656            refreshDrawableState();
3657        }
3658    }
3659
3660    /**
3661     * Called to clear the focus of a view that is about to be removed.
3662     * Doesn't call clearChildFocus, which prevents this view from taking
3663     * focus again before it has been removed from the parent
3664     */
3665    void clearFocusForRemoval() {
3666        if ((mPrivateFlags & FOCUSED) != 0) {
3667            mPrivateFlags &= ~FOCUSED;
3668
3669            onFocusChanged(false, 0, null);
3670            refreshDrawableState();
3671        }
3672    }
3673
3674    /**
3675     * Called internally by the view system when a new view is getting focus.
3676     * This is what clears the old focus.
3677     */
3678    void unFocus() {
3679        if (DBG) {
3680            System.out.println(this + " unFocus()");
3681        }
3682
3683        if ((mPrivateFlags & FOCUSED) != 0) {
3684            mPrivateFlags &= ~FOCUSED;
3685
3686            onFocusChanged(false, 0, null);
3687            refreshDrawableState();
3688        }
3689    }
3690
3691    /**
3692     * Returns true if this view has focus iteself, or is the ancestor of the
3693     * view that has focus.
3694     *
3695     * @return True if this view has or contains focus, false otherwise.
3696     */
3697    @ViewDebug.ExportedProperty(category = "focus")
3698    public boolean hasFocus() {
3699        return (mPrivateFlags & FOCUSED) != 0;
3700    }
3701
3702    /**
3703     * Returns true if this view is focusable or if it contains a reachable View
3704     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3705     * is a View whose parents do not block descendants focus.
3706     *
3707     * Only {@link #VISIBLE} views are considered focusable.
3708     *
3709     * @return True if the view is focusable or if the view contains a focusable
3710     *         View, false otherwise.
3711     *
3712     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3713     */
3714    public boolean hasFocusable() {
3715        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3716    }
3717
3718    /**
3719     * Called by the view system when the focus state of this view changes.
3720     * When the focus change event is caused by directional navigation, direction
3721     * and previouslyFocusedRect provide insight into where the focus is coming from.
3722     * When overriding, be sure to call up through to the super class so that
3723     * the standard focus handling will occur.
3724     *
3725     * @param gainFocus True if the View has focus; false otherwise.
3726     * @param direction The direction focus has moved when requestFocus()
3727     *                  is called to give this view focus. Values are
3728     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3729     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3730     *                  It may not always apply, in which case use the default.
3731     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3732     *        system, of the previously focused view.  If applicable, this will be
3733     *        passed in as finer grained information about where the focus is coming
3734     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3735     */
3736    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3737        if (gainFocus) {
3738            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3739        }
3740
3741        InputMethodManager imm = InputMethodManager.peekInstance();
3742        if (!gainFocus) {
3743            if (isPressed()) {
3744                setPressed(false);
3745            }
3746            if (imm != null && mAttachInfo != null
3747                    && mAttachInfo.mHasWindowFocus) {
3748                imm.focusOut(this);
3749            }
3750            onFocusLost();
3751        } else if (imm != null && mAttachInfo != null
3752                && mAttachInfo.mHasWindowFocus) {
3753            imm.focusIn(this);
3754        }
3755
3756        invalidate(true);
3757        if (mOnFocusChangeListener != null) {
3758            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3759        }
3760
3761        if (mAttachInfo != null) {
3762            mAttachInfo.mKeyDispatchState.reset(this);
3763        }
3764    }
3765
3766    /**
3767     * Sends an accessibility event of the given type. If accessiiblity is
3768     * not enabled this method has no effect. The default implementation calls
3769     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3770     * to populate information about the event source (this View), then calls
3771     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3772     * populate the text content of the event source including its descendants,
3773     * and last calls
3774     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3775     * on its parent to resuest sending of the event to interested parties.
3776     *
3777     * @param eventType The type of the event to send.
3778     *
3779     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3780     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3781     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3782     */
3783    public void sendAccessibilityEvent(int eventType) {
3784        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3785            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3786        }
3787    }
3788
3789    /**
3790     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3791     * takes as an argument an empty {@link AccessibilityEvent} and does not
3792     * perfrom a check whether accessibility is enabled.
3793     *
3794     * @param event The event to send.
3795     *
3796     * @see #sendAccessibilityEvent(int)
3797     */
3798    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3799        if (!isShown()) {
3800            return;
3801        }
3802        onInitializeAccessibilityEvent(event);
3803        dispatchPopulateAccessibilityEvent(event);
3804        // In the beginning we called #isShown(), so we know that getParent() is not null.
3805        getParent().requestSendAccessibilityEvent(this, event);
3806    }
3807
3808    /**
3809     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3810     * to its children for adding their text content to the event. Note that the
3811     * event text is populated in a separate dispatch path since we add to the
3812     * event not only the text of the source but also the text of all its descendants.
3813     * </p>
3814     * A typical implementation will call
3815     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3816     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3817     * on each child. Override this method if custom population of the event text
3818     * content is required.
3819     *
3820     * @param event The event.
3821     *
3822     * @return True if the event population was completed.
3823     */
3824    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3825        onPopulateAccessibilityEvent(event);
3826        return false;
3827    }
3828
3829    /**
3830     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3831     * giving a chance to this View to populate the accessibility event with its
3832     * text content. While the implementation is free to modify other event
3833     * attributes this should be performed in
3834     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
3835     * <p>
3836     * Example: Adding formatted date string to an accessibility event in addition
3837     *          to the text added by the super implementation.
3838     * </p><p><pre><code>
3839     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3840     *     super.onPopulateAccessibilityEvent(event);
3841     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
3842     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
3843     *         mCurrentDate.getTimeInMillis(), flags);
3844     *     event.getText().add(selectedDateUtterance);
3845     * }
3846     * </code></pre></p>
3847     *
3848     * @param event The accessibility event which to populate.
3849     *
3850     * @see #sendAccessibilityEvent(int)
3851     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3852     */
3853    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3854    }
3855
3856    /**
3857     * Initializes an {@link AccessibilityEvent} with information about the
3858     * the type of the event and this View which is the event source. In other
3859     * words, the source of an accessibility event is the view whose state
3860     * change triggered firing the event.
3861     * <p>
3862     * Example: Setting the password property of an event in addition
3863     *          to properties set by the super implementation.
3864     * </p><p><pre><code>
3865     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3866     *    super.onInitializeAccessibilityEvent(event);
3867     *    event.setPassword(true);
3868     * }
3869     * </code></pre></p>
3870     * @param event The event to initialeze.
3871     *
3872     * @see #sendAccessibilityEvent(int)
3873     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3874     */
3875    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3876        event.setSource(this);
3877        event.setClassName(getClass().getName());
3878        event.setPackageName(getContext().getPackageName());
3879        event.setEnabled(isEnabled());
3880        event.setContentDescription(mContentDescription);
3881
3882        final int eventType = event.getEventType();
3883        switch (eventType) {
3884            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
3885                if (mAttachInfo != null) {
3886                    ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
3887                    getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
3888                            FOCUSABLES_ALL);
3889                    event.setItemCount(focusablesTempList.size());
3890                    event.setCurrentItemIndex(focusablesTempList.indexOf(this));
3891                    focusablesTempList.clear();
3892                }
3893            } break;
3894            case AccessibilityEvent.TYPE_VIEW_SCROLLED: {
3895                event.setScrollX(mScrollX);
3896                event.setScrollY(mScrollY);
3897                event.setItemCount(getHeight());
3898            } break;
3899        }
3900    }
3901
3902    /**
3903     * Returns an {@link AccessibilityNodeInfo} representing this view from the
3904     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
3905     * This method is responsible for obtaining an accessibility node info from a
3906     * pool of reusable instances and calling
3907     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
3908     * initialize the former.
3909     * <p>
3910     * Note: The client is responsible for recycling the obtained instance by calling
3911     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
3912     * </p>
3913     * @return A populated {@link AccessibilityNodeInfo}.
3914     *
3915     * @see AccessibilityNodeInfo
3916     */
3917    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
3918        AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
3919        onInitializeAccessibilityNodeInfo(info);
3920        return info;
3921    }
3922
3923    /**
3924     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
3925     * The base implementation sets:
3926     * <ul>
3927     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
3928     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
3929     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
3930     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
3931     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
3932     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
3933     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
3934     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
3935     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
3936     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
3937     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
3938     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
3939     * </ul>
3940     * <p>
3941     * Subclasses should override this method, call the super implementation,
3942     * and set additional attributes.
3943     * </p>
3944     * @param info The instance to initialize.
3945     */
3946    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
3947        Rect bounds = mAttachInfo.mTmpInvalRect;
3948        getDrawingRect(bounds);
3949        info.setBoundsInParent(bounds);
3950
3951        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
3952        getLocationOnScreen(locationOnScreen);
3953        bounds.offsetTo(0, 0);
3954        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
3955        info.setBoundsInScreen(bounds);
3956
3957        ViewParent parent = getParent();
3958        if (parent instanceof View) {
3959            View parentView = (View) parent;
3960            info.setParent(parentView);
3961        }
3962
3963        info.setPackageName(mContext.getPackageName());
3964        info.setClassName(getClass().getName());
3965        info.setContentDescription(getContentDescription());
3966
3967        info.setEnabled(isEnabled());
3968        info.setClickable(isClickable());
3969        info.setFocusable(isFocusable());
3970        info.setFocused(isFocused());
3971        info.setSelected(isSelected());
3972        info.setLongClickable(isLongClickable());
3973
3974        // TODO: These make sense only if we are in an AdapterView but all
3975        // views can be selected. Maybe from accessiiblity perspective
3976        // we should report as selectable view in an AdapterView.
3977        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
3978        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
3979
3980        if (isFocusable()) {
3981            if (isFocused()) {
3982                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
3983            } else {
3984                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
3985            }
3986        }
3987    }
3988
3989    /**
3990     * Gets the unique identifier of this view on the screen for accessibility purposes.
3991     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
3992     *
3993     * @return The view accessibility id.
3994     *
3995     * @hide
3996     */
3997    public int getAccessibilityViewId() {
3998        if (mAccessibilityViewId == NO_ID) {
3999            mAccessibilityViewId = sNextAccessibilityViewId++;
4000        }
4001        return mAccessibilityViewId;
4002    }
4003
4004    /**
4005     * Gets the unique identifier of the window in which this View reseides.
4006     *
4007     * @return The window accessibility id.
4008     *
4009     * @hide
4010     */
4011    public int getAccessibilityWindowId() {
4012        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4013    }
4014
4015    /**
4016     * Gets the {@link View} description. It briefly describes the view and is
4017     * primarily used for accessibility support. Set this property to enable
4018     * better accessibility support for your application. This is especially
4019     * true for views that do not have textual representation (For example,
4020     * ImageButton).
4021     *
4022     * @return The content descriptiopn.
4023     *
4024     * @attr ref android.R.styleable#View_contentDescription
4025     */
4026    public CharSequence getContentDescription() {
4027        return mContentDescription;
4028    }
4029
4030    /**
4031     * Sets the {@link View} description. It briefly describes the view and is
4032     * primarily used for accessibility support. Set this property to enable
4033     * better accessibility support for your application. This is especially
4034     * true for views that do not have textual representation (For example,
4035     * ImageButton).
4036     *
4037     * @param contentDescription The content description.
4038     *
4039     * @attr ref android.R.styleable#View_contentDescription
4040     */
4041    public void setContentDescription(CharSequence contentDescription) {
4042        mContentDescription = contentDescription;
4043    }
4044
4045    /**
4046     * Invoked whenever this view loses focus, either by losing window focus or by losing
4047     * focus within its window. This method can be used to clear any state tied to the
4048     * focus. For instance, if a button is held pressed with the trackball and the window
4049     * loses focus, this method can be used to cancel the press.
4050     *
4051     * Subclasses of View overriding this method should always call super.onFocusLost().
4052     *
4053     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4054     * @see #onWindowFocusChanged(boolean)
4055     *
4056     * @hide pending API council approval
4057     */
4058    protected void onFocusLost() {
4059        resetPressedState();
4060    }
4061
4062    private void resetPressedState() {
4063        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4064            return;
4065        }
4066
4067        if (isPressed()) {
4068            setPressed(false);
4069
4070            if (!mHasPerformedLongPress) {
4071                removeLongPressCallback();
4072            }
4073        }
4074    }
4075
4076    /**
4077     * Returns true if this view has focus
4078     *
4079     * @return True if this view has focus, false otherwise.
4080     */
4081    @ViewDebug.ExportedProperty(category = "focus")
4082    public boolean isFocused() {
4083        return (mPrivateFlags & FOCUSED) != 0;
4084    }
4085
4086    /**
4087     * Find the view in the hierarchy rooted at this view that currently has
4088     * focus.
4089     *
4090     * @return The view that currently has focus, or null if no focused view can
4091     *         be found.
4092     */
4093    public View findFocus() {
4094        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4095    }
4096
4097    /**
4098     * Change whether this view is one of the set of scrollable containers in
4099     * its window.  This will be used to determine whether the window can
4100     * resize or must pan when a soft input area is open -- scrollable
4101     * containers allow the window to use resize mode since the container
4102     * will appropriately shrink.
4103     */
4104    public void setScrollContainer(boolean isScrollContainer) {
4105        if (isScrollContainer) {
4106            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4107                mAttachInfo.mScrollContainers.add(this);
4108                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4109            }
4110            mPrivateFlags |= SCROLL_CONTAINER;
4111        } else {
4112            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4113                mAttachInfo.mScrollContainers.remove(this);
4114            }
4115            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4116        }
4117    }
4118
4119    /**
4120     * Returns the quality of the drawing cache.
4121     *
4122     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4123     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4124     *
4125     * @see #setDrawingCacheQuality(int)
4126     * @see #setDrawingCacheEnabled(boolean)
4127     * @see #isDrawingCacheEnabled()
4128     *
4129     * @attr ref android.R.styleable#View_drawingCacheQuality
4130     */
4131    public int getDrawingCacheQuality() {
4132        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4133    }
4134
4135    /**
4136     * Set the drawing cache quality of this view. This value is used only when the
4137     * drawing cache is enabled
4138     *
4139     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4140     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4141     *
4142     * @see #getDrawingCacheQuality()
4143     * @see #setDrawingCacheEnabled(boolean)
4144     * @see #isDrawingCacheEnabled()
4145     *
4146     * @attr ref android.R.styleable#View_drawingCacheQuality
4147     */
4148    public void setDrawingCacheQuality(int quality) {
4149        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4150    }
4151
4152    /**
4153     * Returns whether the screen should remain on, corresponding to the current
4154     * value of {@link #KEEP_SCREEN_ON}.
4155     *
4156     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4157     *
4158     * @see #setKeepScreenOn(boolean)
4159     *
4160     * @attr ref android.R.styleable#View_keepScreenOn
4161     */
4162    public boolean getKeepScreenOn() {
4163        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4164    }
4165
4166    /**
4167     * Controls whether the screen should remain on, modifying the
4168     * value of {@link #KEEP_SCREEN_ON}.
4169     *
4170     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4171     *
4172     * @see #getKeepScreenOn()
4173     *
4174     * @attr ref android.R.styleable#View_keepScreenOn
4175     */
4176    public void setKeepScreenOn(boolean keepScreenOn) {
4177        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4178    }
4179
4180    /**
4181     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4182     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4183     *
4184     * @attr ref android.R.styleable#View_nextFocusLeft
4185     */
4186    public int getNextFocusLeftId() {
4187        return mNextFocusLeftId;
4188    }
4189
4190    /**
4191     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4192     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4193     * decide automatically.
4194     *
4195     * @attr ref android.R.styleable#View_nextFocusLeft
4196     */
4197    public void setNextFocusLeftId(int nextFocusLeftId) {
4198        mNextFocusLeftId = nextFocusLeftId;
4199    }
4200
4201    /**
4202     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4203     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4204     *
4205     * @attr ref android.R.styleable#View_nextFocusRight
4206     */
4207    public int getNextFocusRightId() {
4208        return mNextFocusRightId;
4209    }
4210
4211    /**
4212     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4213     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4214     * decide automatically.
4215     *
4216     * @attr ref android.R.styleable#View_nextFocusRight
4217     */
4218    public void setNextFocusRightId(int nextFocusRightId) {
4219        mNextFocusRightId = nextFocusRightId;
4220    }
4221
4222    /**
4223     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4224     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4225     *
4226     * @attr ref android.R.styleable#View_nextFocusUp
4227     */
4228    public int getNextFocusUpId() {
4229        return mNextFocusUpId;
4230    }
4231
4232    /**
4233     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4234     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4235     * decide automatically.
4236     *
4237     * @attr ref android.R.styleable#View_nextFocusUp
4238     */
4239    public void setNextFocusUpId(int nextFocusUpId) {
4240        mNextFocusUpId = nextFocusUpId;
4241    }
4242
4243    /**
4244     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4245     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4246     *
4247     * @attr ref android.R.styleable#View_nextFocusDown
4248     */
4249    public int getNextFocusDownId() {
4250        return mNextFocusDownId;
4251    }
4252
4253    /**
4254     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4255     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4256     * decide automatically.
4257     *
4258     * @attr ref android.R.styleable#View_nextFocusDown
4259     */
4260    public void setNextFocusDownId(int nextFocusDownId) {
4261        mNextFocusDownId = nextFocusDownId;
4262    }
4263
4264    /**
4265     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4266     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4267     *
4268     * @attr ref android.R.styleable#View_nextFocusForward
4269     */
4270    public int getNextFocusForwardId() {
4271        return mNextFocusForwardId;
4272    }
4273
4274    /**
4275     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4276     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4277     * decide automatically.
4278     *
4279     * @attr ref android.R.styleable#View_nextFocusForward
4280     */
4281    public void setNextFocusForwardId(int nextFocusForwardId) {
4282        mNextFocusForwardId = nextFocusForwardId;
4283    }
4284
4285    /**
4286     * Returns the visibility of this view and all of its ancestors
4287     *
4288     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4289     */
4290    public boolean isShown() {
4291        View current = this;
4292        //noinspection ConstantConditions
4293        do {
4294            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4295                return false;
4296            }
4297            ViewParent parent = current.mParent;
4298            if (parent == null) {
4299                return false; // We are not attached to the view root
4300            }
4301            if (!(parent instanceof View)) {
4302                return true;
4303            }
4304            current = (View) parent;
4305        } while (current != null);
4306
4307        return false;
4308    }
4309
4310    /**
4311     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4312     * is set
4313     *
4314     * @param insets Insets for system windows
4315     *
4316     * @return True if this view applied the insets, false otherwise
4317     */
4318    protected boolean fitSystemWindows(Rect insets) {
4319        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4320            mPaddingLeft = insets.left;
4321            mPaddingTop = insets.top;
4322            mPaddingRight = insets.right;
4323            mPaddingBottom = insets.bottom;
4324            requestLayout();
4325            return true;
4326        }
4327        return false;
4328    }
4329
4330    /**
4331     * Set whether or not this view should account for system screen decorations
4332     * such as the status bar and inset its content. This allows this view to be
4333     * positioned in absolute screen coordinates and remain visible to the user.
4334     *
4335     * <p>This should only be used by top-level window decor views.
4336     *
4337     * @param fitSystemWindows true to inset content for system screen decorations, false for
4338     *                         default behavior.
4339     *
4340     * @attr ref android.R.styleable#View_fitsSystemWindows
4341     */
4342    public void setFitsSystemWindows(boolean fitSystemWindows) {
4343        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4344    }
4345
4346    /**
4347     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4348     * will account for system screen decorations such as the status bar and inset its
4349     * content. This allows the view to be positioned in absolute screen coordinates
4350     * and remain visible to the user.
4351     *
4352     * @return true if this view will adjust its content bounds for system screen decorations.
4353     *
4354     * @attr ref android.R.styleable#View_fitsSystemWindows
4355     */
4356    public boolean fitsSystemWindows() {
4357        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4358    }
4359
4360    /**
4361     * Returns the visibility status for this view.
4362     *
4363     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4364     * @attr ref android.R.styleable#View_visibility
4365     */
4366    @ViewDebug.ExportedProperty(mapping = {
4367        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4368        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4369        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4370    })
4371    public int getVisibility() {
4372        return mViewFlags & VISIBILITY_MASK;
4373    }
4374
4375    /**
4376     * Set the enabled state of this view.
4377     *
4378     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4379     * @attr ref android.R.styleable#View_visibility
4380     */
4381    @RemotableViewMethod
4382    public void setVisibility(int visibility) {
4383        setFlags(visibility, VISIBILITY_MASK);
4384        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4385    }
4386
4387    /**
4388     * Returns the enabled status for this view. The interpretation of the
4389     * enabled state varies by subclass.
4390     *
4391     * @return True if this view is enabled, false otherwise.
4392     */
4393    @ViewDebug.ExportedProperty
4394    public boolean isEnabled() {
4395        return (mViewFlags & ENABLED_MASK) == ENABLED;
4396    }
4397
4398    /**
4399     * Set the enabled state of this view. The interpretation of the enabled
4400     * state varies by subclass.
4401     *
4402     * @param enabled True if this view is enabled, false otherwise.
4403     */
4404    @RemotableViewMethod
4405    public void setEnabled(boolean enabled) {
4406        if (enabled == isEnabled()) return;
4407
4408        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4409
4410        /*
4411         * The View most likely has to change its appearance, so refresh
4412         * the drawable state.
4413         */
4414        refreshDrawableState();
4415
4416        // Invalidate too, since the default behavior for views is to be
4417        // be drawn at 50% alpha rather than to change the drawable.
4418        invalidate(true);
4419    }
4420
4421    /**
4422     * Set whether this view can receive the focus.
4423     *
4424     * Setting this to false will also ensure that this view is not focusable
4425     * in touch mode.
4426     *
4427     * @param focusable If true, this view can receive the focus.
4428     *
4429     * @see #setFocusableInTouchMode(boolean)
4430     * @attr ref android.R.styleable#View_focusable
4431     */
4432    public void setFocusable(boolean focusable) {
4433        if (!focusable) {
4434            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4435        }
4436        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4437    }
4438
4439    /**
4440     * Set whether this view can receive focus while in touch mode.
4441     *
4442     * Setting this to true will also ensure that this view is focusable.
4443     *
4444     * @param focusableInTouchMode If true, this view can receive the focus while
4445     *   in touch mode.
4446     *
4447     * @see #setFocusable(boolean)
4448     * @attr ref android.R.styleable#View_focusableInTouchMode
4449     */
4450    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4451        // Focusable in touch mode should always be set before the focusable flag
4452        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4453        // which, in touch mode, will not successfully request focus on this view
4454        // because the focusable in touch mode flag is not set
4455        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4456        if (focusableInTouchMode) {
4457            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4458        }
4459    }
4460
4461    /**
4462     * Set whether this view should have sound effects enabled for events such as
4463     * clicking and touching.
4464     *
4465     * <p>You may wish to disable sound effects for a view if you already play sounds,
4466     * for instance, a dial key that plays dtmf tones.
4467     *
4468     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4469     * @see #isSoundEffectsEnabled()
4470     * @see #playSoundEffect(int)
4471     * @attr ref android.R.styleable#View_soundEffectsEnabled
4472     */
4473    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4474        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4475    }
4476
4477    /**
4478     * @return whether this view should have sound effects enabled for events such as
4479     *     clicking and touching.
4480     *
4481     * @see #setSoundEffectsEnabled(boolean)
4482     * @see #playSoundEffect(int)
4483     * @attr ref android.R.styleable#View_soundEffectsEnabled
4484     */
4485    @ViewDebug.ExportedProperty
4486    public boolean isSoundEffectsEnabled() {
4487        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4488    }
4489
4490    /**
4491     * Set whether this view should have haptic feedback for events such as
4492     * long presses.
4493     *
4494     * <p>You may wish to disable haptic feedback if your view already controls
4495     * its own haptic feedback.
4496     *
4497     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4498     * @see #isHapticFeedbackEnabled()
4499     * @see #performHapticFeedback(int)
4500     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4501     */
4502    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4503        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4504    }
4505
4506    /**
4507     * @return whether this view should have haptic feedback enabled for events
4508     * long presses.
4509     *
4510     * @see #setHapticFeedbackEnabled(boolean)
4511     * @see #performHapticFeedback(int)
4512     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4513     */
4514    @ViewDebug.ExportedProperty
4515    public boolean isHapticFeedbackEnabled() {
4516        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4517    }
4518
4519    /**
4520     * Returns the layout direction for this view.
4521     *
4522     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4523     *   {@link #LAYOUT_DIRECTION_RTL},
4524     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4525     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4526     * @attr ref android.R.styleable#View_layoutDirection
4527     *
4528     * @hide
4529     */
4530    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4531        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4532        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4533        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4534        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4535    })
4536    public int getLayoutDirection() {
4537        return mViewFlags & LAYOUT_DIRECTION_MASK;
4538    }
4539
4540    /**
4541     * Set the layout direction for this view. This will propagate a reset of layout direction
4542     * resolution to the view's children and resolve layout direction for this view.
4543     *
4544     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4545     *   {@link #LAYOUT_DIRECTION_RTL},
4546     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4547     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4548     *
4549     * @attr ref android.R.styleable#View_layoutDirection
4550     *
4551     * @hide
4552     */
4553    @RemotableViewMethod
4554    public void setLayoutDirection(int layoutDirection) {
4555        if (getLayoutDirection() != layoutDirection) {
4556            resetResolvedLayoutDirection();
4557            // Setting the flag will also request a layout.
4558            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4559        }
4560    }
4561
4562    /**
4563     * Returns the resolved layout direction for this view.
4564     *
4565     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4566     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4567     *
4568     * @hide
4569     */
4570    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4571        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4572        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4573    })
4574    public int getResolvedLayoutDirection() {
4575        resolveLayoutDirectionIfNeeded();
4576        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4577                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4578    }
4579
4580    /**
4581     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4582     * layout attribute and/or the inherited value from the parent.</p>
4583     *
4584     * @return true if the layout is right-to-left.
4585     *
4586     * @hide
4587     */
4588    @ViewDebug.ExportedProperty(category = "layout")
4589    public boolean isLayoutRtl() {
4590        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4591    }
4592
4593    /**
4594     * If this view doesn't do any drawing on its own, set this flag to
4595     * allow further optimizations. By default, this flag is not set on
4596     * View, but could be set on some View subclasses such as ViewGroup.
4597     *
4598     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4599     * you should clear this flag.
4600     *
4601     * @param willNotDraw whether or not this View draw on its own
4602     */
4603    public void setWillNotDraw(boolean willNotDraw) {
4604        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4605    }
4606
4607    /**
4608     * Returns whether or not this View draws on its own.
4609     *
4610     * @return true if this view has nothing to draw, false otherwise
4611     */
4612    @ViewDebug.ExportedProperty(category = "drawing")
4613    public boolean willNotDraw() {
4614        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4615    }
4616
4617    /**
4618     * When a View's drawing cache is enabled, drawing is redirected to an
4619     * offscreen bitmap. Some views, like an ImageView, must be able to
4620     * bypass this mechanism if they already draw a single bitmap, to avoid
4621     * unnecessary usage of the memory.
4622     *
4623     * @param willNotCacheDrawing true if this view does not cache its
4624     *        drawing, false otherwise
4625     */
4626    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4627        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4628    }
4629
4630    /**
4631     * Returns whether or not this View can cache its drawing or not.
4632     *
4633     * @return true if this view does not cache its drawing, false otherwise
4634     */
4635    @ViewDebug.ExportedProperty(category = "drawing")
4636    public boolean willNotCacheDrawing() {
4637        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4638    }
4639
4640    /**
4641     * Indicates whether this view reacts to click events or not.
4642     *
4643     * @return true if the view is clickable, false otherwise
4644     *
4645     * @see #setClickable(boolean)
4646     * @attr ref android.R.styleable#View_clickable
4647     */
4648    @ViewDebug.ExportedProperty
4649    public boolean isClickable() {
4650        return (mViewFlags & CLICKABLE) == CLICKABLE;
4651    }
4652
4653    /**
4654     * Enables or disables click events for this view. When a view
4655     * is clickable it will change its state to "pressed" on every click.
4656     * Subclasses should set the view clickable to visually react to
4657     * user's clicks.
4658     *
4659     * @param clickable true to make the view clickable, false otherwise
4660     *
4661     * @see #isClickable()
4662     * @attr ref android.R.styleable#View_clickable
4663     */
4664    public void setClickable(boolean clickable) {
4665        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4666    }
4667
4668    /**
4669     * Indicates whether this view reacts to long click events or not.
4670     *
4671     * @return true if the view is long clickable, false otherwise
4672     *
4673     * @see #setLongClickable(boolean)
4674     * @attr ref android.R.styleable#View_longClickable
4675     */
4676    public boolean isLongClickable() {
4677        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4678    }
4679
4680    /**
4681     * Enables or disables long click events for this view. When a view is long
4682     * clickable it reacts to the user holding down the button for a longer
4683     * duration than a tap. This event can either launch the listener or a
4684     * context menu.
4685     *
4686     * @param longClickable true to make the view long clickable, false otherwise
4687     * @see #isLongClickable()
4688     * @attr ref android.R.styleable#View_longClickable
4689     */
4690    public void setLongClickable(boolean longClickable) {
4691        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4692    }
4693
4694    /**
4695     * Sets the pressed state for this view.
4696     *
4697     * @see #isClickable()
4698     * @see #setClickable(boolean)
4699     *
4700     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4701     *        the View's internal state from a previously set "pressed" state.
4702     */
4703    public void setPressed(boolean pressed) {
4704        if (pressed) {
4705            mPrivateFlags |= PRESSED;
4706        } else {
4707            mPrivateFlags &= ~PRESSED;
4708        }
4709        refreshDrawableState();
4710        dispatchSetPressed(pressed);
4711    }
4712
4713    /**
4714     * Dispatch setPressed to all of this View's children.
4715     *
4716     * @see #setPressed(boolean)
4717     *
4718     * @param pressed The new pressed state
4719     */
4720    protected void dispatchSetPressed(boolean pressed) {
4721    }
4722
4723    /**
4724     * Indicates whether the view is currently in pressed state. Unless
4725     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4726     * the pressed state.
4727     *
4728     * @see #setPressed(boolean)
4729     * @see #isClickable()
4730     * @see #setClickable(boolean)
4731     *
4732     * @return true if the view is currently pressed, false otherwise
4733     */
4734    public boolean isPressed() {
4735        return (mPrivateFlags & PRESSED) == PRESSED;
4736    }
4737
4738    /**
4739     * Indicates whether this view will save its state (that is,
4740     * whether its {@link #onSaveInstanceState} method will be called).
4741     *
4742     * @return Returns true if the view state saving is enabled, else false.
4743     *
4744     * @see #setSaveEnabled(boolean)
4745     * @attr ref android.R.styleable#View_saveEnabled
4746     */
4747    public boolean isSaveEnabled() {
4748        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4749    }
4750
4751    /**
4752     * Controls whether the saving of this view's state is
4753     * enabled (that is, whether its {@link #onSaveInstanceState} method
4754     * will be called).  Note that even if freezing is enabled, the
4755     * view still must have an id assigned to it (via {@link #setId(int)})
4756     * for its state to be saved.  This flag can only disable the
4757     * saving of this view; any child views may still have their state saved.
4758     *
4759     * @param enabled Set to false to <em>disable</em> state saving, or true
4760     * (the default) to allow it.
4761     *
4762     * @see #isSaveEnabled()
4763     * @see #setId(int)
4764     * @see #onSaveInstanceState()
4765     * @attr ref android.R.styleable#View_saveEnabled
4766     */
4767    public void setSaveEnabled(boolean enabled) {
4768        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4769    }
4770
4771    /**
4772     * Gets whether the framework should discard touches when the view's
4773     * window is obscured by another visible window.
4774     * Refer to the {@link View} security documentation for more details.
4775     *
4776     * @return True if touch filtering is enabled.
4777     *
4778     * @see #setFilterTouchesWhenObscured(boolean)
4779     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4780     */
4781    @ViewDebug.ExportedProperty
4782    public boolean getFilterTouchesWhenObscured() {
4783        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4784    }
4785
4786    /**
4787     * Sets whether the framework should discard touches when the view's
4788     * window is obscured by another visible window.
4789     * Refer to the {@link View} security documentation for more details.
4790     *
4791     * @param enabled True if touch filtering should be enabled.
4792     *
4793     * @see #getFilterTouchesWhenObscured
4794     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4795     */
4796    public void setFilterTouchesWhenObscured(boolean enabled) {
4797        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4798                FILTER_TOUCHES_WHEN_OBSCURED);
4799    }
4800
4801    /**
4802     * Indicates whether the entire hierarchy under this view will save its
4803     * state when a state saving traversal occurs from its parent.  The default
4804     * is true; if false, these views will not be saved unless
4805     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4806     *
4807     * @return Returns true if the view state saving from parent is enabled, else false.
4808     *
4809     * @see #setSaveFromParentEnabled(boolean)
4810     */
4811    public boolean isSaveFromParentEnabled() {
4812        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4813    }
4814
4815    /**
4816     * Controls whether the entire hierarchy under this view will save its
4817     * state when a state saving traversal occurs from its parent.  The default
4818     * is true; if false, these views will not be saved unless
4819     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4820     *
4821     * @param enabled Set to false to <em>disable</em> state saving, or true
4822     * (the default) to allow it.
4823     *
4824     * @see #isSaveFromParentEnabled()
4825     * @see #setId(int)
4826     * @see #onSaveInstanceState()
4827     */
4828    public void setSaveFromParentEnabled(boolean enabled) {
4829        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4830    }
4831
4832
4833    /**
4834     * Returns whether this View is able to take focus.
4835     *
4836     * @return True if this view can take focus, or false otherwise.
4837     * @attr ref android.R.styleable#View_focusable
4838     */
4839    @ViewDebug.ExportedProperty(category = "focus")
4840    public final boolean isFocusable() {
4841        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
4842    }
4843
4844    /**
4845     * When a view is focusable, it may not want to take focus when in touch mode.
4846     * For example, a button would like focus when the user is navigating via a D-pad
4847     * so that the user can click on it, but once the user starts touching the screen,
4848     * the button shouldn't take focus
4849     * @return Whether the view is focusable in touch mode.
4850     * @attr ref android.R.styleable#View_focusableInTouchMode
4851     */
4852    @ViewDebug.ExportedProperty
4853    public final boolean isFocusableInTouchMode() {
4854        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
4855    }
4856
4857    /**
4858     * Find the nearest view in the specified direction that can take focus.
4859     * This does not actually give focus to that view.
4860     *
4861     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
4862     *
4863     * @return The nearest focusable in the specified direction, or null if none
4864     *         can be found.
4865     */
4866    public View focusSearch(int direction) {
4867        if (mParent != null) {
4868            return mParent.focusSearch(this, direction);
4869        } else {
4870            return null;
4871        }
4872    }
4873
4874    /**
4875     * This method is the last chance for the focused view and its ancestors to
4876     * respond to an arrow key. This is called when the focused view did not
4877     * consume the key internally, nor could the view system find a new view in
4878     * the requested direction to give focus to.
4879     *
4880     * @param focused The currently focused view.
4881     * @param direction The direction focus wants to move. One of FOCUS_UP,
4882     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
4883     * @return True if the this view consumed this unhandled move.
4884     */
4885    public boolean dispatchUnhandledMove(View focused, int direction) {
4886        return false;
4887    }
4888
4889    /**
4890     * If a user manually specified the next view id for a particular direction,
4891     * use the root to look up the view.
4892     * @param root The root view of the hierarchy containing this view.
4893     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
4894     * or FOCUS_BACKWARD.
4895     * @return The user specified next view, or null if there is none.
4896     */
4897    View findUserSetNextFocus(View root, int direction) {
4898        switch (direction) {
4899            case FOCUS_LEFT:
4900                if (mNextFocusLeftId == View.NO_ID) return null;
4901                return findViewShouldExist(root, mNextFocusLeftId);
4902            case FOCUS_RIGHT:
4903                if (mNextFocusRightId == View.NO_ID) return null;
4904                return findViewShouldExist(root, mNextFocusRightId);
4905            case FOCUS_UP:
4906                if (mNextFocusUpId == View.NO_ID) return null;
4907                return findViewShouldExist(root, mNextFocusUpId);
4908            case FOCUS_DOWN:
4909                if (mNextFocusDownId == View.NO_ID) return null;
4910                return findViewShouldExist(root, mNextFocusDownId);
4911            case FOCUS_FORWARD:
4912                if (mNextFocusForwardId == View.NO_ID) return null;
4913                return findViewShouldExist(root, mNextFocusForwardId);
4914            case FOCUS_BACKWARD: {
4915                final int id = mID;
4916                return root.findViewByPredicate(new Predicate<View>() {
4917                    @Override
4918                    public boolean apply(View t) {
4919                        return t.mNextFocusForwardId == id;
4920                    }
4921                });
4922            }
4923        }
4924        return null;
4925    }
4926
4927    private static View findViewShouldExist(View root, int childViewId) {
4928        View result = root.findViewById(childViewId);
4929        if (result == null) {
4930            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
4931                    + "by user for id " + childViewId);
4932        }
4933        return result;
4934    }
4935
4936    /**
4937     * Find and return all focusable views that are descendants of this view,
4938     * possibly including this view if it is focusable itself.
4939     *
4940     * @param direction The direction of the focus
4941     * @return A list of focusable views
4942     */
4943    public ArrayList<View> getFocusables(int direction) {
4944        ArrayList<View> result = new ArrayList<View>(24);
4945        addFocusables(result, direction);
4946        return result;
4947    }
4948
4949    /**
4950     * Add any focusable views that are descendants of this view (possibly
4951     * including this view if it is focusable itself) to views.  If we are in touch mode,
4952     * only add views that are also focusable in touch mode.
4953     *
4954     * @param views Focusable views found so far
4955     * @param direction The direction of the focus
4956     */
4957    public void addFocusables(ArrayList<View> views, int direction) {
4958        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
4959    }
4960
4961    /**
4962     * Adds any focusable views that are descendants of this view (possibly
4963     * including this view if it is focusable itself) to views. This method
4964     * adds all focusable views regardless if we are in touch mode or
4965     * only views focusable in touch mode if we are in touch mode depending on
4966     * the focusable mode paramater.
4967     *
4968     * @param views Focusable views found so far or null if all we are interested is
4969     *        the number of focusables.
4970     * @param direction The direction of the focus.
4971     * @param focusableMode The type of focusables to be added.
4972     *
4973     * @see #FOCUSABLES_ALL
4974     * @see #FOCUSABLES_TOUCH_MODE
4975     */
4976    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
4977        if (!isFocusable()) {
4978            return;
4979        }
4980
4981        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
4982                isInTouchMode() && !isFocusableInTouchMode()) {
4983            return;
4984        }
4985
4986        if (views != null) {
4987            views.add(this);
4988        }
4989    }
4990
4991    /**
4992     * Finds the Views that contain given text. The containment is case insensitive.
4993     * As View's text is considered any text content that View renders.
4994     *
4995     * @param outViews The output list of matching Views.
4996     * @param text The text to match against.
4997     */
4998    public void findViewsWithText(ArrayList<View> outViews, CharSequence text) {
4999    }
5000
5001    /**
5002     * Find and return all touchable views that are descendants of this view,
5003     * possibly including this view if it is touchable itself.
5004     *
5005     * @return A list of touchable views
5006     */
5007    public ArrayList<View> getTouchables() {
5008        ArrayList<View> result = new ArrayList<View>();
5009        addTouchables(result);
5010        return result;
5011    }
5012
5013    /**
5014     * Add any touchable views that are descendants of this view (possibly
5015     * including this view if it is touchable itself) to views.
5016     *
5017     * @param views Touchable views found so far
5018     */
5019    public void addTouchables(ArrayList<View> views) {
5020        final int viewFlags = mViewFlags;
5021
5022        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5023                && (viewFlags & ENABLED_MASK) == ENABLED) {
5024            views.add(this);
5025        }
5026    }
5027
5028    /**
5029     * Call this to try to give focus to a specific view or to one of its
5030     * descendants.
5031     *
5032     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5033     * false), or if it is focusable and it is not focusable in touch mode
5034     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5035     *
5036     * See also {@link #focusSearch(int)}, which is what you call to say that you
5037     * have focus, and you want your parent to look for the next one.
5038     *
5039     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5040     * {@link #FOCUS_DOWN} and <code>null</code>.
5041     *
5042     * @return Whether this view or one of its descendants actually took focus.
5043     */
5044    public final boolean requestFocus() {
5045        return requestFocus(View.FOCUS_DOWN);
5046    }
5047
5048
5049    /**
5050     * Call this to try to give focus to a specific view or to one of its
5051     * descendants and give it a hint about what direction focus is heading.
5052     *
5053     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5054     * false), or if it is focusable and it is not focusable in touch mode
5055     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5056     *
5057     * See also {@link #focusSearch(int)}, which is what you call to say that you
5058     * have focus, and you want your parent to look for the next one.
5059     *
5060     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5061     * <code>null</code> set for the previously focused rectangle.
5062     *
5063     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5064     * @return Whether this view or one of its descendants actually took focus.
5065     */
5066    public final boolean requestFocus(int direction) {
5067        return requestFocus(direction, null);
5068    }
5069
5070    /**
5071     * Call this to try to give focus to a specific view or to one of its descendants
5072     * and give it hints about the direction and a specific rectangle that the focus
5073     * is coming from.  The rectangle can help give larger views a finer grained hint
5074     * about where focus is coming from, and therefore, where to show selection, or
5075     * forward focus change internally.
5076     *
5077     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5078     * false), or if it is focusable and it is not focusable in touch mode
5079     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5080     *
5081     * A View will not take focus if it is not visible.
5082     *
5083     * A View will not take focus if one of its parents has
5084     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5085     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5086     *
5087     * See also {@link #focusSearch(int)}, which is what you call to say that you
5088     * have focus, and you want your parent to look for the next one.
5089     *
5090     * You may wish to override this method if your custom {@link View} has an internal
5091     * {@link View} that it wishes to forward the request to.
5092     *
5093     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5094     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5095     *        to give a finer grained hint about where focus is coming from.  May be null
5096     *        if there is no hint.
5097     * @return Whether this view or one of its descendants actually took focus.
5098     */
5099    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5100        // need to be focusable
5101        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5102                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5103            return false;
5104        }
5105
5106        // need to be focusable in touch mode if in touch mode
5107        if (isInTouchMode() &&
5108            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5109               return false;
5110        }
5111
5112        // need to not have any parents blocking us
5113        if (hasAncestorThatBlocksDescendantFocus()) {
5114            return false;
5115        }
5116
5117        handleFocusGainInternal(direction, previouslyFocusedRect);
5118        return true;
5119    }
5120
5121    /** Gets the ViewAncestor, or null if not attached. */
5122    /*package*/ ViewRootImpl getViewRootImpl() {
5123        View root = getRootView();
5124        return root != null ? (ViewRootImpl)root.getParent() : null;
5125    }
5126
5127    /**
5128     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5129     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5130     * touch mode to request focus when they are touched.
5131     *
5132     * @return Whether this view or one of its descendants actually took focus.
5133     *
5134     * @see #isInTouchMode()
5135     *
5136     */
5137    public final boolean requestFocusFromTouch() {
5138        // Leave touch mode if we need to
5139        if (isInTouchMode()) {
5140            ViewRootImpl viewRoot = getViewRootImpl();
5141            if (viewRoot != null) {
5142                viewRoot.ensureTouchMode(false);
5143            }
5144        }
5145        return requestFocus(View.FOCUS_DOWN);
5146    }
5147
5148    /**
5149     * @return Whether any ancestor of this view blocks descendant focus.
5150     */
5151    private boolean hasAncestorThatBlocksDescendantFocus() {
5152        ViewParent ancestor = mParent;
5153        while (ancestor instanceof ViewGroup) {
5154            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5155            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5156                return true;
5157            } else {
5158                ancestor = vgAncestor.getParent();
5159            }
5160        }
5161        return false;
5162    }
5163
5164    /**
5165     * @hide
5166     */
5167    public void dispatchStartTemporaryDetach() {
5168        onStartTemporaryDetach();
5169    }
5170
5171    /**
5172     * This is called when a container is going to temporarily detach a child, with
5173     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5174     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5175     * {@link #onDetachedFromWindow()} when the container is done.
5176     */
5177    public void onStartTemporaryDetach() {
5178        removeUnsetPressCallback();
5179        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5180    }
5181
5182    /**
5183     * @hide
5184     */
5185    public void dispatchFinishTemporaryDetach() {
5186        onFinishTemporaryDetach();
5187    }
5188
5189    /**
5190     * Called after {@link #onStartTemporaryDetach} when the container is done
5191     * changing the view.
5192     */
5193    public void onFinishTemporaryDetach() {
5194    }
5195
5196    /**
5197     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5198     * for this view's window.  Returns null if the view is not currently attached
5199     * to the window.  Normally you will not need to use this directly, but
5200     * just use the standard high-level event callbacks like
5201     * {@link #onKeyDown(int, KeyEvent)}.
5202     */
5203    public KeyEvent.DispatcherState getKeyDispatcherState() {
5204        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5205    }
5206
5207    /**
5208     * Dispatch a key event before it is processed by any input method
5209     * associated with the view hierarchy.  This can be used to intercept
5210     * key events in special situations before the IME consumes them; a
5211     * typical example would be handling the BACK key to update the application's
5212     * UI instead of allowing the IME to see it and close itself.
5213     *
5214     * @param event The key event to be dispatched.
5215     * @return True if the event was handled, false otherwise.
5216     */
5217    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5218        return onKeyPreIme(event.getKeyCode(), event);
5219    }
5220
5221    /**
5222     * Dispatch a key event to the next view on the focus path. This path runs
5223     * from the top of the view tree down to the currently focused view. If this
5224     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5225     * the next node down the focus path. This method also fires any key
5226     * listeners.
5227     *
5228     * @param event The key event to be dispatched.
5229     * @return True if the event was handled, false otherwise.
5230     */
5231    public boolean dispatchKeyEvent(KeyEvent event) {
5232        if (mInputEventConsistencyVerifier != null) {
5233            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5234        }
5235
5236        // Give any attached key listener a first crack at the event.
5237        //noinspection SimplifiableIfStatement
5238        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5239                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5240            return true;
5241        }
5242
5243        if (event.dispatch(this, mAttachInfo != null
5244                ? mAttachInfo.mKeyDispatchState : null, this)) {
5245            return true;
5246        }
5247
5248        if (mInputEventConsistencyVerifier != null) {
5249            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5250        }
5251        return false;
5252    }
5253
5254    /**
5255     * Dispatches a key shortcut event.
5256     *
5257     * @param event The key event to be dispatched.
5258     * @return True if the event was handled by the view, false otherwise.
5259     */
5260    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5261        return onKeyShortcut(event.getKeyCode(), event);
5262    }
5263
5264    /**
5265     * Pass the touch screen motion event down to the target view, or this
5266     * view if it is the target.
5267     *
5268     * @param event The motion event to be dispatched.
5269     * @return True if the event was handled by the view, false otherwise.
5270     */
5271    public boolean dispatchTouchEvent(MotionEvent event) {
5272        if (mInputEventConsistencyVerifier != null) {
5273            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5274        }
5275
5276        if (onFilterTouchEventForSecurity(event)) {
5277            //noinspection SimplifiableIfStatement
5278            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
5279                    mOnTouchListener.onTouch(this, event)) {
5280                return true;
5281            }
5282
5283            if (onTouchEvent(event)) {
5284                return true;
5285            }
5286        }
5287
5288        if (mInputEventConsistencyVerifier != null) {
5289            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5290        }
5291        return false;
5292    }
5293
5294    /**
5295     * Filter the touch event to apply security policies.
5296     *
5297     * @param event The motion event to be filtered.
5298     * @return True if the event should be dispatched, false if the event should be dropped.
5299     *
5300     * @see #getFilterTouchesWhenObscured
5301     */
5302    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5303        //noinspection RedundantIfStatement
5304        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5305                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5306            // Window is obscured, drop this touch.
5307            return false;
5308        }
5309        return true;
5310    }
5311
5312    /**
5313     * Pass a trackball motion event down to the focused view.
5314     *
5315     * @param event The motion event to be dispatched.
5316     * @return True if the event was handled by the view, false otherwise.
5317     */
5318    public boolean dispatchTrackballEvent(MotionEvent event) {
5319        if (mInputEventConsistencyVerifier != null) {
5320            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5321        }
5322
5323        return onTrackballEvent(event);
5324    }
5325
5326    /**
5327     * Dispatch a generic motion event.
5328     * <p>
5329     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5330     * are delivered to the view under the pointer.  All other generic motion events are
5331     * delivered to the focused view.  Hover events are handled specially and are delivered
5332     * to {@link #onHoverEvent(MotionEvent)}.
5333     * </p>
5334     *
5335     * @param event The motion event to be dispatched.
5336     * @return True if the event was handled by the view, false otherwise.
5337     */
5338    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5339        if (mInputEventConsistencyVerifier != null) {
5340            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5341        }
5342
5343        final int source = event.getSource();
5344        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5345            final int action = event.getAction();
5346            if (action == MotionEvent.ACTION_HOVER_ENTER
5347                    || action == MotionEvent.ACTION_HOVER_MOVE
5348                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5349                if (dispatchHoverEvent(event)) {
5350                    // For compatibility with existing applications that handled HOVER_MOVE
5351                    // events in onGenericMotionEvent, dispatch the event there.  The
5352                    // onHoverEvent method did not exist at the time.
5353                    if (action == MotionEvent.ACTION_HOVER_MOVE) {
5354                        dispatchGenericMotionEventInternal(event);
5355                    }
5356                    return true;
5357                }
5358            } else if (dispatchGenericPointerEvent(event)) {
5359                return true;
5360            }
5361        } else if (dispatchGenericFocusedEvent(event)) {
5362            return true;
5363        }
5364
5365        if (dispatchGenericMotionEventInternal(event)) {
5366            return true;
5367        }
5368
5369        if (mInputEventConsistencyVerifier != null) {
5370            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5371        }
5372        return false;
5373    }
5374
5375    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5376        //noinspection SimplifiableIfStatement
5377        if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5378                && mOnGenericMotionListener.onGenericMotion(this, event)) {
5379            return true;
5380        }
5381
5382        if (onGenericMotionEvent(event)) {
5383            return true;
5384        }
5385
5386        if (mInputEventConsistencyVerifier != null) {
5387            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5388        }
5389        return false;
5390    }
5391
5392    /**
5393     * Dispatch a hover event.
5394     * <p>
5395     * Do not call this method directly.
5396     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5397     * </p>
5398     *
5399     * @param event The motion event to be dispatched.
5400     * @return True if the event was handled by the view, false otherwise.
5401     */
5402    protected boolean dispatchHoverEvent(MotionEvent event) {
5403        switch (event.getAction()) {
5404            case MotionEvent.ACTION_HOVER_ENTER:
5405                if (!hasHoveredChild() && !mSendingHoverAccessibilityEvents) {
5406                    mSendingHoverAccessibilityEvents = true;
5407                    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
5408                }
5409                break;
5410            case MotionEvent.ACTION_HOVER_EXIT:
5411                if (mSendingHoverAccessibilityEvents) {
5412                    mSendingHoverAccessibilityEvents = false;
5413                    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
5414                }
5415                break;
5416        }
5417
5418        //noinspection SimplifiableIfStatement
5419        if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5420                && mOnHoverListener.onHover(this, event)) {
5421            return true;
5422        }
5423
5424        return onHoverEvent(event);
5425    }
5426
5427    /**
5428     * Returns true if the view has a child to which it has recently sent
5429     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5430     * it does not have a hovered child, then it must be the innermost hovered view.
5431     * @hide
5432     */
5433    protected boolean hasHoveredChild() {
5434        return false;
5435    }
5436
5437    /**
5438     * Dispatch a generic motion event to the view under the first pointer.
5439     * <p>
5440     * Do not call this method directly.
5441     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5442     * </p>
5443     *
5444     * @param event The motion event to be dispatched.
5445     * @return True if the event was handled by the view, false otherwise.
5446     */
5447    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5448        return false;
5449    }
5450
5451    /**
5452     * Dispatch a generic motion event to the currently focused view.
5453     * <p>
5454     * Do not call this method directly.
5455     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5456     * </p>
5457     *
5458     * @param event The motion event to be dispatched.
5459     * @return True if the event was handled by the view, false otherwise.
5460     */
5461    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5462        return false;
5463    }
5464
5465    /**
5466     * Dispatch a pointer event.
5467     * <p>
5468     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5469     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5470     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5471     * and should not be expected to handle other pointing device features.
5472     * </p>
5473     *
5474     * @param event The motion event to be dispatched.
5475     * @return True if the event was handled by the view, false otherwise.
5476     * @hide
5477     */
5478    public final boolean dispatchPointerEvent(MotionEvent event) {
5479        if (event.isTouchEvent()) {
5480            return dispatchTouchEvent(event);
5481        } else {
5482            return dispatchGenericMotionEvent(event);
5483        }
5484    }
5485
5486    /**
5487     * Called when the window containing this view gains or loses window focus.
5488     * ViewGroups should override to route to their children.
5489     *
5490     * @param hasFocus True if the window containing this view now has focus,
5491     *        false otherwise.
5492     */
5493    public void dispatchWindowFocusChanged(boolean hasFocus) {
5494        onWindowFocusChanged(hasFocus);
5495    }
5496
5497    /**
5498     * Called when the window containing this view gains or loses focus.  Note
5499     * that this is separate from view focus: to receive key events, both
5500     * your view and its window must have focus.  If a window is displayed
5501     * on top of yours that takes input focus, then your own window will lose
5502     * focus but the view focus will remain unchanged.
5503     *
5504     * @param hasWindowFocus True if the window containing this view now has
5505     *        focus, false otherwise.
5506     */
5507    public void onWindowFocusChanged(boolean hasWindowFocus) {
5508        InputMethodManager imm = InputMethodManager.peekInstance();
5509        if (!hasWindowFocus) {
5510            if (isPressed()) {
5511                setPressed(false);
5512            }
5513            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5514                imm.focusOut(this);
5515            }
5516            removeLongPressCallback();
5517            removeTapCallback();
5518            onFocusLost();
5519        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5520            imm.focusIn(this);
5521        }
5522        refreshDrawableState();
5523    }
5524
5525    /**
5526     * Returns true if this view is in a window that currently has window focus.
5527     * Note that this is not the same as the view itself having focus.
5528     *
5529     * @return True if this view is in a window that currently has window focus.
5530     */
5531    public boolean hasWindowFocus() {
5532        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5533    }
5534
5535    /**
5536     * Dispatch a view visibility change down the view hierarchy.
5537     * ViewGroups should override to route to their children.
5538     * @param changedView The view whose visibility changed. Could be 'this' or
5539     * an ancestor view.
5540     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5541     * {@link #INVISIBLE} or {@link #GONE}.
5542     */
5543    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5544        onVisibilityChanged(changedView, visibility);
5545    }
5546
5547    /**
5548     * Called when the visibility of the view or an ancestor of the view is changed.
5549     * @param changedView The view whose visibility changed. Could be 'this' or
5550     * an ancestor view.
5551     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5552     * {@link #INVISIBLE} or {@link #GONE}.
5553     */
5554    protected void onVisibilityChanged(View changedView, int visibility) {
5555        if (visibility == VISIBLE) {
5556            if (mAttachInfo != null) {
5557                initialAwakenScrollBars();
5558            } else {
5559                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5560            }
5561        }
5562    }
5563
5564    /**
5565     * Dispatch a hint about whether this view is displayed. For instance, when
5566     * a View moves out of the screen, it might receives a display hint indicating
5567     * the view is not displayed. Applications should not <em>rely</em> on this hint
5568     * as there is no guarantee that they will receive one.
5569     *
5570     * @param hint A hint about whether or not this view is displayed:
5571     * {@link #VISIBLE} or {@link #INVISIBLE}.
5572     */
5573    public void dispatchDisplayHint(int hint) {
5574        onDisplayHint(hint);
5575    }
5576
5577    /**
5578     * Gives this view a hint about whether is displayed or not. For instance, when
5579     * a View moves out of the screen, it might receives a display hint indicating
5580     * the view is not displayed. Applications should not <em>rely</em> on this hint
5581     * as there is no guarantee that they will receive one.
5582     *
5583     * @param hint A hint about whether or not this view is displayed:
5584     * {@link #VISIBLE} or {@link #INVISIBLE}.
5585     */
5586    protected void onDisplayHint(int hint) {
5587    }
5588
5589    /**
5590     * Dispatch a window visibility change down the view hierarchy.
5591     * ViewGroups should override to route to their children.
5592     *
5593     * @param visibility The new visibility of the window.
5594     *
5595     * @see #onWindowVisibilityChanged(int)
5596     */
5597    public void dispatchWindowVisibilityChanged(int visibility) {
5598        onWindowVisibilityChanged(visibility);
5599    }
5600
5601    /**
5602     * Called when the window containing has change its visibility
5603     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5604     * that this tells you whether or not your window is being made visible
5605     * to the window manager; this does <em>not</em> tell you whether or not
5606     * your window is obscured by other windows on the screen, even if it
5607     * is itself visible.
5608     *
5609     * @param visibility The new visibility of the window.
5610     */
5611    protected void onWindowVisibilityChanged(int visibility) {
5612        if (visibility == VISIBLE) {
5613            initialAwakenScrollBars();
5614        }
5615    }
5616
5617    /**
5618     * Returns the current visibility of the window this view is attached to
5619     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5620     *
5621     * @return Returns the current visibility of the view's window.
5622     */
5623    public int getWindowVisibility() {
5624        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5625    }
5626
5627    /**
5628     * Retrieve the overall visible display size in which the window this view is
5629     * attached to has been positioned in.  This takes into account screen
5630     * decorations above the window, for both cases where the window itself
5631     * is being position inside of them or the window is being placed under
5632     * then and covered insets are used for the window to position its content
5633     * inside.  In effect, this tells you the available area where content can
5634     * be placed and remain visible to users.
5635     *
5636     * <p>This function requires an IPC back to the window manager to retrieve
5637     * the requested information, so should not be used in performance critical
5638     * code like drawing.
5639     *
5640     * @param outRect Filled in with the visible display frame.  If the view
5641     * is not attached to a window, this is simply the raw display size.
5642     */
5643    public void getWindowVisibleDisplayFrame(Rect outRect) {
5644        if (mAttachInfo != null) {
5645            try {
5646                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5647            } catch (RemoteException e) {
5648                return;
5649            }
5650            // XXX This is really broken, and probably all needs to be done
5651            // in the window manager, and we need to know more about whether
5652            // we want the area behind or in front of the IME.
5653            final Rect insets = mAttachInfo.mVisibleInsets;
5654            outRect.left += insets.left;
5655            outRect.top += insets.top;
5656            outRect.right -= insets.right;
5657            outRect.bottom -= insets.bottom;
5658            return;
5659        }
5660        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5661        d.getRectSize(outRect);
5662    }
5663
5664    /**
5665     * Dispatch a notification about a resource configuration change down
5666     * the view hierarchy.
5667     * ViewGroups should override to route to their children.
5668     *
5669     * @param newConfig The new resource configuration.
5670     *
5671     * @see #onConfigurationChanged(android.content.res.Configuration)
5672     */
5673    public void dispatchConfigurationChanged(Configuration newConfig) {
5674        onConfigurationChanged(newConfig);
5675    }
5676
5677    /**
5678     * Called when the current configuration of the resources being used
5679     * by the application have changed.  You can use this to decide when
5680     * to reload resources that can changed based on orientation and other
5681     * configuration characterstics.  You only need to use this if you are
5682     * not relying on the normal {@link android.app.Activity} mechanism of
5683     * recreating the activity instance upon a configuration change.
5684     *
5685     * @param newConfig The new resource configuration.
5686     */
5687    protected void onConfigurationChanged(Configuration newConfig) {
5688    }
5689
5690    /**
5691     * Private function to aggregate all per-view attributes in to the view
5692     * root.
5693     */
5694    void dispatchCollectViewAttributes(int visibility) {
5695        performCollectViewAttributes(visibility);
5696    }
5697
5698    void performCollectViewAttributes(int visibility) {
5699        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
5700            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
5701                mAttachInfo.mKeepScreenOn = true;
5702            }
5703            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
5704            if (mOnSystemUiVisibilityChangeListener != null) {
5705                mAttachInfo.mHasSystemUiListeners = true;
5706            }
5707        }
5708    }
5709
5710    void needGlobalAttributesUpdate(boolean force) {
5711        final AttachInfo ai = mAttachInfo;
5712        if (ai != null) {
5713            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
5714                    || ai.mHasSystemUiListeners) {
5715                ai.mRecomputeGlobalAttributes = true;
5716            }
5717        }
5718    }
5719
5720    /**
5721     * Returns whether the device is currently in touch mode.  Touch mode is entered
5722     * once the user begins interacting with the device by touch, and affects various
5723     * things like whether focus is always visible to the user.
5724     *
5725     * @return Whether the device is in touch mode.
5726     */
5727    @ViewDebug.ExportedProperty
5728    public boolean isInTouchMode() {
5729        if (mAttachInfo != null) {
5730            return mAttachInfo.mInTouchMode;
5731        } else {
5732            return ViewRootImpl.isInTouchMode();
5733        }
5734    }
5735
5736    /**
5737     * Returns the context the view is running in, through which it can
5738     * access the current theme, resources, etc.
5739     *
5740     * @return The view's Context.
5741     */
5742    @ViewDebug.CapturedViewProperty
5743    public final Context getContext() {
5744        return mContext;
5745    }
5746
5747    /**
5748     * Handle a key event before it is processed by any input method
5749     * associated with the view hierarchy.  This can be used to intercept
5750     * key events in special situations before the IME consumes them; a
5751     * typical example would be handling the BACK key to update the application's
5752     * UI instead of allowing the IME to see it and close itself.
5753     *
5754     * @param keyCode The value in event.getKeyCode().
5755     * @param event Description of the key event.
5756     * @return If you handled the event, return true. If you want to allow the
5757     *         event to be handled by the next receiver, return false.
5758     */
5759    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5760        return false;
5761    }
5762
5763    /**
5764     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
5765     * KeyEvent.Callback.onKeyDown()}: perform press of the view
5766     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
5767     * is released, if the view is enabled and clickable.
5768     *
5769     * @param keyCode A key code that represents the button pressed, from
5770     *                {@link android.view.KeyEvent}.
5771     * @param event   The KeyEvent object that defines the button action.
5772     */
5773    public boolean onKeyDown(int keyCode, KeyEvent event) {
5774        boolean result = false;
5775
5776        switch (keyCode) {
5777            case KeyEvent.KEYCODE_DPAD_CENTER:
5778            case KeyEvent.KEYCODE_ENTER: {
5779                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5780                    return true;
5781                }
5782                // Long clickable items don't necessarily have to be clickable
5783                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
5784                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
5785                        (event.getRepeatCount() == 0)) {
5786                    setPressed(true);
5787                    checkForLongClick(0);
5788                    return true;
5789                }
5790                break;
5791            }
5792        }
5793        return result;
5794    }
5795
5796    /**
5797     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
5798     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
5799     * the event).
5800     */
5801    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
5802        return false;
5803    }
5804
5805    /**
5806     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
5807     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
5808     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
5809     * {@link KeyEvent#KEYCODE_ENTER} is released.
5810     *
5811     * @param keyCode A key code that represents the button pressed, from
5812     *                {@link android.view.KeyEvent}.
5813     * @param event   The KeyEvent object that defines the button action.
5814     */
5815    public boolean onKeyUp(int keyCode, KeyEvent event) {
5816        boolean result = false;
5817
5818        switch (keyCode) {
5819            case KeyEvent.KEYCODE_DPAD_CENTER:
5820            case KeyEvent.KEYCODE_ENTER: {
5821                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5822                    return true;
5823                }
5824                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
5825                    setPressed(false);
5826
5827                    if (!mHasPerformedLongPress) {
5828                        // This is a tap, so remove the longpress check
5829                        removeLongPressCallback();
5830
5831                        result = performClick();
5832                    }
5833                }
5834                break;
5835            }
5836        }
5837        return result;
5838    }
5839
5840    /**
5841     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
5842     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
5843     * the event).
5844     *
5845     * @param keyCode     A key code that represents the button pressed, from
5846     *                    {@link android.view.KeyEvent}.
5847     * @param repeatCount The number of times the action was made.
5848     * @param event       The KeyEvent object that defines the button action.
5849     */
5850    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
5851        return false;
5852    }
5853
5854    /**
5855     * Called on the focused view when a key shortcut event is not handled.
5856     * Override this method to implement local key shortcuts for the View.
5857     * Key shortcuts can also be implemented by setting the
5858     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
5859     *
5860     * @param keyCode The value in event.getKeyCode().
5861     * @param event Description of the key event.
5862     * @return If you handled the event, return true. If you want to allow the
5863     *         event to be handled by the next receiver, return false.
5864     */
5865    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
5866        return false;
5867    }
5868
5869    /**
5870     * Check whether the called view is a text editor, in which case it
5871     * would make sense to automatically display a soft input window for
5872     * it.  Subclasses should override this if they implement
5873     * {@link #onCreateInputConnection(EditorInfo)} to return true if
5874     * a call on that method would return a non-null InputConnection, and
5875     * they are really a first-class editor that the user would normally
5876     * start typing on when the go into a window containing your view.
5877     *
5878     * <p>The default implementation always returns false.  This does
5879     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
5880     * will not be called or the user can not otherwise perform edits on your
5881     * view; it is just a hint to the system that this is not the primary
5882     * purpose of this view.
5883     *
5884     * @return Returns true if this view is a text editor, else false.
5885     */
5886    public boolean onCheckIsTextEditor() {
5887        return false;
5888    }
5889
5890    /**
5891     * Create a new InputConnection for an InputMethod to interact
5892     * with the view.  The default implementation returns null, since it doesn't
5893     * support input methods.  You can override this to implement such support.
5894     * This is only needed for views that take focus and text input.
5895     *
5896     * <p>When implementing this, you probably also want to implement
5897     * {@link #onCheckIsTextEditor()} to indicate you will return a
5898     * non-null InputConnection.
5899     *
5900     * @param outAttrs Fill in with attribute information about the connection.
5901     */
5902    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
5903        return null;
5904    }
5905
5906    /**
5907     * Called by the {@link android.view.inputmethod.InputMethodManager}
5908     * when a view who is not the current
5909     * input connection target is trying to make a call on the manager.  The
5910     * default implementation returns false; you can override this to return
5911     * true for certain views if you are performing InputConnection proxying
5912     * to them.
5913     * @param view The View that is making the InputMethodManager call.
5914     * @return Return true to allow the call, false to reject.
5915     */
5916    public boolean checkInputConnectionProxy(View view) {
5917        return false;
5918    }
5919
5920    /**
5921     * Show the context menu for this view. It is not safe to hold on to the
5922     * menu after returning from this method.
5923     *
5924     * You should normally not overload this method. Overload
5925     * {@link #onCreateContextMenu(ContextMenu)} or define an
5926     * {@link OnCreateContextMenuListener} to add items to the context menu.
5927     *
5928     * @param menu The context menu to populate
5929     */
5930    public void createContextMenu(ContextMenu menu) {
5931        ContextMenuInfo menuInfo = getContextMenuInfo();
5932
5933        // Sets the current menu info so all items added to menu will have
5934        // my extra info set.
5935        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
5936
5937        onCreateContextMenu(menu);
5938        if (mOnCreateContextMenuListener != null) {
5939            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
5940        }
5941
5942        // Clear the extra information so subsequent items that aren't mine don't
5943        // have my extra info.
5944        ((MenuBuilder)menu).setCurrentMenuInfo(null);
5945
5946        if (mParent != null) {
5947            mParent.createContextMenu(menu);
5948        }
5949    }
5950
5951    /**
5952     * Views should implement this if they have extra information to associate
5953     * with the context menu. The return result is supplied as a parameter to
5954     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
5955     * callback.
5956     *
5957     * @return Extra information about the item for which the context menu
5958     *         should be shown. This information will vary across different
5959     *         subclasses of View.
5960     */
5961    protected ContextMenuInfo getContextMenuInfo() {
5962        return null;
5963    }
5964
5965    /**
5966     * Views should implement this if the view itself is going to add items to
5967     * the context menu.
5968     *
5969     * @param menu the context menu to populate
5970     */
5971    protected void onCreateContextMenu(ContextMenu menu) {
5972    }
5973
5974    /**
5975     * Implement this method to handle trackball motion events.  The
5976     * <em>relative</em> movement of the trackball since the last event
5977     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
5978     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
5979     * that a movement of 1 corresponds to the user pressing one DPAD key (so
5980     * they will often be fractional values, representing the more fine-grained
5981     * movement information available from a trackball).
5982     *
5983     * @param event The motion event.
5984     * @return True if the event was handled, false otherwise.
5985     */
5986    public boolean onTrackballEvent(MotionEvent event) {
5987        return false;
5988    }
5989
5990    /**
5991     * Implement this method to handle generic motion events.
5992     * <p>
5993     * Generic motion events describe joystick movements, mouse hovers, track pad
5994     * touches, scroll wheel movements and other input events.  The
5995     * {@link MotionEvent#getSource() source} of the motion event specifies
5996     * the class of input that was received.  Implementations of this method
5997     * must examine the bits in the source before processing the event.
5998     * The following code example shows how this is done.
5999     * </p><p>
6000     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6001     * are delivered to the view under the pointer.  All other generic motion events are
6002     * delivered to the focused view.
6003     * </p>
6004     * <code>
6005     * public boolean onGenericMotionEvent(MotionEvent event) {
6006     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6007     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6008     *             // process the joystick movement...
6009     *             return true;
6010     *         }
6011     *     }
6012     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6013     *         switch (event.getAction()) {
6014     *             case MotionEvent.ACTION_HOVER_MOVE:
6015     *                 // process the mouse hover movement...
6016     *                 return true;
6017     *             case MotionEvent.ACTION_SCROLL:
6018     *                 // process the scroll wheel movement...
6019     *                 return true;
6020     *         }
6021     *     }
6022     *     return super.onGenericMotionEvent(event);
6023     * }
6024     * </code>
6025     *
6026     * @param event The generic motion event being processed.
6027     * @return True if the event was handled, false otherwise.
6028     */
6029    public boolean onGenericMotionEvent(MotionEvent event) {
6030        return false;
6031    }
6032
6033    /**
6034     * Implement this method to handle hover events.
6035     * <p>
6036     * This method is called whenever a pointer is hovering into, over, or out of the
6037     * bounds of a view and the view is not currently being touched.
6038     * Hover events are represented as pointer events with action
6039     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6040     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6041     * </p>
6042     * <ul>
6043     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6044     * when the pointer enters the bounds of the view.</li>
6045     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6046     * when the pointer has already entered the bounds of the view and has moved.</li>
6047     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6048     * when the pointer has exited the bounds of the view or when the pointer is
6049     * about to go down due to a button click, tap, or similar user action that
6050     * causes the view to be touched.</li>
6051     * </ul>
6052     * <p>
6053     * The view should implement this method to return true to indicate that it is
6054     * handling the hover event, such as by changing its drawable state.
6055     * </p><p>
6056     * The default implementation calls {@link #setHovered} to update the hovered state
6057     * of the view when a hover enter or hover exit event is received, if the view
6058     * is enabled and is clickable.
6059     * </p>
6060     *
6061     * @param event The motion event that describes the hover.
6062     * @return True if the view handled the hover event.
6063     *
6064     * @see #isHovered
6065     * @see #setHovered
6066     * @see #onHoverChanged
6067     */
6068    public boolean onHoverEvent(MotionEvent event) {
6069        if (isHoverable()) {
6070            switch (event.getAction()) {
6071                case MotionEvent.ACTION_HOVER_ENTER:
6072                    setHovered(true);
6073                    break;
6074                case MotionEvent.ACTION_HOVER_EXIT:
6075                    setHovered(false);
6076                    break;
6077            }
6078            return true;
6079        }
6080        return false;
6081    }
6082
6083    /**
6084     * Returns true if the view should handle {@link #onHoverEvent}
6085     * by calling {@link #setHovered} to change its hovered state.
6086     *
6087     * @return True if the view is hoverable.
6088     */
6089    private boolean isHoverable() {
6090        final int viewFlags = mViewFlags;
6091        //noinspection SimplifiableIfStatement
6092        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6093            return false;
6094        }
6095
6096        return (viewFlags & CLICKABLE) == CLICKABLE
6097                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6098    }
6099
6100    /**
6101     * Returns true if the view is currently hovered.
6102     *
6103     * @return True if the view is currently hovered.
6104     *
6105     * @see #setHovered
6106     * @see #onHoverChanged
6107     */
6108    @ViewDebug.ExportedProperty
6109    public boolean isHovered() {
6110        return (mPrivateFlags & HOVERED) != 0;
6111    }
6112
6113    /**
6114     * Sets whether the view is currently hovered.
6115     * <p>
6116     * Calling this method also changes the drawable state of the view.  This
6117     * enables the view to react to hover by using different drawable resources
6118     * to change its appearance.
6119     * </p><p>
6120     * The {@link #onHoverChanged} method is called when the hovered state changes.
6121     * </p>
6122     *
6123     * @param hovered True if the view is hovered.
6124     *
6125     * @see #isHovered
6126     * @see #onHoverChanged
6127     */
6128    public void setHovered(boolean hovered) {
6129        if (hovered) {
6130            if ((mPrivateFlags & HOVERED) == 0) {
6131                mPrivateFlags |= HOVERED;
6132                refreshDrawableState();
6133                onHoverChanged(true);
6134            }
6135        } else {
6136            if ((mPrivateFlags & HOVERED) != 0) {
6137                mPrivateFlags &= ~HOVERED;
6138                refreshDrawableState();
6139                onHoverChanged(false);
6140            }
6141        }
6142    }
6143
6144    /**
6145     * Implement this method to handle hover state changes.
6146     * <p>
6147     * This method is called whenever the hover state changes as a result of a
6148     * call to {@link #setHovered}.
6149     * </p>
6150     *
6151     * @param hovered The current hover state, as returned by {@link #isHovered}.
6152     *
6153     * @see #isHovered
6154     * @see #setHovered
6155     */
6156    public void onHoverChanged(boolean hovered) {
6157    }
6158
6159    /**
6160     * Implement this method to handle touch screen motion events.
6161     *
6162     * @param event The motion event.
6163     * @return True if the event was handled, false otherwise.
6164     */
6165    public boolean onTouchEvent(MotionEvent event) {
6166        final int viewFlags = mViewFlags;
6167
6168        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6169            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6170                mPrivateFlags &= ~PRESSED;
6171                refreshDrawableState();
6172            }
6173            // A disabled view that is clickable still consumes the touch
6174            // events, it just doesn't respond to them.
6175            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6176                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6177        }
6178
6179        if (mTouchDelegate != null) {
6180            if (mTouchDelegate.onTouchEvent(event)) {
6181                return true;
6182            }
6183        }
6184
6185        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6186                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6187            switch (event.getAction()) {
6188                case MotionEvent.ACTION_UP:
6189                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6190                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6191                        // take focus if we don't have it already and we should in
6192                        // touch mode.
6193                        boolean focusTaken = false;
6194                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6195                            focusTaken = requestFocus();
6196                        }
6197
6198                        if (prepressed) {
6199                            // The button is being released before we actually
6200                            // showed it as pressed.  Make it show the pressed
6201                            // state now (before scheduling the click) to ensure
6202                            // the user sees it.
6203                            mPrivateFlags |= PRESSED;
6204                            refreshDrawableState();
6205                       }
6206
6207                        if (!mHasPerformedLongPress) {
6208                            // This is a tap, so remove the longpress check
6209                            removeLongPressCallback();
6210
6211                            // Only perform take click actions if we were in the pressed state
6212                            if (!focusTaken) {
6213                                // Use a Runnable and post this rather than calling
6214                                // performClick directly. This lets other visual state
6215                                // of the view update before click actions start.
6216                                if (mPerformClick == null) {
6217                                    mPerformClick = new PerformClick();
6218                                }
6219                                if (!post(mPerformClick)) {
6220                                    performClick();
6221                                }
6222                            }
6223                        }
6224
6225                        if (mUnsetPressedState == null) {
6226                            mUnsetPressedState = new UnsetPressedState();
6227                        }
6228
6229                        if (prepressed) {
6230                            postDelayed(mUnsetPressedState,
6231                                    ViewConfiguration.getPressedStateDuration());
6232                        } else if (!post(mUnsetPressedState)) {
6233                            // If the post failed, unpress right now
6234                            mUnsetPressedState.run();
6235                        }
6236                        removeTapCallback();
6237                    }
6238                    break;
6239
6240                case MotionEvent.ACTION_DOWN:
6241                    mHasPerformedLongPress = false;
6242
6243                    if (performButtonActionOnTouchDown(event)) {
6244                        break;
6245                    }
6246
6247                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6248                    boolean isInScrollingContainer = false;
6249                    ViewParent p = getParent();
6250                    while (p != null && p instanceof ViewGroup) {
6251                        if (((ViewGroup) p).shouldDelayChildPressedState()) {
6252                            isInScrollingContainer = true;
6253                            break;
6254                        }
6255                        p = p.getParent();
6256                    }
6257
6258                    // For views inside a scrolling container, delay the pressed feedback for
6259                    // a short period in case this is a scroll.
6260                    if (isInScrollingContainer) {
6261                        mPrivateFlags |= PREPRESSED;
6262                        if (mPendingCheckForTap == null) {
6263                            mPendingCheckForTap = new CheckForTap();
6264                        }
6265                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6266                    } else {
6267                        // Not inside a scrolling container, so show the feedback right away
6268                        mPrivateFlags |= PRESSED;
6269                        refreshDrawableState();
6270                        checkForLongClick(0);
6271                    }
6272                    break;
6273
6274                case MotionEvent.ACTION_CANCEL:
6275                    mPrivateFlags &= ~PRESSED;
6276                    refreshDrawableState();
6277                    removeTapCallback();
6278                    break;
6279
6280                case MotionEvent.ACTION_MOVE:
6281                    final int x = (int) event.getX();
6282                    final int y = (int) event.getY();
6283
6284                    // Be lenient about moving outside of buttons
6285                    if (!pointInView(x, y, mTouchSlop)) {
6286                        // Outside button
6287                        removeTapCallback();
6288                        if ((mPrivateFlags & PRESSED) != 0) {
6289                            // Remove any future long press/tap checks
6290                            removeLongPressCallback();
6291
6292                            // Need to switch from pressed to not pressed
6293                            mPrivateFlags &= ~PRESSED;
6294                            refreshDrawableState();
6295                        }
6296                    }
6297                    break;
6298            }
6299            return true;
6300        }
6301
6302        return false;
6303    }
6304
6305    /**
6306     * Remove the longpress detection timer.
6307     */
6308    private void removeLongPressCallback() {
6309        if (mPendingCheckForLongPress != null) {
6310          removeCallbacks(mPendingCheckForLongPress);
6311        }
6312    }
6313
6314    /**
6315     * Remove the pending click action
6316     */
6317    private void removePerformClickCallback() {
6318        if (mPerformClick != null) {
6319            removeCallbacks(mPerformClick);
6320        }
6321    }
6322
6323    /**
6324     * Remove the prepress detection timer.
6325     */
6326    private void removeUnsetPressCallback() {
6327        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6328            setPressed(false);
6329            removeCallbacks(mUnsetPressedState);
6330        }
6331    }
6332
6333    /**
6334     * Remove the tap detection timer.
6335     */
6336    private void removeTapCallback() {
6337        if (mPendingCheckForTap != null) {
6338            mPrivateFlags &= ~PREPRESSED;
6339            removeCallbacks(mPendingCheckForTap);
6340        }
6341    }
6342
6343    /**
6344     * Cancels a pending long press.  Your subclass can use this if you
6345     * want the context menu to come up if the user presses and holds
6346     * at the same place, but you don't want it to come up if they press
6347     * and then move around enough to cause scrolling.
6348     */
6349    public void cancelLongPress() {
6350        removeLongPressCallback();
6351
6352        /*
6353         * The prepressed state handled by the tap callback is a display
6354         * construct, but the tap callback will post a long press callback
6355         * less its own timeout. Remove it here.
6356         */
6357        removeTapCallback();
6358    }
6359
6360    /**
6361     * Remove the pending callback for sending a
6362     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6363     */
6364    private void removeSendViewScrolledAccessibilityEventCallback() {
6365        if (mSendViewScrolledAccessibilityEvent != null) {
6366            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6367        }
6368    }
6369
6370    /**
6371     * Sets the TouchDelegate for this View.
6372     */
6373    public void setTouchDelegate(TouchDelegate delegate) {
6374        mTouchDelegate = delegate;
6375    }
6376
6377    /**
6378     * Gets the TouchDelegate for this View.
6379     */
6380    public TouchDelegate getTouchDelegate() {
6381        return mTouchDelegate;
6382    }
6383
6384    /**
6385     * Set flags controlling behavior of this view.
6386     *
6387     * @param flags Constant indicating the value which should be set
6388     * @param mask Constant indicating the bit range that should be changed
6389     */
6390    void setFlags(int flags, int mask) {
6391        int old = mViewFlags;
6392        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6393
6394        int changed = mViewFlags ^ old;
6395        if (changed == 0) {
6396            return;
6397        }
6398        int privateFlags = mPrivateFlags;
6399
6400        /* Check if the FOCUSABLE bit has changed */
6401        if (((changed & FOCUSABLE_MASK) != 0) &&
6402                ((privateFlags & HAS_BOUNDS) !=0)) {
6403            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6404                    && ((privateFlags & FOCUSED) != 0)) {
6405                /* Give up focus if we are no longer focusable */
6406                clearFocus();
6407            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6408                    && ((privateFlags & FOCUSED) == 0)) {
6409                /*
6410                 * Tell the view system that we are now available to take focus
6411                 * if no one else already has it.
6412                 */
6413                if (mParent != null) mParent.focusableViewAvailable(this);
6414            }
6415        }
6416
6417        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6418            if ((changed & VISIBILITY_MASK) != 0) {
6419                /*
6420                 * If this view is becoming visible, set the DRAWN flag so that
6421                 * the next invalidate() will not be skipped.
6422                 */
6423                mPrivateFlags |= DRAWN;
6424
6425                needGlobalAttributesUpdate(true);
6426
6427                // a view becoming visible is worth notifying the parent
6428                // about in case nothing has focus.  even if this specific view
6429                // isn't focusable, it may contain something that is, so let
6430                // the root view try to give this focus if nothing else does.
6431                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6432                    mParent.focusableViewAvailable(this);
6433                }
6434            }
6435        }
6436
6437        /* Check if the GONE bit has changed */
6438        if ((changed & GONE) != 0) {
6439            needGlobalAttributesUpdate(false);
6440            requestLayout();
6441            invalidate(true);
6442
6443            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6444                if (hasFocus()) clearFocus();
6445                destroyDrawingCache();
6446            }
6447            if (mAttachInfo != null) {
6448                mAttachInfo.mViewVisibilityChanged = true;
6449            }
6450        }
6451
6452        /* Check if the VISIBLE bit has changed */
6453        if ((changed & INVISIBLE) != 0) {
6454            needGlobalAttributesUpdate(false);
6455            /*
6456             * If this view is becoming invisible, set the DRAWN flag so that
6457             * the next invalidate() will not be skipped.
6458             */
6459            mPrivateFlags |= DRAWN;
6460
6461            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6462                // root view becoming invisible shouldn't clear focus
6463                if (getRootView() != this) {
6464                    clearFocus();
6465                }
6466            }
6467            if (mAttachInfo != null) {
6468                mAttachInfo.mViewVisibilityChanged = true;
6469            }
6470        }
6471
6472        if ((changed & VISIBILITY_MASK) != 0) {
6473            if (mParent instanceof ViewGroup) {
6474                ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
6475                ((View) mParent).invalidate(true);
6476            }
6477            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6478        }
6479
6480        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6481            destroyDrawingCache();
6482        }
6483
6484        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6485            destroyDrawingCache();
6486            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6487            invalidateParentCaches();
6488        }
6489
6490        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6491            destroyDrawingCache();
6492            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6493        }
6494
6495        if ((changed & DRAW_MASK) != 0) {
6496            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6497                if (mBGDrawable != null) {
6498                    mPrivateFlags &= ~SKIP_DRAW;
6499                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6500                } else {
6501                    mPrivateFlags |= SKIP_DRAW;
6502                }
6503            } else {
6504                mPrivateFlags &= ~SKIP_DRAW;
6505            }
6506            requestLayout();
6507            invalidate(true);
6508        }
6509
6510        if ((changed & KEEP_SCREEN_ON) != 0) {
6511            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6512                mParent.recomputeViewAttributes(this);
6513            }
6514        }
6515
6516        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6517            requestLayout();
6518        }
6519    }
6520
6521    /**
6522     * Change the view's z order in the tree, so it's on top of other sibling
6523     * views
6524     */
6525    public void bringToFront() {
6526        if (mParent != null) {
6527            mParent.bringChildToFront(this);
6528        }
6529    }
6530
6531    /**
6532     * This is called in response to an internal scroll in this view (i.e., the
6533     * view scrolled its own contents). This is typically as a result of
6534     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6535     * called.
6536     *
6537     * @param l Current horizontal scroll origin.
6538     * @param t Current vertical scroll origin.
6539     * @param oldl Previous horizontal scroll origin.
6540     * @param oldt Previous vertical scroll origin.
6541     */
6542    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6543        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6544            postSendViewScrolledAccessibilityEventCallback();
6545        }
6546
6547        mBackgroundSizeChanged = true;
6548
6549        final AttachInfo ai = mAttachInfo;
6550        if (ai != null) {
6551            ai.mViewScrollChanged = true;
6552        }
6553    }
6554
6555    /**
6556     * Interface definition for a callback to be invoked when the layout bounds of a view
6557     * changes due to layout processing.
6558     */
6559    public interface OnLayoutChangeListener {
6560        /**
6561         * Called when the focus state of a view has changed.
6562         *
6563         * @param v The view whose state has changed.
6564         * @param left The new value of the view's left property.
6565         * @param top The new value of the view's top property.
6566         * @param right The new value of the view's right property.
6567         * @param bottom The new value of the view's bottom property.
6568         * @param oldLeft The previous value of the view's left property.
6569         * @param oldTop The previous value of the view's top property.
6570         * @param oldRight The previous value of the view's right property.
6571         * @param oldBottom The previous value of the view's bottom property.
6572         */
6573        void onLayoutChange(View v, int left, int top, int right, int bottom,
6574            int oldLeft, int oldTop, int oldRight, int oldBottom);
6575    }
6576
6577    /**
6578     * This is called during layout when the size of this view has changed. If
6579     * you were just added to the view hierarchy, you're called with the old
6580     * values of 0.
6581     *
6582     * @param w Current width of this view.
6583     * @param h Current height of this view.
6584     * @param oldw Old width of this view.
6585     * @param oldh Old height of this view.
6586     */
6587    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6588    }
6589
6590    /**
6591     * Called by draw to draw the child views. This may be overridden
6592     * by derived classes to gain control just before its children are drawn
6593     * (but after its own view has been drawn).
6594     * @param canvas the canvas on which to draw the view
6595     */
6596    protected void dispatchDraw(Canvas canvas) {
6597    }
6598
6599    /**
6600     * Gets the parent of this view. Note that the parent is a
6601     * ViewParent and not necessarily a View.
6602     *
6603     * @return Parent of this view.
6604     */
6605    public final ViewParent getParent() {
6606        return mParent;
6607    }
6608
6609    /**
6610     * Set the horizontal scrolled position of your view. This will cause a call to
6611     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6612     * invalidated.
6613     * @param value the x position to scroll to
6614     */
6615    public void setScrollX(int value) {
6616        scrollTo(value, mScrollY);
6617    }
6618
6619    /**
6620     * Set the vertical scrolled position of your view. This will cause a call to
6621     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6622     * invalidated.
6623     * @param value the y position to scroll to
6624     */
6625    public void setScrollY(int value) {
6626        scrollTo(mScrollX, value);
6627    }
6628
6629    /**
6630     * Return the scrolled left position of this view. This is the left edge of
6631     * the displayed part of your view. You do not need to draw any pixels
6632     * farther left, since those are outside of the frame of your view on
6633     * screen.
6634     *
6635     * @return The left edge of the displayed part of your view, in pixels.
6636     */
6637    public final int getScrollX() {
6638        return mScrollX;
6639    }
6640
6641    /**
6642     * Return the scrolled top position of this view. This is the top edge of
6643     * the displayed part of your view. You do not need to draw any pixels above
6644     * it, since those are outside of the frame of your view on screen.
6645     *
6646     * @return The top edge of the displayed part of your view, in pixels.
6647     */
6648    public final int getScrollY() {
6649        return mScrollY;
6650    }
6651
6652    /**
6653     * Return the width of the your view.
6654     *
6655     * @return The width of your view, in pixels.
6656     */
6657    @ViewDebug.ExportedProperty(category = "layout")
6658    public final int getWidth() {
6659        return mRight - mLeft;
6660    }
6661
6662    /**
6663     * Return the height of your view.
6664     *
6665     * @return The height of your view, in pixels.
6666     */
6667    @ViewDebug.ExportedProperty(category = "layout")
6668    public final int getHeight() {
6669        return mBottom - mTop;
6670    }
6671
6672    /**
6673     * Return the visible drawing bounds of your view. Fills in the output
6674     * rectangle with the values from getScrollX(), getScrollY(),
6675     * getWidth(), and getHeight().
6676     *
6677     * @param outRect The (scrolled) drawing bounds of the view.
6678     */
6679    public void getDrawingRect(Rect outRect) {
6680        outRect.left = mScrollX;
6681        outRect.top = mScrollY;
6682        outRect.right = mScrollX + (mRight - mLeft);
6683        outRect.bottom = mScrollY + (mBottom - mTop);
6684    }
6685
6686    /**
6687     * Like {@link #getMeasuredWidthAndState()}, but only returns the
6688     * raw width component (that is the result is masked by
6689     * {@link #MEASURED_SIZE_MASK}).
6690     *
6691     * @return The raw measured width of this view.
6692     */
6693    public final int getMeasuredWidth() {
6694        return mMeasuredWidth & MEASURED_SIZE_MASK;
6695    }
6696
6697    /**
6698     * Return the full width measurement information for this view as computed
6699     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6700     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6701     * This should be used during measurement and layout calculations only. Use
6702     * {@link #getWidth()} to see how wide a view is after layout.
6703     *
6704     * @return The measured width of this view as a bit mask.
6705     */
6706    public final int getMeasuredWidthAndState() {
6707        return mMeasuredWidth;
6708    }
6709
6710    /**
6711     * Like {@link #getMeasuredHeightAndState()}, but only returns the
6712     * raw width component (that is the result is masked by
6713     * {@link #MEASURED_SIZE_MASK}).
6714     *
6715     * @return The raw measured height of this view.
6716     */
6717    public final int getMeasuredHeight() {
6718        return mMeasuredHeight & MEASURED_SIZE_MASK;
6719    }
6720
6721    /**
6722     * Return the full height measurement information for this view as computed
6723     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6724     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6725     * This should be used during measurement and layout calculations only. Use
6726     * {@link #getHeight()} to see how wide a view is after layout.
6727     *
6728     * @return The measured width of this view as a bit mask.
6729     */
6730    public final int getMeasuredHeightAndState() {
6731        return mMeasuredHeight;
6732    }
6733
6734    /**
6735     * Return only the state bits of {@link #getMeasuredWidthAndState()}
6736     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
6737     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
6738     * and the height component is at the shifted bits
6739     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
6740     */
6741    public final int getMeasuredState() {
6742        return (mMeasuredWidth&MEASURED_STATE_MASK)
6743                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
6744                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
6745    }
6746
6747    /**
6748     * The transform matrix of this view, which is calculated based on the current
6749     * roation, scale, and pivot properties.
6750     *
6751     * @see #getRotation()
6752     * @see #getScaleX()
6753     * @see #getScaleY()
6754     * @see #getPivotX()
6755     * @see #getPivotY()
6756     * @return The current transform matrix for the view
6757     */
6758    public Matrix getMatrix() {
6759        updateMatrix();
6760        return mMatrix;
6761    }
6762
6763    /**
6764     * Utility function to determine if the value is far enough away from zero to be
6765     * considered non-zero.
6766     * @param value A floating point value to check for zero-ness
6767     * @return whether the passed-in value is far enough away from zero to be considered non-zero
6768     */
6769    private static boolean nonzero(float value) {
6770        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
6771    }
6772
6773    /**
6774     * Returns true if the transform matrix is the identity matrix.
6775     * Recomputes the matrix if necessary.
6776     *
6777     * @return True if the transform matrix is the identity matrix, false otherwise.
6778     */
6779    final boolean hasIdentityMatrix() {
6780        updateMatrix();
6781        return mMatrixIsIdentity;
6782    }
6783
6784    /**
6785     * Recomputes the transform matrix if necessary.
6786     */
6787    private void updateMatrix() {
6788        if (mMatrixDirty) {
6789            // transform-related properties have changed since the last time someone
6790            // asked for the matrix; recalculate it with the current values
6791
6792            // Figure out if we need to update the pivot point
6793            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
6794                if ((mRight - mLeft) != mPrevWidth || (mBottom - mTop) != mPrevHeight) {
6795                    mPrevWidth = mRight - mLeft;
6796                    mPrevHeight = mBottom - mTop;
6797                    mPivotX = mPrevWidth / 2f;
6798                    mPivotY = mPrevHeight / 2f;
6799                }
6800            }
6801            mMatrix.reset();
6802            if (!nonzero(mRotationX) && !nonzero(mRotationY)) {
6803                mMatrix.setTranslate(mTranslationX, mTranslationY);
6804                mMatrix.preRotate(mRotation, mPivotX, mPivotY);
6805                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6806            } else {
6807                if (mCamera == null) {
6808                    mCamera = new Camera();
6809                    matrix3D = new Matrix();
6810                }
6811                mCamera.save();
6812                mMatrix.preScale(mScaleX, mScaleY, mPivotX, mPivotY);
6813                mCamera.rotate(mRotationX, mRotationY, -mRotation);
6814                mCamera.getMatrix(matrix3D);
6815                matrix3D.preTranslate(-mPivotX, -mPivotY);
6816                matrix3D.postTranslate(mPivotX + mTranslationX, mPivotY + mTranslationY);
6817                mMatrix.postConcat(matrix3D);
6818                mCamera.restore();
6819            }
6820            mMatrixDirty = false;
6821            mMatrixIsIdentity = mMatrix.isIdentity();
6822            mInverseMatrixDirty = true;
6823        }
6824    }
6825
6826    /**
6827     * Utility method to retrieve the inverse of the current mMatrix property.
6828     * We cache the matrix to avoid recalculating it when transform properties
6829     * have not changed.
6830     *
6831     * @return The inverse of the current matrix of this view.
6832     */
6833    final Matrix getInverseMatrix() {
6834        updateMatrix();
6835        if (mInverseMatrixDirty) {
6836            if (mInverseMatrix == null) {
6837                mInverseMatrix = new Matrix();
6838            }
6839            mMatrix.invert(mInverseMatrix);
6840            mInverseMatrixDirty = false;
6841        }
6842        return mInverseMatrix;
6843    }
6844
6845    /**
6846     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
6847     * views are drawn) from the camera to this view. The camera's distance
6848     * affects 3D transformations, for instance rotations around the X and Y
6849     * axis. If the rotationX or rotationY properties are changed and this view is
6850     * large (more than half the size of the screen), it is recommended to always
6851     * use a camera distance that's greater than the height (X axis rotation) or
6852     * the width (Y axis rotation) of this view.</p>
6853     *
6854     * <p>The distance of the camera from the view plane can have an affect on the
6855     * perspective distortion of the view when it is rotated around the x or y axis.
6856     * For example, a large distance will result in a large viewing angle, and there
6857     * will not be much perspective distortion of the view as it rotates. A short
6858     * distance may cause much more perspective distortion upon rotation, and can
6859     * also result in some drawing artifacts if the rotated view ends up partially
6860     * behind the camera (which is why the recommendation is to use a distance at
6861     * least as far as the size of the view, if the view is to be rotated.)</p>
6862     *
6863     * <p>The distance is expressed in "depth pixels." The default distance depends
6864     * on the screen density. For instance, on a medium density display, the
6865     * default distance is 1280. On a high density display, the default distance
6866     * is 1920.</p>
6867     *
6868     * <p>If you want to specify a distance that leads to visually consistent
6869     * results across various densities, use the following formula:</p>
6870     * <pre>
6871     * float scale = context.getResources().getDisplayMetrics().density;
6872     * view.setCameraDistance(distance * scale);
6873     * </pre>
6874     *
6875     * <p>The density scale factor of a high density display is 1.5,
6876     * and 1920 = 1280 * 1.5.</p>
6877     *
6878     * @param distance The distance in "depth pixels", if negative the opposite
6879     *        value is used
6880     *
6881     * @see #setRotationX(float)
6882     * @see #setRotationY(float)
6883     */
6884    public void setCameraDistance(float distance) {
6885        invalidateParentCaches();
6886        invalidate(false);
6887
6888        final float dpi = mResources.getDisplayMetrics().densityDpi;
6889        if (mCamera == null) {
6890            mCamera = new Camera();
6891            matrix3D = new Matrix();
6892        }
6893
6894        mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
6895        mMatrixDirty = true;
6896
6897        invalidate(false);
6898    }
6899
6900    /**
6901     * The degrees that the view is rotated around the pivot point.
6902     *
6903     * @see #setRotation(float)
6904     * @see #getPivotX()
6905     * @see #getPivotY()
6906     *
6907     * @return The degrees of rotation.
6908     */
6909    public float getRotation() {
6910        return mRotation;
6911    }
6912
6913    /**
6914     * Sets the degrees that the view is rotated around the pivot point. Increasing values
6915     * result in clockwise rotation.
6916     *
6917     * @param rotation The degrees of rotation.
6918     *
6919     * @see #getRotation()
6920     * @see #getPivotX()
6921     * @see #getPivotY()
6922     * @see #setRotationX(float)
6923     * @see #setRotationY(float)
6924     *
6925     * @attr ref android.R.styleable#View_rotation
6926     */
6927    public void setRotation(float rotation) {
6928        if (mRotation != rotation) {
6929            invalidateParentCaches();
6930            // Double-invalidation is necessary to capture view's old and new areas
6931            invalidate(false);
6932            mRotation = rotation;
6933            mMatrixDirty = true;
6934            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6935            invalidate(false);
6936        }
6937    }
6938
6939    /**
6940     * The degrees that the view is rotated around the vertical axis through the pivot point.
6941     *
6942     * @see #getPivotX()
6943     * @see #getPivotY()
6944     * @see #setRotationY(float)
6945     *
6946     * @return The degrees of Y rotation.
6947     */
6948    public float getRotationY() {
6949        return mRotationY;
6950    }
6951
6952    /**
6953     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
6954     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
6955     * down the y axis.
6956     *
6957     * When rotating large views, it is recommended to adjust the camera distance
6958     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
6959     *
6960     * @param rotationY The degrees of Y rotation.
6961     *
6962     * @see #getRotationY()
6963     * @see #getPivotX()
6964     * @see #getPivotY()
6965     * @see #setRotation(float)
6966     * @see #setRotationX(float)
6967     * @see #setCameraDistance(float)
6968     *
6969     * @attr ref android.R.styleable#View_rotationY
6970     */
6971    public void setRotationY(float rotationY) {
6972        if (mRotationY != rotationY) {
6973            invalidateParentCaches();
6974            // Double-invalidation is necessary to capture view's old and new areas
6975            invalidate(false);
6976            mRotationY = rotationY;
6977            mMatrixDirty = true;
6978            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
6979            invalidate(false);
6980        }
6981    }
6982
6983    /**
6984     * The degrees that the view is rotated around the horizontal axis through the pivot point.
6985     *
6986     * @see #getPivotX()
6987     * @see #getPivotY()
6988     * @see #setRotationX(float)
6989     *
6990     * @return The degrees of X rotation.
6991     */
6992    public float getRotationX() {
6993        return mRotationX;
6994    }
6995
6996    /**
6997     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
6998     * Increasing values result in clockwise rotation from the viewpoint of looking down the
6999     * x axis.
7000     *
7001     * When rotating large views, it is recommended to adjust the camera distance
7002     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7003     *
7004     * @param rotationX The degrees of X rotation.
7005     *
7006     * @see #getRotationX()
7007     * @see #getPivotX()
7008     * @see #getPivotY()
7009     * @see #setRotation(float)
7010     * @see #setRotationY(float)
7011     * @see #setCameraDistance(float)
7012     *
7013     * @attr ref android.R.styleable#View_rotationX
7014     */
7015    public void setRotationX(float rotationX) {
7016        if (mRotationX != rotationX) {
7017            invalidateParentCaches();
7018            // Double-invalidation is necessary to capture view's old and new areas
7019            invalidate(false);
7020            mRotationX = rotationX;
7021            mMatrixDirty = true;
7022            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7023            invalidate(false);
7024        }
7025    }
7026
7027    /**
7028     * The amount that the view is scaled in x around the pivot point, as a proportion of
7029     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7030     *
7031     * <p>By default, this is 1.0f.
7032     *
7033     * @see #getPivotX()
7034     * @see #getPivotY()
7035     * @return The scaling factor.
7036     */
7037    public float getScaleX() {
7038        return mScaleX;
7039    }
7040
7041    /**
7042     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7043     * the view's unscaled width. A value of 1 means that no scaling is applied.
7044     *
7045     * @param scaleX The scaling factor.
7046     * @see #getPivotX()
7047     * @see #getPivotY()
7048     *
7049     * @attr ref android.R.styleable#View_scaleX
7050     */
7051    public void setScaleX(float scaleX) {
7052        if (mScaleX != scaleX) {
7053            invalidateParentCaches();
7054            // Double-invalidation is necessary to capture view's old and new areas
7055            invalidate(false);
7056            mScaleX = scaleX;
7057            mMatrixDirty = true;
7058            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7059            invalidate(false);
7060        }
7061    }
7062
7063    /**
7064     * The amount that the view is scaled in y around the pivot point, as a proportion of
7065     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7066     *
7067     * <p>By default, this is 1.0f.
7068     *
7069     * @see #getPivotX()
7070     * @see #getPivotY()
7071     * @return The scaling factor.
7072     */
7073    public float getScaleY() {
7074        return mScaleY;
7075    }
7076
7077    /**
7078     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7079     * the view's unscaled width. A value of 1 means that no scaling is applied.
7080     *
7081     * @param scaleY The scaling factor.
7082     * @see #getPivotX()
7083     * @see #getPivotY()
7084     *
7085     * @attr ref android.R.styleable#View_scaleY
7086     */
7087    public void setScaleY(float scaleY) {
7088        if (mScaleY != scaleY) {
7089            invalidateParentCaches();
7090            // Double-invalidation is necessary to capture view's old and new areas
7091            invalidate(false);
7092            mScaleY = scaleY;
7093            mMatrixDirty = true;
7094            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7095            invalidate(false);
7096        }
7097    }
7098
7099    /**
7100     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7101     * and {@link #setScaleX(float) scaled}.
7102     *
7103     * @see #getRotation()
7104     * @see #getScaleX()
7105     * @see #getScaleY()
7106     * @see #getPivotY()
7107     * @return The x location of the pivot point.
7108     */
7109    public float getPivotX() {
7110        return mPivotX;
7111    }
7112
7113    /**
7114     * Sets the x location of the point around which the view is
7115     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7116     * By default, the pivot point is centered on the object.
7117     * Setting this property disables this behavior and causes the view to use only the
7118     * explicitly set pivotX and pivotY values.
7119     *
7120     * @param pivotX The x location of the pivot point.
7121     * @see #getRotation()
7122     * @see #getScaleX()
7123     * @see #getScaleY()
7124     * @see #getPivotY()
7125     *
7126     * @attr ref android.R.styleable#View_transformPivotX
7127     */
7128    public void setPivotX(float pivotX) {
7129        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7130        if (mPivotX != pivotX) {
7131            invalidateParentCaches();
7132            // Double-invalidation is necessary to capture view's old and new areas
7133            invalidate(false);
7134            mPivotX = pivotX;
7135            mMatrixDirty = true;
7136            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7137            invalidate(false);
7138        }
7139    }
7140
7141    /**
7142     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7143     * and {@link #setScaleY(float) scaled}.
7144     *
7145     * @see #getRotation()
7146     * @see #getScaleX()
7147     * @see #getScaleY()
7148     * @see #getPivotY()
7149     * @return The y location of the pivot point.
7150     */
7151    public float getPivotY() {
7152        return mPivotY;
7153    }
7154
7155    /**
7156     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7157     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7158     * Setting this property disables this behavior and causes the view to use only the
7159     * explicitly set pivotX and pivotY values.
7160     *
7161     * @param pivotY The y location of the pivot point.
7162     * @see #getRotation()
7163     * @see #getScaleX()
7164     * @see #getScaleY()
7165     * @see #getPivotY()
7166     *
7167     * @attr ref android.R.styleable#View_transformPivotY
7168     */
7169    public void setPivotY(float pivotY) {
7170        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7171        if (mPivotY != pivotY) {
7172            invalidateParentCaches();
7173            // Double-invalidation is necessary to capture view's old and new areas
7174            invalidate(false);
7175            mPivotY = pivotY;
7176            mMatrixDirty = true;
7177            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7178            invalidate(false);
7179        }
7180    }
7181
7182    /**
7183     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7184     * completely transparent and 1 means the view is completely opaque.
7185     *
7186     * <p>By default this is 1.0f.
7187     * @return The opacity of the view.
7188     */
7189    public float getAlpha() {
7190        return mAlpha;
7191    }
7192
7193    /**
7194     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7195     * completely transparent and 1 means the view is completely opaque.</p>
7196     *
7197     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7198     * responsible for applying the opacity itself. Otherwise, calling this method is
7199     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7200     * setting a hardware layer.</p>
7201     *
7202     * @param alpha The opacity of the view.
7203     *
7204     * @see #setLayerType(int, android.graphics.Paint)
7205     *
7206     * @attr ref android.R.styleable#View_alpha
7207     */
7208    public void setAlpha(float alpha) {
7209        mAlpha = alpha;
7210        invalidateParentCaches();
7211        if (onSetAlpha((int) (alpha * 255))) {
7212            mPrivateFlags |= ALPHA_SET;
7213            // subclass is handling alpha - don't optimize rendering cache invalidation
7214            invalidate(true);
7215        } else {
7216            mPrivateFlags &= ~ALPHA_SET;
7217            invalidate(false);
7218        }
7219    }
7220
7221    /**
7222     * Faster version of setAlpha() which performs the same steps except there are
7223     * no calls to invalidate(). The caller of this function should perform proper invalidation
7224     * on the parent and this object. The return value indicates whether the subclass handles
7225     * alpha (the return value for onSetAlpha()).
7226     *
7227     * @param alpha The new value for the alpha property
7228     * @return true if the View subclass handles alpha (the return value for onSetAlpha())
7229     */
7230    boolean setAlphaNoInvalidation(float alpha) {
7231        mAlpha = alpha;
7232        boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7233        if (subclassHandlesAlpha) {
7234            mPrivateFlags |= ALPHA_SET;
7235        } else {
7236            mPrivateFlags &= ~ALPHA_SET;
7237        }
7238        return subclassHandlesAlpha;
7239    }
7240
7241    /**
7242     * Top position of this view relative to its parent.
7243     *
7244     * @return The top of this view, in pixels.
7245     */
7246    @ViewDebug.CapturedViewProperty
7247    public final int getTop() {
7248        return mTop;
7249    }
7250
7251    /**
7252     * Sets the top position of this view relative to its parent. This method is meant to be called
7253     * by the layout system and should not generally be called otherwise, because the property
7254     * may be changed at any time by the layout.
7255     *
7256     * @param top The top of this view, in pixels.
7257     */
7258    public final void setTop(int top) {
7259        if (top != mTop) {
7260            updateMatrix();
7261            if (mMatrixIsIdentity) {
7262                if (mAttachInfo != null) {
7263                    int minTop;
7264                    int yLoc;
7265                    if (top < mTop) {
7266                        minTop = top;
7267                        yLoc = top - mTop;
7268                    } else {
7269                        minTop = mTop;
7270                        yLoc = 0;
7271                    }
7272                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7273                }
7274            } else {
7275                // Double-invalidation is necessary to capture view's old and new areas
7276                invalidate(true);
7277            }
7278
7279            int width = mRight - mLeft;
7280            int oldHeight = mBottom - mTop;
7281
7282            mTop = top;
7283
7284            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7285
7286            if (!mMatrixIsIdentity) {
7287                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7288                    // A change in dimension means an auto-centered pivot point changes, too
7289                    mMatrixDirty = true;
7290                }
7291                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7292                invalidate(true);
7293            }
7294            mBackgroundSizeChanged = true;
7295            invalidateParentIfNeeded();
7296        }
7297    }
7298
7299    /**
7300     * Bottom position of this view relative to its parent.
7301     *
7302     * @return The bottom of this view, in pixels.
7303     */
7304    @ViewDebug.CapturedViewProperty
7305    public final int getBottom() {
7306        return mBottom;
7307    }
7308
7309    /**
7310     * True if this view has changed since the last time being drawn.
7311     *
7312     * @return The dirty state of this view.
7313     */
7314    public boolean isDirty() {
7315        return (mPrivateFlags & DIRTY_MASK) != 0;
7316    }
7317
7318    /**
7319     * Sets the bottom position of this view relative to its parent. This method is meant to be
7320     * called by the layout system and should not generally be called otherwise, because the
7321     * property may be changed at any time by the layout.
7322     *
7323     * @param bottom The bottom of this view, in pixels.
7324     */
7325    public final void setBottom(int bottom) {
7326        if (bottom != mBottom) {
7327            updateMatrix();
7328            if (mMatrixIsIdentity) {
7329                if (mAttachInfo != null) {
7330                    int maxBottom;
7331                    if (bottom < mBottom) {
7332                        maxBottom = mBottom;
7333                    } else {
7334                        maxBottom = bottom;
7335                    }
7336                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7337                }
7338            } else {
7339                // Double-invalidation is necessary to capture view's old and new areas
7340                invalidate(true);
7341            }
7342
7343            int width = mRight - mLeft;
7344            int oldHeight = mBottom - mTop;
7345
7346            mBottom = bottom;
7347
7348            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7349
7350            if (!mMatrixIsIdentity) {
7351                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7352                    // A change in dimension means an auto-centered pivot point changes, too
7353                    mMatrixDirty = true;
7354                }
7355                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7356                invalidate(true);
7357            }
7358            mBackgroundSizeChanged = true;
7359            invalidateParentIfNeeded();
7360        }
7361    }
7362
7363    /**
7364     * Left position of this view relative to its parent.
7365     *
7366     * @return The left edge of this view, in pixels.
7367     */
7368    @ViewDebug.CapturedViewProperty
7369    public final int getLeft() {
7370        return mLeft;
7371    }
7372
7373    /**
7374     * Sets the left position of this view relative to its parent. This method is meant to be called
7375     * by the layout system and should not generally be called otherwise, because the property
7376     * may be changed at any time by the layout.
7377     *
7378     * @param left The bottom of this view, in pixels.
7379     */
7380    public final void setLeft(int left) {
7381        if (left != mLeft) {
7382            updateMatrix();
7383            if (mMatrixIsIdentity) {
7384                if (mAttachInfo != null) {
7385                    int minLeft;
7386                    int xLoc;
7387                    if (left < mLeft) {
7388                        minLeft = left;
7389                        xLoc = left - mLeft;
7390                    } else {
7391                        minLeft = mLeft;
7392                        xLoc = 0;
7393                    }
7394                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7395                }
7396            } else {
7397                // Double-invalidation is necessary to capture view's old and new areas
7398                invalidate(true);
7399            }
7400
7401            int oldWidth = mRight - mLeft;
7402            int height = mBottom - mTop;
7403
7404            mLeft = left;
7405
7406            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7407
7408            if (!mMatrixIsIdentity) {
7409                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7410                    // A change in dimension means an auto-centered pivot point changes, too
7411                    mMatrixDirty = true;
7412                }
7413                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7414                invalidate(true);
7415            }
7416            mBackgroundSizeChanged = true;
7417            invalidateParentIfNeeded();
7418        }
7419    }
7420
7421    /**
7422     * Right position of this view relative to its parent.
7423     *
7424     * @return The right edge of this view, in pixels.
7425     */
7426    @ViewDebug.CapturedViewProperty
7427    public final int getRight() {
7428        return mRight;
7429    }
7430
7431    /**
7432     * Sets the right position of this view relative to its parent. This method is meant to be called
7433     * by the layout system and should not generally be called otherwise, because the property
7434     * may be changed at any time by the layout.
7435     *
7436     * @param right The bottom of this view, in pixels.
7437     */
7438    public final void setRight(int right) {
7439        if (right != mRight) {
7440            updateMatrix();
7441            if (mMatrixIsIdentity) {
7442                if (mAttachInfo != null) {
7443                    int maxRight;
7444                    if (right < mRight) {
7445                        maxRight = mRight;
7446                    } else {
7447                        maxRight = right;
7448                    }
7449                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7450                }
7451            } else {
7452                // Double-invalidation is necessary to capture view's old and new areas
7453                invalidate(true);
7454            }
7455
7456            int oldWidth = mRight - mLeft;
7457            int height = mBottom - mTop;
7458
7459            mRight = right;
7460
7461            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7462
7463            if (!mMatrixIsIdentity) {
7464                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7465                    // A change in dimension means an auto-centered pivot point changes, too
7466                    mMatrixDirty = true;
7467                }
7468                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7469                invalidate(true);
7470            }
7471            mBackgroundSizeChanged = true;
7472            invalidateParentIfNeeded();
7473        }
7474    }
7475
7476    /**
7477     * The visual x position of this view, in pixels. This is equivalent to the
7478     * {@link #setTranslationX(float) translationX} property plus the current
7479     * {@link #getLeft() left} property.
7480     *
7481     * @return The visual x position of this view, in pixels.
7482     */
7483    public float getX() {
7484        return mLeft + mTranslationX;
7485    }
7486
7487    /**
7488     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7489     * {@link #setTranslationX(float) translationX} property to be the difference between
7490     * the x value passed in and the current {@link #getLeft() left} property.
7491     *
7492     * @param x The visual x position of this view, in pixels.
7493     */
7494    public void setX(float x) {
7495        setTranslationX(x - mLeft);
7496    }
7497
7498    /**
7499     * The visual y position of this view, in pixels. This is equivalent to the
7500     * {@link #setTranslationY(float) translationY} property plus the current
7501     * {@link #getTop() top} property.
7502     *
7503     * @return The visual y position of this view, in pixels.
7504     */
7505    public float getY() {
7506        return mTop + mTranslationY;
7507    }
7508
7509    /**
7510     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7511     * {@link #setTranslationY(float) translationY} property to be the difference between
7512     * the y value passed in and the current {@link #getTop() top} property.
7513     *
7514     * @param y The visual y position of this view, in pixels.
7515     */
7516    public void setY(float y) {
7517        setTranslationY(y - mTop);
7518    }
7519
7520
7521    /**
7522     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7523     * This position is post-layout, in addition to wherever the object's
7524     * layout placed it.
7525     *
7526     * @return The horizontal position of this view relative to its left position, in pixels.
7527     */
7528    public float getTranslationX() {
7529        return mTranslationX;
7530    }
7531
7532    /**
7533     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7534     * This effectively positions the object post-layout, in addition to wherever the object's
7535     * layout placed it.
7536     *
7537     * @param translationX The horizontal position of this view relative to its left position,
7538     * in pixels.
7539     *
7540     * @attr ref android.R.styleable#View_translationX
7541     */
7542    public void setTranslationX(float translationX) {
7543        if (mTranslationX != translationX) {
7544            invalidateParentCaches();
7545            // Double-invalidation is necessary to capture view's old and new areas
7546            invalidate(false);
7547            mTranslationX = translationX;
7548            mMatrixDirty = true;
7549            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7550            invalidate(false);
7551        }
7552    }
7553
7554    /**
7555     * The horizontal location of this view relative to its {@link #getTop() top} position.
7556     * This position is post-layout, in addition to wherever the object's
7557     * layout placed it.
7558     *
7559     * @return The vertical position of this view relative to its top position,
7560     * in pixels.
7561     */
7562    public float getTranslationY() {
7563        return mTranslationY;
7564    }
7565
7566    /**
7567     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7568     * This effectively positions the object post-layout, in addition to wherever the object's
7569     * layout placed it.
7570     *
7571     * @param translationY The vertical position of this view relative to its top position,
7572     * in pixels.
7573     *
7574     * @attr ref android.R.styleable#View_translationY
7575     */
7576    public void setTranslationY(float translationY) {
7577        if (mTranslationY != translationY) {
7578            invalidateParentCaches();
7579            // Double-invalidation is necessary to capture view's old and new areas
7580            invalidate(false);
7581            mTranslationY = translationY;
7582            mMatrixDirty = true;
7583            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7584            invalidate(false);
7585        }
7586    }
7587
7588    /**
7589     * @hide
7590     */
7591    public void setFastTranslationX(float x) {
7592        mTranslationX = x;
7593        mMatrixDirty = true;
7594    }
7595
7596    /**
7597     * @hide
7598     */
7599    public void setFastTranslationY(float y) {
7600        mTranslationY = y;
7601        mMatrixDirty = true;
7602    }
7603
7604    /**
7605     * @hide
7606     */
7607    public void setFastX(float x) {
7608        mTranslationX = x - mLeft;
7609        mMatrixDirty = true;
7610    }
7611
7612    /**
7613     * @hide
7614     */
7615    public void setFastY(float y) {
7616        mTranslationY = y - mTop;
7617        mMatrixDirty = true;
7618    }
7619
7620    /**
7621     * @hide
7622     */
7623    public void setFastScaleX(float x) {
7624        mScaleX = x;
7625        mMatrixDirty = true;
7626    }
7627
7628    /**
7629     * @hide
7630     */
7631    public void setFastScaleY(float y) {
7632        mScaleY = y;
7633        mMatrixDirty = true;
7634    }
7635
7636    /**
7637     * @hide
7638     */
7639    public void setFastAlpha(float alpha) {
7640        mAlpha = alpha;
7641    }
7642
7643    /**
7644     * @hide
7645     */
7646    public void setFastRotationY(float y) {
7647        mRotationY = y;
7648        mMatrixDirty = true;
7649    }
7650
7651    /**
7652     * Hit rectangle in parent's coordinates
7653     *
7654     * @param outRect The hit rectangle of the view.
7655     */
7656    public void getHitRect(Rect outRect) {
7657        updateMatrix();
7658        if (mMatrixIsIdentity || mAttachInfo == null) {
7659            outRect.set(mLeft, mTop, mRight, mBottom);
7660        } else {
7661            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
7662            tmpRect.set(-mPivotX, -mPivotY, getWidth() - mPivotX, getHeight() - mPivotY);
7663            mMatrix.mapRect(tmpRect);
7664            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
7665                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
7666        }
7667    }
7668
7669    /**
7670     * Determines whether the given point, in local coordinates is inside the view.
7671     */
7672    /*package*/ final boolean pointInView(float localX, float localY) {
7673        return localX >= 0 && localX < (mRight - mLeft)
7674                && localY >= 0 && localY < (mBottom - mTop);
7675    }
7676
7677    /**
7678     * Utility method to determine whether the given point, in local coordinates,
7679     * is inside the view, where the area of the view is expanded by the slop factor.
7680     * This method is called while processing touch-move events to determine if the event
7681     * is still within the view.
7682     */
7683    private boolean pointInView(float localX, float localY, float slop) {
7684        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
7685                localY < ((mBottom - mTop) + slop);
7686    }
7687
7688    /**
7689     * When a view has focus and the user navigates away from it, the next view is searched for
7690     * starting from the rectangle filled in by this method.
7691     *
7692     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
7693     * of the view.  However, if your view maintains some idea of internal selection,
7694     * such as a cursor, or a selected row or column, you should override this method and
7695     * fill in a more specific rectangle.
7696     *
7697     * @param r The rectangle to fill in, in this view's coordinates.
7698     */
7699    public void getFocusedRect(Rect r) {
7700        getDrawingRect(r);
7701    }
7702
7703    /**
7704     * If some part of this view is not clipped by any of its parents, then
7705     * return that area in r in global (root) coordinates. To convert r to local
7706     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
7707     * -globalOffset.y)) If the view is completely clipped or translated out,
7708     * return false.
7709     *
7710     * @param r If true is returned, r holds the global coordinates of the
7711     *        visible portion of this view.
7712     * @param globalOffset If true is returned, globalOffset holds the dx,dy
7713     *        between this view and its root. globalOffet may be null.
7714     * @return true if r is non-empty (i.e. part of the view is visible at the
7715     *         root level.
7716     */
7717    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
7718        int width = mRight - mLeft;
7719        int height = mBottom - mTop;
7720        if (width > 0 && height > 0) {
7721            r.set(0, 0, width, height);
7722            if (globalOffset != null) {
7723                globalOffset.set(-mScrollX, -mScrollY);
7724            }
7725            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
7726        }
7727        return false;
7728    }
7729
7730    public final boolean getGlobalVisibleRect(Rect r) {
7731        return getGlobalVisibleRect(r, null);
7732    }
7733
7734    public final boolean getLocalVisibleRect(Rect r) {
7735        Point offset = new Point();
7736        if (getGlobalVisibleRect(r, offset)) {
7737            r.offset(-offset.x, -offset.y); // make r local
7738            return true;
7739        }
7740        return false;
7741    }
7742
7743    /**
7744     * Offset this view's vertical location by the specified number of pixels.
7745     *
7746     * @param offset the number of pixels to offset the view by
7747     */
7748    public void offsetTopAndBottom(int offset) {
7749        if (offset != 0) {
7750            updateMatrix();
7751            if (mMatrixIsIdentity) {
7752                final ViewParent p = mParent;
7753                if (p != null && mAttachInfo != null) {
7754                    final Rect r = mAttachInfo.mTmpInvalRect;
7755                    int minTop;
7756                    int maxBottom;
7757                    int yLoc;
7758                    if (offset < 0) {
7759                        minTop = mTop + offset;
7760                        maxBottom = mBottom;
7761                        yLoc = offset;
7762                    } else {
7763                        minTop = mTop;
7764                        maxBottom = mBottom + offset;
7765                        yLoc = 0;
7766                    }
7767                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
7768                    p.invalidateChild(this, r);
7769                }
7770            } else {
7771                invalidate(false);
7772            }
7773
7774            mTop += offset;
7775            mBottom += offset;
7776
7777            if (!mMatrixIsIdentity) {
7778                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7779                invalidate(false);
7780            }
7781            invalidateParentIfNeeded();
7782        }
7783    }
7784
7785    /**
7786     * Offset this view's horizontal location by the specified amount of pixels.
7787     *
7788     * @param offset the numer of pixels to offset the view by
7789     */
7790    public void offsetLeftAndRight(int offset) {
7791        if (offset != 0) {
7792            updateMatrix();
7793            if (mMatrixIsIdentity) {
7794                final ViewParent p = mParent;
7795                if (p != null && mAttachInfo != null) {
7796                    final Rect r = mAttachInfo.mTmpInvalRect;
7797                    int minLeft;
7798                    int maxRight;
7799                    if (offset < 0) {
7800                        minLeft = mLeft + offset;
7801                        maxRight = mRight;
7802                    } else {
7803                        minLeft = mLeft;
7804                        maxRight = mRight + offset;
7805                    }
7806                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
7807                    p.invalidateChild(this, r);
7808                }
7809            } else {
7810                invalidate(false);
7811            }
7812
7813            mLeft += offset;
7814            mRight += offset;
7815
7816            if (!mMatrixIsIdentity) {
7817                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7818                invalidate(false);
7819            }
7820            invalidateParentIfNeeded();
7821        }
7822    }
7823
7824    /**
7825     * Get the LayoutParams associated with this view. All views should have
7826     * layout parameters. These supply parameters to the <i>parent</i> of this
7827     * view specifying how it should be arranged. There are many subclasses of
7828     * ViewGroup.LayoutParams, and these correspond to the different subclasses
7829     * of ViewGroup that are responsible for arranging their children.
7830     *
7831     * This method may return null if this View is not attached to a parent
7832     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
7833     * was not invoked successfully. When a View is attached to a parent
7834     * ViewGroup, this method must not return null.
7835     *
7836     * @return The LayoutParams associated with this view, or null if no
7837     *         parameters have been set yet
7838     */
7839    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
7840    public ViewGroup.LayoutParams getLayoutParams() {
7841        return mLayoutParams;
7842    }
7843
7844    /**
7845     * Set the layout parameters associated with this view. These supply
7846     * parameters to the <i>parent</i> of this view specifying how it should be
7847     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
7848     * correspond to the different subclasses of ViewGroup that are responsible
7849     * for arranging their children.
7850     *
7851     * @param params The layout parameters for this view, cannot be null
7852     */
7853    public void setLayoutParams(ViewGroup.LayoutParams params) {
7854        if (params == null) {
7855            throw new NullPointerException("Layout parameters cannot be null");
7856        }
7857        mLayoutParams = params;
7858        requestLayout();
7859    }
7860
7861    /**
7862     * Set the scrolled position of your view. This will cause a call to
7863     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7864     * invalidated.
7865     * @param x the x position to scroll to
7866     * @param y the y position to scroll to
7867     */
7868    public void scrollTo(int x, int y) {
7869        if (mScrollX != x || mScrollY != y) {
7870            int oldX = mScrollX;
7871            int oldY = mScrollY;
7872            mScrollX = x;
7873            mScrollY = y;
7874            invalidateParentCaches();
7875            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
7876            if (!awakenScrollBars()) {
7877                invalidate(true);
7878            }
7879        }
7880    }
7881
7882    /**
7883     * Move the scrolled position of your view. This will cause a call to
7884     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7885     * invalidated.
7886     * @param x the amount of pixels to scroll by horizontally
7887     * @param y the amount of pixels to scroll by vertically
7888     */
7889    public void scrollBy(int x, int y) {
7890        scrollTo(mScrollX + x, mScrollY + y);
7891    }
7892
7893    /**
7894     * <p>Trigger the scrollbars to draw. When invoked this method starts an
7895     * animation to fade the scrollbars out after a default delay. If a subclass
7896     * provides animated scrolling, the start delay should equal the duration
7897     * of the scrolling animation.</p>
7898     *
7899     * <p>The animation starts only if at least one of the scrollbars is
7900     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
7901     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7902     * this method returns true, and false otherwise. If the animation is
7903     * started, this method calls {@link #invalidate()}; in that case the
7904     * caller should not call {@link #invalidate()}.</p>
7905     *
7906     * <p>This method should be invoked every time a subclass directly updates
7907     * the scroll parameters.</p>
7908     *
7909     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
7910     * and {@link #scrollTo(int, int)}.</p>
7911     *
7912     * @return true if the animation is played, false otherwise
7913     *
7914     * @see #awakenScrollBars(int)
7915     * @see #scrollBy(int, int)
7916     * @see #scrollTo(int, int)
7917     * @see #isHorizontalScrollBarEnabled()
7918     * @see #isVerticalScrollBarEnabled()
7919     * @see #setHorizontalScrollBarEnabled(boolean)
7920     * @see #setVerticalScrollBarEnabled(boolean)
7921     */
7922    protected boolean awakenScrollBars() {
7923        return mScrollCache != null &&
7924                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
7925    }
7926
7927    /**
7928     * Trigger the scrollbars to draw.
7929     * This method differs from awakenScrollBars() only in its default duration.
7930     * initialAwakenScrollBars() will show the scroll bars for longer than
7931     * usual to give the user more of a chance to notice them.
7932     *
7933     * @return true if the animation is played, false otherwise.
7934     */
7935    private boolean initialAwakenScrollBars() {
7936        return mScrollCache != null &&
7937                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
7938    }
7939
7940    /**
7941     * <p>
7942     * Trigger the scrollbars to draw. When invoked this method starts an
7943     * animation to fade the scrollbars out after a fixed delay. If a subclass
7944     * provides animated scrolling, the start delay should equal the duration of
7945     * the scrolling animation.
7946     * </p>
7947     *
7948     * <p>
7949     * The animation starts only if at least one of the scrollbars is enabled,
7950     * as specified by {@link #isHorizontalScrollBarEnabled()} and
7951     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7952     * this method returns true, and false otherwise. If the animation is
7953     * started, this method calls {@link #invalidate()}; in that case the caller
7954     * should not call {@link #invalidate()}.
7955     * </p>
7956     *
7957     * <p>
7958     * This method should be invoked everytime a subclass directly updates the
7959     * scroll parameters.
7960     * </p>
7961     *
7962     * @param startDelay the delay, in milliseconds, after which the animation
7963     *        should start; when the delay is 0, the animation starts
7964     *        immediately
7965     * @return true if the animation is played, false otherwise
7966     *
7967     * @see #scrollBy(int, int)
7968     * @see #scrollTo(int, int)
7969     * @see #isHorizontalScrollBarEnabled()
7970     * @see #isVerticalScrollBarEnabled()
7971     * @see #setHorizontalScrollBarEnabled(boolean)
7972     * @see #setVerticalScrollBarEnabled(boolean)
7973     */
7974    protected boolean awakenScrollBars(int startDelay) {
7975        return awakenScrollBars(startDelay, true);
7976    }
7977
7978    /**
7979     * <p>
7980     * Trigger the scrollbars to draw. When invoked this method starts an
7981     * animation to fade the scrollbars out after a fixed delay. If a subclass
7982     * provides animated scrolling, the start delay should equal the duration of
7983     * the scrolling animation.
7984     * </p>
7985     *
7986     * <p>
7987     * The animation starts only if at least one of the scrollbars is enabled,
7988     * as specified by {@link #isHorizontalScrollBarEnabled()} and
7989     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
7990     * this method returns true, and false otherwise. If the animation is
7991     * started, this method calls {@link #invalidate()} if the invalidate parameter
7992     * is set to true; in that case the caller
7993     * should not call {@link #invalidate()}.
7994     * </p>
7995     *
7996     * <p>
7997     * This method should be invoked everytime a subclass directly updates the
7998     * scroll parameters.
7999     * </p>
8000     *
8001     * @param startDelay the delay, in milliseconds, after which the animation
8002     *        should start; when the delay is 0, the animation starts
8003     *        immediately
8004     *
8005     * @param invalidate Wheter this method should call invalidate
8006     *
8007     * @return true if the animation is played, false otherwise
8008     *
8009     * @see #scrollBy(int, int)
8010     * @see #scrollTo(int, int)
8011     * @see #isHorizontalScrollBarEnabled()
8012     * @see #isVerticalScrollBarEnabled()
8013     * @see #setHorizontalScrollBarEnabled(boolean)
8014     * @see #setVerticalScrollBarEnabled(boolean)
8015     */
8016    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8017        final ScrollabilityCache scrollCache = mScrollCache;
8018
8019        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8020            return false;
8021        }
8022
8023        if (scrollCache.scrollBar == null) {
8024            scrollCache.scrollBar = new ScrollBarDrawable();
8025        }
8026
8027        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8028
8029            if (invalidate) {
8030                // Invalidate to show the scrollbars
8031                invalidate(true);
8032            }
8033
8034            if (scrollCache.state == ScrollabilityCache.OFF) {
8035                // FIXME: this is copied from WindowManagerService.
8036                // We should get this value from the system when it
8037                // is possible to do so.
8038                final int KEY_REPEAT_FIRST_DELAY = 750;
8039                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8040            }
8041
8042            // Tell mScrollCache when we should start fading. This may
8043            // extend the fade start time if one was already scheduled
8044            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8045            scrollCache.fadeStartTime = fadeStartTime;
8046            scrollCache.state = ScrollabilityCache.ON;
8047
8048            // Schedule our fader to run, unscheduling any old ones first
8049            if (mAttachInfo != null) {
8050                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8051                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8052            }
8053
8054            return true;
8055        }
8056
8057        return false;
8058    }
8059
8060    /**
8061     * Mark the the area defined by dirty as needing to be drawn. If the view is
8062     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8063     * in the future. This must be called from a UI thread. To call from a non-UI
8064     * thread, call {@link #postInvalidate()}.
8065     *
8066     * WARNING: This method is destructive to dirty.
8067     * @param dirty the rectangle representing the bounds of the dirty region
8068     */
8069    public void invalidate(Rect dirty) {
8070        if (ViewDebug.TRACE_HIERARCHY) {
8071            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8072        }
8073
8074        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8075                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8076                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8077            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8078            mPrivateFlags |= INVALIDATED;
8079            final ViewParent p = mParent;
8080            final AttachInfo ai = mAttachInfo;
8081            //noinspection PointlessBooleanExpression,ConstantConditions
8082            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8083                if (p != null && ai != null && ai.mHardwareAccelerated) {
8084                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8085                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8086                    p.invalidateChild(this, null);
8087                    return;
8088                }
8089            }
8090            if (p != null && ai != null) {
8091                final int scrollX = mScrollX;
8092                final int scrollY = mScrollY;
8093                final Rect r = ai.mTmpInvalRect;
8094                r.set(dirty.left - scrollX, dirty.top - scrollY,
8095                        dirty.right - scrollX, dirty.bottom - scrollY);
8096                mParent.invalidateChild(this, r);
8097            }
8098        }
8099    }
8100
8101    /**
8102     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
8103     * The coordinates of the dirty rect are relative to the view.
8104     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8105     * will be called at some point in the future. This must be called from
8106     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8107     * @param l the left position of the dirty region
8108     * @param t the top position of the dirty region
8109     * @param r the right position of the dirty region
8110     * @param b the bottom position of the dirty region
8111     */
8112    public void invalidate(int l, int t, int r, int b) {
8113        if (ViewDebug.TRACE_HIERARCHY) {
8114            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8115        }
8116
8117        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8118                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8119                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8120            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8121            mPrivateFlags |= INVALIDATED;
8122            final ViewParent p = mParent;
8123            final AttachInfo ai = mAttachInfo;
8124            //noinspection PointlessBooleanExpression,ConstantConditions
8125            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8126                if (p != null && ai != null && ai.mHardwareAccelerated) {
8127                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8128                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8129                    p.invalidateChild(this, null);
8130                    return;
8131                }
8132            }
8133            if (p != null && ai != null && l < r && t < b) {
8134                final int scrollX = mScrollX;
8135                final int scrollY = mScrollY;
8136                final Rect tmpr = ai.mTmpInvalRect;
8137                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8138                p.invalidateChild(this, tmpr);
8139            }
8140        }
8141    }
8142
8143    /**
8144     * Invalidate the whole view. If the view is visible,
8145     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8146     * the future. This must be called from a UI thread. To call from a non-UI thread,
8147     * call {@link #postInvalidate()}.
8148     */
8149    public void invalidate() {
8150        invalidate(true);
8151    }
8152
8153    /**
8154     * This is where the invalidate() work actually happens. A full invalidate()
8155     * causes the drawing cache to be invalidated, but this function can be called with
8156     * invalidateCache set to false to skip that invalidation step for cases that do not
8157     * need it (for example, a component that remains at the same dimensions with the same
8158     * content).
8159     *
8160     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8161     * well. This is usually true for a full invalidate, but may be set to false if the
8162     * View's contents or dimensions have not changed.
8163     */
8164    void invalidate(boolean invalidateCache) {
8165        if (ViewDebug.TRACE_HIERARCHY) {
8166            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8167        }
8168
8169        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8170                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8171                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8172            mLastIsOpaque = isOpaque();
8173            mPrivateFlags &= ~DRAWN;
8174            if (invalidateCache) {
8175                mPrivateFlags |= INVALIDATED;
8176                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8177            }
8178            final AttachInfo ai = mAttachInfo;
8179            final ViewParent p = mParent;
8180            //noinspection PointlessBooleanExpression,ConstantConditions
8181            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8182                if (p != null && ai != null && ai.mHardwareAccelerated) {
8183                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8184                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8185                    p.invalidateChild(this, null);
8186                    return;
8187                }
8188            }
8189
8190            if (p != null && ai != null) {
8191                final Rect r = ai.mTmpInvalRect;
8192                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8193                // Don't call invalidate -- we don't want to internally scroll
8194                // our own bounds
8195                p.invalidateChild(this, r);
8196            }
8197        }
8198    }
8199
8200    /**
8201     * @hide
8202     */
8203    public void fastInvalidate() {
8204        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8205            (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8206            (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8207            if (mParent instanceof View) {
8208                ((View) mParent).mPrivateFlags |= INVALIDATED;
8209            }
8210            mPrivateFlags &= ~DRAWN;
8211            mPrivateFlags |= INVALIDATED;
8212            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8213            if (mParent != null && mAttachInfo != null) {
8214                if (mAttachInfo.mHardwareAccelerated) {
8215                    mParent.invalidateChild(this, null);
8216                } else {
8217                    final Rect r = mAttachInfo.mTmpInvalRect;
8218                    r.set(0, 0, mRight - mLeft, mBottom - mTop);
8219                    // Don't call invalidate -- we don't want to internally scroll
8220                    // our own bounds
8221                    mParent.invalidateChild(this, r);
8222                }
8223            }
8224        }
8225    }
8226
8227    /**
8228     * Used to indicate that the parent of this view should clear its caches. This functionality
8229     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8230     * which is necessary when various parent-managed properties of the view change, such as
8231     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8232     * clears the parent caches and does not causes an invalidate event.
8233     *
8234     * @hide
8235     */
8236    protected void invalidateParentCaches() {
8237        if (mParent instanceof View) {
8238            ((View) mParent).mPrivateFlags |= INVALIDATED;
8239        }
8240    }
8241
8242    /**
8243     * Used to indicate that the parent of this view should be invalidated. This functionality
8244     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8245     * which is necessary when various parent-managed properties of the view change, such as
8246     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8247     * an invalidation event to the parent.
8248     *
8249     * @hide
8250     */
8251    protected void invalidateParentIfNeeded() {
8252        if (isHardwareAccelerated() && mParent instanceof View) {
8253            ((View) mParent).invalidate(true);
8254        }
8255    }
8256
8257    /**
8258     * Indicates whether this View is opaque. An opaque View guarantees that it will
8259     * draw all the pixels overlapping its bounds using a fully opaque color.
8260     *
8261     * Subclasses of View should override this method whenever possible to indicate
8262     * whether an instance is opaque. Opaque Views are treated in a special way by
8263     * the View hierarchy, possibly allowing it to perform optimizations during
8264     * invalidate/draw passes.
8265     *
8266     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8267     */
8268    @ViewDebug.ExportedProperty(category = "drawing")
8269    public boolean isOpaque() {
8270        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8271                (mAlpha >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8272    }
8273
8274    /**
8275     * @hide
8276     */
8277    protected void computeOpaqueFlags() {
8278        // Opaque if:
8279        //   - Has a background
8280        //   - Background is opaque
8281        //   - Doesn't have scrollbars or scrollbars are inside overlay
8282
8283        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8284            mPrivateFlags |= OPAQUE_BACKGROUND;
8285        } else {
8286            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8287        }
8288
8289        final int flags = mViewFlags;
8290        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8291                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8292            mPrivateFlags |= OPAQUE_SCROLLBARS;
8293        } else {
8294            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8295        }
8296    }
8297
8298    /**
8299     * @hide
8300     */
8301    protected boolean hasOpaqueScrollbars() {
8302        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8303    }
8304
8305    /**
8306     * @return A handler associated with the thread running the View. This
8307     * handler can be used to pump events in the UI events queue.
8308     */
8309    public Handler getHandler() {
8310        if (mAttachInfo != null) {
8311            return mAttachInfo.mHandler;
8312        }
8313        return null;
8314    }
8315
8316    /**
8317     * Causes the Runnable to be added to the message queue.
8318     * The runnable will be run on the user interface thread.
8319     *
8320     * @param action The Runnable that will be executed.
8321     *
8322     * @return Returns true if the Runnable was successfully placed in to the
8323     *         message queue.  Returns false on failure, usually because the
8324     *         looper processing the message queue is exiting.
8325     */
8326    public boolean post(Runnable action) {
8327        Handler handler;
8328        AttachInfo attachInfo = mAttachInfo;
8329        if (attachInfo != null) {
8330            handler = attachInfo.mHandler;
8331        } else {
8332            // Assume that post will succeed later
8333            ViewRootImpl.getRunQueue().post(action);
8334            return true;
8335        }
8336
8337        return handler.post(action);
8338    }
8339
8340    /**
8341     * Causes the Runnable to be added to the message queue, to be run
8342     * after the specified amount of time elapses.
8343     * The runnable will be run on the user interface thread.
8344     *
8345     * @param action The Runnable that will be executed.
8346     * @param delayMillis The delay (in milliseconds) until the Runnable
8347     *        will be executed.
8348     *
8349     * @return true if the Runnable was successfully placed in to the
8350     *         message queue.  Returns false on failure, usually because the
8351     *         looper processing the message queue is exiting.  Note that a
8352     *         result of true does not mean the Runnable will be processed --
8353     *         if the looper is quit before the delivery time of the message
8354     *         occurs then the message will be dropped.
8355     */
8356    public boolean postDelayed(Runnable action, long delayMillis) {
8357        Handler handler;
8358        AttachInfo attachInfo = mAttachInfo;
8359        if (attachInfo != null) {
8360            handler = attachInfo.mHandler;
8361        } else {
8362            // Assume that post will succeed later
8363            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8364            return true;
8365        }
8366
8367        return handler.postDelayed(action, delayMillis);
8368    }
8369
8370    /**
8371     * Removes the specified Runnable from the message queue.
8372     *
8373     * @param action The Runnable to remove from the message handling queue
8374     *
8375     * @return true if this view could ask the Handler to remove the Runnable,
8376     *         false otherwise. When the returned value is true, the Runnable
8377     *         may or may not have been actually removed from the message queue
8378     *         (for instance, if the Runnable was not in the queue already.)
8379     */
8380    public boolean removeCallbacks(Runnable action) {
8381        Handler handler;
8382        AttachInfo attachInfo = mAttachInfo;
8383        if (attachInfo != null) {
8384            handler = attachInfo.mHandler;
8385        } else {
8386            // Assume that post will succeed later
8387            ViewRootImpl.getRunQueue().removeCallbacks(action);
8388            return true;
8389        }
8390
8391        handler.removeCallbacks(action);
8392        return true;
8393    }
8394
8395    /**
8396     * Cause an invalidate to happen on a subsequent cycle through the event loop.
8397     * Use this to invalidate the View from a non-UI thread.
8398     *
8399     * @see #invalidate()
8400     */
8401    public void postInvalidate() {
8402        postInvalidateDelayed(0);
8403    }
8404
8405    /**
8406     * Cause an invalidate of the specified area to happen on a subsequent cycle
8407     * through the event loop. Use this to invalidate the View from a non-UI thread.
8408     *
8409     * @param left The left coordinate of the rectangle to invalidate.
8410     * @param top The top coordinate of the rectangle to invalidate.
8411     * @param right The right coordinate of the rectangle to invalidate.
8412     * @param bottom The bottom coordinate of the rectangle to invalidate.
8413     *
8414     * @see #invalidate(int, int, int, int)
8415     * @see #invalidate(Rect)
8416     */
8417    public void postInvalidate(int left, int top, int right, int bottom) {
8418        postInvalidateDelayed(0, left, top, right, bottom);
8419    }
8420
8421    /**
8422     * Cause an invalidate to happen on a subsequent cycle through the event
8423     * loop. Waits for the specified amount of time.
8424     *
8425     * @param delayMilliseconds the duration in milliseconds to delay the
8426     *         invalidation by
8427     */
8428    public void postInvalidateDelayed(long delayMilliseconds) {
8429        // We try only with the AttachInfo because there's no point in invalidating
8430        // if we are not attached to our window
8431        AttachInfo attachInfo = mAttachInfo;
8432        if (attachInfo != null) {
8433            Message msg = Message.obtain();
8434            msg.what = AttachInfo.INVALIDATE_MSG;
8435            msg.obj = this;
8436            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8437        }
8438    }
8439
8440    /**
8441     * Cause an invalidate of the specified area to happen on a subsequent cycle
8442     * through the event loop. Waits for the specified amount of time.
8443     *
8444     * @param delayMilliseconds the duration in milliseconds to delay the
8445     *         invalidation by
8446     * @param left The left coordinate of the rectangle to invalidate.
8447     * @param top The top coordinate of the rectangle to invalidate.
8448     * @param right The right coordinate of the rectangle to invalidate.
8449     * @param bottom The bottom coordinate of the rectangle to invalidate.
8450     */
8451    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8452            int right, int bottom) {
8453
8454        // We try only with the AttachInfo because there's no point in invalidating
8455        // if we are not attached to our window
8456        AttachInfo attachInfo = mAttachInfo;
8457        if (attachInfo != null) {
8458            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8459            info.target = this;
8460            info.left = left;
8461            info.top = top;
8462            info.right = right;
8463            info.bottom = bottom;
8464
8465            final Message msg = Message.obtain();
8466            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8467            msg.obj = info;
8468            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8469        }
8470    }
8471
8472    /**
8473     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8474     * This event is sent at most once every
8475     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8476     */
8477    private void postSendViewScrolledAccessibilityEventCallback() {
8478        if (mSendViewScrolledAccessibilityEvent == null) {
8479            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8480        }
8481        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8482            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8483            postDelayed(mSendViewScrolledAccessibilityEvent,
8484                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8485        }
8486    }
8487
8488    /**
8489     * Called by a parent to request that a child update its values for mScrollX
8490     * and mScrollY if necessary. This will typically be done if the child is
8491     * animating a scroll using a {@link android.widget.Scroller Scroller}
8492     * object.
8493     */
8494    public void computeScroll() {
8495    }
8496
8497    /**
8498     * <p>Indicate whether the horizontal edges are faded when the view is
8499     * scrolled horizontally.</p>
8500     *
8501     * @return true if the horizontal edges should are faded on scroll, false
8502     *         otherwise
8503     *
8504     * @see #setHorizontalFadingEdgeEnabled(boolean)
8505     * @attr ref android.R.styleable#View_fadingEdge
8506     */
8507    public boolean isHorizontalFadingEdgeEnabled() {
8508        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8509    }
8510
8511    /**
8512     * <p>Define whether the horizontal edges should be faded when this view
8513     * is scrolled horizontally.</p>
8514     *
8515     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8516     *                                    be faded when the view is scrolled
8517     *                                    horizontally
8518     *
8519     * @see #isHorizontalFadingEdgeEnabled()
8520     * @attr ref android.R.styleable#View_fadingEdge
8521     */
8522    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8523        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8524            if (horizontalFadingEdgeEnabled) {
8525                initScrollCache();
8526            }
8527
8528            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8529        }
8530    }
8531
8532    /**
8533     * <p>Indicate whether the vertical edges are faded when the view is
8534     * scrolled horizontally.</p>
8535     *
8536     * @return true if the vertical edges should are faded on scroll, false
8537     *         otherwise
8538     *
8539     * @see #setVerticalFadingEdgeEnabled(boolean)
8540     * @attr ref android.R.styleable#View_fadingEdge
8541     */
8542    public boolean isVerticalFadingEdgeEnabled() {
8543        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8544    }
8545
8546    /**
8547     * <p>Define whether the vertical edges should be faded when this view
8548     * is scrolled vertically.</p>
8549     *
8550     * @param verticalFadingEdgeEnabled true if the vertical edges should
8551     *                                  be faded when the view is scrolled
8552     *                                  vertically
8553     *
8554     * @see #isVerticalFadingEdgeEnabled()
8555     * @attr ref android.R.styleable#View_fadingEdge
8556     */
8557    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8558        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8559            if (verticalFadingEdgeEnabled) {
8560                initScrollCache();
8561            }
8562
8563            mViewFlags ^= FADING_EDGE_VERTICAL;
8564        }
8565    }
8566
8567    /**
8568     * Returns the strength, or intensity, of the top faded edge. The strength is
8569     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8570     * returns 0.0 or 1.0 but no value in between.
8571     *
8572     * Subclasses should override this method to provide a smoother fade transition
8573     * when scrolling occurs.
8574     *
8575     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8576     */
8577    protected float getTopFadingEdgeStrength() {
8578        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8579    }
8580
8581    /**
8582     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8583     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8584     * returns 0.0 or 1.0 but no value in between.
8585     *
8586     * Subclasses should override this method to provide a smoother fade transition
8587     * when scrolling occurs.
8588     *
8589     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8590     */
8591    protected float getBottomFadingEdgeStrength() {
8592        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8593                computeVerticalScrollRange() ? 1.0f : 0.0f;
8594    }
8595
8596    /**
8597     * Returns the strength, or intensity, of the left faded edge. The strength is
8598     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8599     * returns 0.0 or 1.0 but no value in between.
8600     *
8601     * Subclasses should override this method to provide a smoother fade transition
8602     * when scrolling occurs.
8603     *
8604     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8605     */
8606    protected float getLeftFadingEdgeStrength() {
8607        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8608    }
8609
8610    /**
8611     * Returns the strength, or intensity, of the right faded edge. The strength is
8612     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8613     * returns 0.0 or 1.0 but no value in between.
8614     *
8615     * Subclasses should override this method to provide a smoother fade transition
8616     * when scrolling occurs.
8617     *
8618     * @return the intensity of the right fade as a float between 0.0f and 1.0f
8619     */
8620    protected float getRightFadingEdgeStrength() {
8621        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
8622                computeHorizontalScrollRange() ? 1.0f : 0.0f;
8623    }
8624
8625    /**
8626     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
8627     * scrollbar is not drawn by default.</p>
8628     *
8629     * @return true if the horizontal scrollbar should be painted, false
8630     *         otherwise
8631     *
8632     * @see #setHorizontalScrollBarEnabled(boolean)
8633     */
8634    public boolean isHorizontalScrollBarEnabled() {
8635        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8636    }
8637
8638    /**
8639     * <p>Define whether the horizontal scrollbar should be drawn or not. The
8640     * scrollbar is not drawn by default.</p>
8641     *
8642     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
8643     *                                   be painted
8644     *
8645     * @see #isHorizontalScrollBarEnabled()
8646     */
8647    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
8648        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
8649            mViewFlags ^= SCROLLBARS_HORIZONTAL;
8650            computeOpaqueFlags();
8651            resolvePadding();
8652        }
8653    }
8654
8655    /**
8656     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
8657     * scrollbar is not drawn by default.</p>
8658     *
8659     * @return true if the vertical scrollbar should be painted, false
8660     *         otherwise
8661     *
8662     * @see #setVerticalScrollBarEnabled(boolean)
8663     */
8664    public boolean isVerticalScrollBarEnabled() {
8665        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
8666    }
8667
8668    /**
8669     * <p>Define whether the vertical scrollbar should be drawn or not. The
8670     * scrollbar is not drawn by default.</p>
8671     *
8672     * @param verticalScrollBarEnabled true if the vertical scrollbar should
8673     *                                 be painted
8674     *
8675     * @see #isVerticalScrollBarEnabled()
8676     */
8677    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
8678        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
8679            mViewFlags ^= SCROLLBARS_VERTICAL;
8680            computeOpaqueFlags();
8681            resolvePadding();
8682        }
8683    }
8684
8685    /**
8686     * @hide
8687     */
8688    protected void recomputePadding() {
8689        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
8690    }
8691
8692    /**
8693     * Define whether scrollbars will fade when the view is not scrolling.
8694     *
8695     * @param fadeScrollbars wheter to enable fading
8696     *
8697     */
8698    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
8699        initScrollCache();
8700        final ScrollabilityCache scrollabilityCache = mScrollCache;
8701        scrollabilityCache.fadeScrollBars = fadeScrollbars;
8702        if (fadeScrollbars) {
8703            scrollabilityCache.state = ScrollabilityCache.OFF;
8704        } else {
8705            scrollabilityCache.state = ScrollabilityCache.ON;
8706        }
8707    }
8708
8709    /**
8710     *
8711     * Returns true if scrollbars will fade when this view is not scrolling
8712     *
8713     * @return true if scrollbar fading is enabled
8714     */
8715    public boolean isScrollbarFadingEnabled() {
8716        return mScrollCache != null && mScrollCache.fadeScrollBars;
8717    }
8718
8719    /**
8720     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
8721     * inset. When inset, they add to the padding of the view. And the scrollbars
8722     * can be drawn inside the padding area or on the edge of the view. For example,
8723     * if a view has a background drawable and you want to draw the scrollbars
8724     * inside the padding specified by the drawable, you can use
8725     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
8726     * appear at the edge of the view, ignoring the padding, then you can use
8727     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
8728     * @param style the style of the scrollbars. Should be one of
8729     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
8730     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
8731     * @see #SCROLLBARS_INSIDE_OVERLAY
8732     * @see #SCROLLBARS_INSIDE_INSET
8733     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8734     * @see #SCROLLBARS_OUTSIDE_INSET
8735     */
8736    public void setScrollBarStyle(int style) {
8737        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
8738            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
8739            computeOpaqueFlags();
8740            resolvePadding();
8741        }
8742    }
8743
8744    /**
8745     * <p>Returns the current scrollbar style.</p>
8746     * @return the current scrollbar style
8747     * @see #SCROLLBARS_INSIDE_OVERLAY
8748     * @see #SCROLLBARS_INSIDE_INSET
8749     * @see #SCROLLBARS_OUTSIDE_OVERLAY
8750     * @see #SCROLLBARS_OUTSIDE_INSET
8751     */
8752    public int getScrollBarStyle() {
8753        return mViewFlags & SCROLLBARS_STYLE_MASK;
8754    }
8755
8756    /**
8757     * <p>Compute the horizontal range that the horizontal scrollbar
8758     * represents.</p>
8759     *
8760     * <p>The range is expressed in arbitrary units that must be the same as the
8761     * units used by {@link #computeHorizontalScrollExtent()} and
8762     * {@link #computeHorizontalScrollOffset()}.</p>
8763     *
8764     * <p>The default range is the drawing width of this view.</p>
8765     *
8766     * @return the total horizontal range represented by the horizontal
8767     *         scrollbar
8768     *
8769     * @see #computeHorizontalScrollExtent()
8770     * @see #computeHorizontalScrollOffset()
8771     * @see android.widget.ScrollBarDrawable
8772     */
8773    protected int computeHorizontalScrollRange() {
8774        return getWidth();
8775    }
8776
8777    /**
8778     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
8779     * within the horizontal range. This value is used to compute the position
8780     * of the thumb within the scrollbar's track.</p>
8781     *
8782     * <p>The range is expressed in arbitrary units that must be the same as the
8783     * units used by {@link #computeHorizontalScrollRange()} and
8784     * {@link #computeHorizontalScrollExtent()}.</p>
8785     *
8786     * <p>The default offset is the scroll offset of this view.</p>
8787     *
8788     * @return the horizontal offset of the scrollbar's thumb
8789     *
8790     * @see #computeHorizontalScrollRange()
8791     * @see #computeHorizontalScrollExtent()
8792     * @see android.widget.ScrollBarDrawable
8793     */
8794    protected int computeHorizontalScrollOffset() {
8795        return mScrollX;
8796    }
8797
8798    /**
8799     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
8800     * within the horizontal range. This value is used to compute the length
8801     * of the thumb within the scrollbar's track.</p>
8802     *
8803     * <p>The range is expressed in arbitrary units that must be the same as the
8804     * units used by {@link #computeHorizontalScrollRange()} and
8805     * {@link #computeHorizontalScrollOffset()}.</p>
8806     *
8807     * <p>The default extent is the drawing width of this view.</p>
8808     *
8809     * @return the horizontal extent of the scrollbar's thumb
8810     *
8811     * @see #computeHorizontalScrollRange()
8812     * @see #computeHorizontalScrollOffset()
8813     * @see android.widget.ScrollBarDrawable
8814     */
8815    protected int computeHorizontalScrollExtent() {
8816        return getWidth();
8817    }
8818
8819    /**
8820     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
8821     *
8822     * <p>The range is expressed in arbitrary units that must be the same as the
8823     * units used by {@link #computeVerticalScrollExtent()} and
8824     * {@link #computeVerticalScrollOffset()}.</p>
8825     *
8826     * @return the total vertical range represented by the vertical scrollbar
8827     *
8828     * <p>The default range is the drawing height of this view.</p>
8829     *
8830     * @see #computeVerticalScrollExtent()
8831     * @see #computeVerticalScrollOffset()
8832     * @see android.widget.ScrollBarDrawable
8833     */
8834    protected int computeVerticalScrollRange() {
8835        return getHeight();
8836    }
8837
8838    /**
8839     * <p>Compute the vertical offset of the vertical scrollbar's thumb
8840     * within the horizontal range. This value is used to compute the position
8841     * of the thumb within the scrollbar's track.</p>
8842     *
8843     * <p>The range is expressed in arbitrary units that must be the same as the
8844     * units used by {@link #computeVerticalScrollRange()} and
8845     * {@link #computeVerticalScrollExtent()}.</p>
8846     *
8847     * <p>The default offset is the scroll offset of this view.</p>
8848     *
8849     * @return the vertical offset of the scrollbar's thumb
8850     *
8851     * @see #computeVerticalScrollRange()
8852     * @see #computeVerticalScrollExtent()
8853     * @see android.widget.ScrollBarDrawable
8854     */
8855    protected int computeVerticalScrollOffset() {
8856        return mScrollY;
8857    }
8858
8859    /**
8860     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
8861     * within the vertical range. This value is used to compute the length
8862     * of the thumb within the scrollbar's track.</p>
8863     *
8864     * <p>The range is expressed in arbitrary units that must be the same as the
8865     * units used by {@link #computeVerticalScrollRange()} and
8866     * {@link #computeVerticalScrollOffset()}.</p>
8867     *
8868     * <p>The default extent is the drawing height of this view.</p>
8869     *
8870     * @return the vertical extent of the scrollbar's thumb
8871     *
8872     * @see #computeVerticalScrollRange()
8873     * @see #computeVerticalScrollOffset()
8874     * @see android.widget.ScrollBarDrawable
8875     */
8876    protected int computeVerticalScrollExtent() {
8877        return getHeight();
8878    }
8879
8880    /**
8881     * Check if this view can be scrolled horizontally in a certain direction.
8882     *
8883     * @param direction Negative to check scrolling left, positive to check scrolling right.
8884     * @return true if this view can be scrolled in the specified direction, false otherwise.
8885     */
8886    public boolean canScrollHorizontally(int direction) {
8887        final int offset = computeHorizontalScrollOffset();
8888        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
8889        if (range == 0) return false;
8890        if (direction < 0) {
8891            return offset > 0;
8892        } else {
8893            return offset < range - 1;
8894        }
8895    }
8896
8897    /**
8898     * Check if this view can be scrolled vertically in a certain direction.
8899     *
8900     * @param direction Negative to check scrolling up, positive to check scrolling down.
8901     * @return true if this view can be scrolled in the specified direction, false otherwise.
8902     */
8903    public boolean canScrollVertically(int direction) {
8904        final int offset = computeVerticalScrollOffset();
8905        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
8906        if (range == 0) return false;
8907        if (direction < 0) {
8908            return offset > 0;
8909        } else {
8910            return offset < range - 1;
8911        }
8912    }
8913
8914    /**
8915     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
8916     * scrollbars are painted only if they have been awakened first.</p>
8917     *
8918     * @param canvas the canvas on which to draw the scrollbars
8919     *
8920     * @see #awakenScrollBars(int)
8921     */
8922    protected final void onDrawScrollBars(Canvas canvas) {
8923        // scrollbars are drawn only when the animation is running
8924        final ScrollabilityCache cache = mScrollCache;
8925        if (cache != null) {
8926
8927            int state = cache.state;
8928
8929            if (state == ScrollabilityCache.OFF) {
8930                return;
8931            }
8932
8933            boolean invalidate = false;
8934
8935            if (state == ScrollabilityCache.FADING) {
8936                // We're fading -- get our fade interpolation
8937                if (cache.interpolatorValues == null) {
8938                    cache.interpolatorValues = new float[1];
8939                }
8940
8941                float[] values = cache.interpolatorValues;
8942
8943                // Stops the animation if we're done
8944                if (cache.scrollBarInterpolator.timeToValues(values) ==
8945                        Interpolator.Result.FREEZE_END) {
8946                    cache.state = ScrollabilityCache.OFF;
8947                } else {
8948                    cache.scrollBar.setAlpha(Math.round(values[0]));
8949                }
8950
8951                // This will make the scroll bars inval themselves after
8952                // drawing. We only want this when we're fading so that
8953                // we prevent excessive redraws
8954                invalidate = true;
8955            } else {
8956                // We're just on -- but we may have been fading before so
8957                // reset alpha
8958                cache.scrollBar.setAlpha(255);
8959            }
8960
8961
8962            final int viewFlags = mViewFlags;
8963
8964            final boolean drawHorizontalScrollBar =
8965                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8966            final boolean drawVerticalScrollBar =
8967                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
8968                && !isVerticalScrollBarHidden();
8969
8970            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
8971                final int width = mRight - mLeft;
8972                final int height = mBottom - mTop;
8973
8974                final ScrollBarDrawable scrollBar = cache.scrollBar;
8975
8976                final int scrollX = mScrollX;
8977                final int scrollY = mScrollY;
8978                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
8979
8980                int left, top, right, bottom;
8981
8982                if (drawHorizontalScrollBar) {
8983                    int size = scrollBar.getSize(false);
8984                    if (size <= 0) {
8985                        size = cache.scrollBarSize;
8986                    }
8987
8988                    scrollBar.setParameters(computeHorizontalScrollRange(),
8989                                            computeHorizontalScrollOffset(),
8990                                            computeHorizontalScrollExtent(), false);
8991                    final int verticalScrollBarGap = drawVerticalScrollBar ?
8992                            getVerticalScrollbarWidth() : 0;
8993                    top = scrollY + height - size - (mUserPaddingBottom & inside);
8994                    left = scrollX + (mPaddingLeft & inside);
8995                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
8996                    bottom = top + size;
8997                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
8998                    if (invalidate) {
8999                        invalidate(left, top, right, bottom);
9000                    }
9001                }
9002
9003                if (drawVerticalScrollBar) {
9004                    int size = scrollBar.getSize(true);
9005                    if (size <= 0) {
9006                        size = cache.scrollBarSize;
9007                    }
9008
9009                    scrollBar.setParameters(computeVerticalScrollRange(),
9010                                            computeVerticalScrollOffset(),
9011                                            computeVerticalScrollExtent(), true);
9012                    switch (mVerticalScrollbarPosition) {
9013                        default:
9014                        case SCROLLBAR_POSITION_DEFAULT:
9015                        case SCROLLBAR_POSITION_RIGHT:
9016                            left = scrollX + width - size - (mUserPaddingRight & inside);
9017                            break;
9018                        case SCROLLBAR_POSITION_LEFT:
9019                            left = scrollX + (mUserPaddingLeft & inside);
9020                            break;
9021                    }
9022                    top = scrollY + (mPaddingTop & inside);
9023                    right = left + size;
9024                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9025                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9026                    if (invalidate) {
9027                        invalidate(left, top, right, bottom);
9028                    }
9029                }
9030            }
9031        }
9032    }
9033
9034    /**
9035     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9036     * FastScroller is visible.
9037     * @return whether to temporarily hide the vertical scrollbar
9038     * @hide
9039     */
9040    protected boolean isVerticalScrollBarHidden() {
9041        return false;
9042    }
9043
9044    /**
9045     * <p>Draw the horizontal scrollbar if
9046     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9047     *
9048     * @param canvas the canvas on which to draw the scrollbar
9049     * @param scrollBar the scrollbar's drawable
9050     *
9051     * @see #isHorizontalScrollBarEnabled()
9052     * @see #computeHorizontalScrollRange()
9053     * @see #computeHorizontalScrollExtent()
9054     * @see #computeHorizontalScrollOffset()
9055     * @see android.widget.ScrollBarDrawable
9056     * @hide
9057     */
9058    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9059            int l, int t, int r, int b) {
9060        scrollBar.setBounds(l, t, r, b);
9061        scrollBar.draw(canvas);
9062    }
9063
9064    /**
9065     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9066     * returns true.</p>
9067     *
9068     * @param canvas the canvas on which to draw the scrollbar
9069     * @param scrollBar the scrollbar's drawable
9070     *
9071     * @see #isVerticalScrollBarEnabled()
9072     * @see #computeVerticalScrollRange()
9073     * @see #computeVerticalScrollExtent()
9074     * @see #computeVerticalScrollOffset()
9075     * @see android.widget.ScrollBarDrawable
9076     * @hide
9077     */
9078    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9079            int l, int t, int r, int b) {
9080        scrollBar.setBounds(l, t, r, b);
9081        scrollBar.draw(canvas);
9082    }
9083
9084    /**
9085     * Implement this to do your drawing.
9086     *
9087     * @param canvas the canvas on which the background will be drawn
9088     */
9089    protected void onDraw(Canvas canvas) {
9090    }
9091
9092    /*
9093     * Caller is responsible for calling requestLayout if necessary.
9094     * (This allows addViewInLayout to not request a new layout.)
9095     */
9096    void assignParent(ViewParent parent) {
9097        if (mParent == null) {
9098            mParent = parent;
9099        } else if (parent == null) {
9100            mParent = null;
9101        } else {
9102            throw new RuntimeException("view " + this + " being added, but"
9103                    + " it already has a parent");
9104        }
9105    }
9106
9107    /**
9108     * This is called when the view is attached to a window.  At this point it
9109     * has a Surface and will start drawing.  Note that this function is
9110     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9111     * however it may be called any time before the first onDraw -- including
9112     * before or after {@link #onMeasure(int, int)}.
9113     *
9114     * @see #onDetachedFromWindow()
9115     */
9116    protected void onAttachedToWindow() {
9117        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9118            mParent.requestTransparentRegion(this);
9119        }
9120        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9121            initialAwakenScrollBars();
9122            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9123        }
9124        jumpDrawablesToCurrentState();
9125        resolveLayoutDirectionIfNeeded();
9126        resolvePadding();
9127        resolveTextDirection();
9128        if (isFocused()) {
9129            InputMethodManager imm = InputMethodManager.peekInstance();
9130            imm.focusIn(this);
9131        }
9132    }
9133
9134    /**
9135     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9136     * that the parent directionality can and will be resolved before its children.
9137     */
9138    private void resolveLayoutDirectionIfNeeded() {
9139        // Do not resolve if it is not needed
9140        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9141
9142        // Clear any previous layout direction resolution
9143        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9144
9145        // Set resolved depending on layout direction
9146        switch (getLayoutDirection()) {
9147            case LAYOUT_DIRECTION_INHERIT:
9148                // We cannot do the resolution if there is no parent
9149                if (mParent == null) return;
9150
9151                // If this is root view, no need to look at parent's layout dir.
9152                if (mParent instanceof ViewGroup) {
9153                    ViewGroup viewGroup = ((ViewGroup) mParent);
9154
9155                    // Check if the parent view group can resolve
9156                    if (! viewGroup.canResolveLayoutDirection()) {
9157                        return;
9158                    }
9159                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9160                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9161                    }
9162                }
9163                break;
9164            case LAYOUT_DIRECTION_RTL:
9165                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9166                break;
9167            case LAYOUT_DIRECTION_LOCALE:
9168                if(isLayoutDirectionRtl(Locale.getDefault())) {
9169                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9170                }
9171                break;
9172            default:
9173                // Nothing to do, LTR by default
9174        }
9175
9176        // Set to resolved
9177        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9178    }
9179
9180    /**
9181     * @hide
9182     */
9183    protected void resolvePadding() {
9184        // If the user specified the absolute padding (either with android:padding or
9185        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9186        // use the default padding or the padding from the background drawable
9187        // (stored at this point in mPadding*)
9188        switch (getResolvedLayoutDirection()) {
9189            case LAYOUT_DIRECTION_RTL:
9190                // Start user padding override Right user padding. Otherwise, if Right user
9191                // padding is not defined, use the default Right padding. If Right user padding
9192                // is defined, just use it.
9193                if (mUserPaddingStart >= 0) {
9194                    mUserPaddingRight = mUserPaddingStart;
9195                } else if (mUserPaddingRight < 0) {
9196                    mUserPaddingRight = mPaddingRight;
9197                }
9198                if (mUserPaddingEnd >= 0) {
9199                    mUserPaddingLeft = mUserPaddingEnd;
9200                } else if (mUserPaddingLeft < 0) {
9201                    mUserPaddingLeft = mPaddingLeft;
9202                }
9203                break;
9204            case LAYOUT_DIRECTION_LTR:
9205            default:
9206                // Start user padding override Left user padding. Otherwise, if Left user
9207                // padding is not defined, use the default left padding. If Left user padding
9208                // is defined, just use it.
9209                if (mUserPaddingStart >= 0) {
9210                    mUserPaddingLeft = mUserPaddingStart;
9211                } else if (mUserPaddingLeft < 0) {
9212                    mUserPaddingLeft = mPaddingLeft;
9213                }
9214                if (mUserPaddingEnd >= 0) {
9215                    mUserPaddingRight = mUserPaddingEnd;
9216                } else if (mUserPaddingRight < 0) {
9217                    mUserPaddingRight = mPaddingRight;
9218                }
9219        }
9220
9221        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9222
9223        recomputePadding();
9224    }
9225
9226    protected boolean canResolveLayoutDirection() {
9227        switch (getLayoutDirection()) {
9228            case LAYOUT_DIRECTION_INHERIT:
9229                return (mParent != null);
9230            default:
9231                return true;
9232        }
9233    }
9234
9235    /**
9236     * Reset the resolved layout direction.
9237     *
9238     * Subclasses need to override this method to clear cached information that depends on the
9239     * resolved layout direction, or to inform child views that inherit their layout direction.
9240     * Overrides must also call the superclass implementation at the start of their implementation.
9241     *
9242     * @hide
9243     */
9244    protected void resetResolvedLayoutDirection() {
9245        // Reset the current View resolution
9246        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9247    }
9248
9249    /**
9250     * Check if a Locale is corresponding to a RTL script.
9251     *
9252     * @param locale Locale to check
9253     * @return true if a Locale is corresponding to a RTL script.
9254     */
9255    protected static boolean isLayoutDirectionRtl(Locale locale) {
9256        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9257                LocaleUtil.getLayoutDirectionFromLocale(locale));
9258    }
9259
9260    /**
9261     * This is called when the view is detached from a window.  At this point it
9262     * no longer has a surface for drawing.
9263     *
9264     * @see #onAttachedToWindow()
9265     */
9266    protected void onDetachedFromWindow() {
9267        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9268
9269        removeUnsetPressCallback();
9270        removeLongPressCallback();
9271        removePerformClickCallback();
9272        removeSendViewScrolledAccessibilityEventCallback();
9273
9274        destroyDrawingCache();
9275
9276        destroyLayer();
9277
9278        if (mDisplayList != null) {
9279            mDisplayList.invalidate();
9280        }
9281
9282        if (mAttachInfo != null) {
9283            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9284            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_RECT_MSG, this);
9285        }
9286
9287        mCurrentAnimation = null;
9288
9289        resetResolvedLayoutDirection();
9290        resetResolvedTextDirection();
9291    }
9292
9293    /**
9294     * @return The number of times this view has been attached to a window
9295     */
9296    protected int getWindowAttachCount() {
9297        return mWindowAttachCount;
9298    }
9299
9300    /**
9301     * Retrieve a unique token identifying the window this view is attached to.
9302     * @return Return the window's token for use in
9303     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9304     */
9305    public IBinder getWindowToken() {
9306        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9307    }
9308
9309    /**
9310     * Retrieve a unique token identifying the top-level "real" window of
9311     * the window that this view is attached to.  That is, this is like
9312     * {@link #getWindowToken}, except if the window this view in is a panel
9313     * window (attached to another containing window), then the token of
9314     * the containing window is returned instead.
9315     *
9316     * @return Returns the associated window token, either
9317     * {@link #getWindowToken()} or the containing window's token.
9318     */
9319    public IBinder getApplicationWindowToken() {
9320        AttachInfo ai = mAttachInfo;
9321        if (ai != null) {
9322            IBinder appWindowToken = ai.mPanelParentWindowToken;
9323            if (appWindowToken == null) {
9324                appWindowToken = ai.mWindowToken;
9325            }
9326            return appWindowToken;
9327        }
9328        return null;
9329    }
9330
9331    /**
9332     * Retrieve private session object this view hierarchy is using to
9333     * communicate with the window manager.
9334     * @return the session object to communicate with the window manager
9335     */
9336    /*package*/ IWindowSession getWindowSession() {
9337        return mAttachInfo != null ? mAttachInfo.mSession : null;
9338    }
9339
9340    /**
9341     * @param info the {@link android.view.View.AttachInfo} to associated with
9342     *        this view
9343     */
9344    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9345        //System.out.println("Attached! " + this);
9346        mAttachInfo = info;
9347        mWindowAttachCount++;
9348        // We will need to evaluate the drawable state at least once.
9349        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9350        if (mFloatingTreeObserver != null) {
9351            info.mTreeObserver.merge(mFloatingTreeObserver);
9352            mFloatingTreeObserver = null;
9353        }
9354        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9355            mAttachInfo.mScrollContainers.add(this);
9356            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9357        }
9358        performCollectViewAttributes(visibility);
9359        onAttachedToWindow();
9360
9361        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9362                mOnAttachStateChangeListeners;
9363        if (listeners != null && listeners.size() > 0) {
9364            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9365            // perform the dispatching. The iterator is a safe guard against listeners that
9366            // could mutate the list by calling the various add/remove methods. This prevents
9367            // the array from being modified while we iterate it.
9368            for (OnAttachStateChangeListener listener : listeners) {
9369                listener.onViewAttachedToWindow(this);
9370            }
9371        }
9372
9373        int vis = info.mWindowVisibility;
9374        if (vis != GONE) {
9375            onWindowVisibilityChanged(vis);
9376        }
9377        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9378            // If nobody has evaluated the drawable state yet, then do it now.
9379            refreshDrawableState();
9380        }
9381    }
9382
9383    void dispatchDetachedFromWindow() {
9384        AttachInfo info = mAttachInfo;
9385        if (info != null) {
9386            int vis = info.mWindowVisibility;
9387            if (vis != GONE) {
9388                onWindowVisibilityChanged(GONE);
9389            }
9390        }
9391
9392        onDetachedFromWindow();
9393
9394        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9395                mOnAttachStateChangeListeners;
9396        if (listeners != null && listeners.size() > 0) {
9397            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9398            // perform the dispatching. The iterator is a safe guard against listeners that
9399            // could mutate the list by calling the various add/remove methods. This prevents
9400            // the array from being modified while we iterate it.
9401            for (OnAttachStateChangeListener listener : listeners) {
9402                listener.onViewDetachedFromWindow(this);
9403            }
9404        }
9405
9406        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9407            mAttachInfo.mScrollContainers.remove(this);
9408            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9409        }
9410
9411        mAttachInfo = null;
9412    }
9413
9414    /**
9415     * Store this view hierarchy's frozen state into the given container.
9416     *
9417     * @param container The SparseArray in which to save the view's state.
9418     *
9419     * @see #restoreHierarchyState(android.util.SparseArray)
9420     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9421     * @see #onSaveInstanceState()
9422     */
9423    public void saveHierarchyState(SparseArray<Parcelable> container) {
9424        dispatchSaveInstanceState(container);
9425    }
9426
9427    /**
9428     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9429     * this view and its children. May be overridden to modify how freezing happens to a
9430     * view's children; for example, some views may want to not store state for their children.
9431     *
9432     * @param container The SparseArray in which to save the view's state.
9433     *
9434     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9435     * @see #saveHierarchyState(android.util.SparseArray)
9436     * @see #onSaveInstanceState()
9437     */
9438    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9439        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9440            mPrivateFlags &= ~SAVE_STATE_CALLED;
9441            Parcelable state = onSaveInstanceState();
9442            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9443                throw new IllegalStateException(
9444                        "Derived class did not call super.onSaveInstanceState()");
9445            }
9446            if (state != null) {
9447                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9448                // + ": " + state);
9449                container.put(mID, state);
9450            }
9451        }
9452    }
9453
9454    /**
9455     * Hook allowing a view to generate a representation of its internal state
9456     * that can later be used to create a new instance with that same state.
9457     * This state should only contain information that is not persistent or can
9458     * not be reconstructed later. For example, you will never store your
9459     * current position on screen because that will be computed again when a
9460     * new instance of the view is placed in its view hierarchy.
9461     * <p>
9462     * Some examples of things you may store here: the current cursor position
9463     * in a text view (but usually not the text itself since that is stored in a
9464     * content provider or other persistent storage), the currently selected
9465     * item in a list view.
9466     *
9467     * @return Returns a Parcelable object containing the view's current dynamic
9468     *         state, or null if there is nothing interesting to save. The
9469     *         default implementation returns null.
9470     * @see #onRestoreInstanceState(android.os.Parcelable)
9471     * @see #saveHierarchyState(android.util.SparseArray)
9472     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9473     * @see #setSaveEnabled(boolean)
9474     */
9475    protected Parcelable onSaveInstanceState() {
9476        mPrivateFlags |= SAVE_STATE_CALLED;
9477        return BaseSavedState.EMPTY_STATE;
9478    }
9479
9480    /**
9481     * Restore this view hierarchy's frozen state from the given container.
9482     *
9483     * @param container The SparseArray which holds previously frozen states.
9484     *
9485     * @see #saveHierarchyState(android.util.SparseArray)
9486     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9487     * @see #onRestoreInstanceState(android.os.Parcelable)
9488     */
9489    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9490        dispatchRestoreInstanceState(container);
9491    }
9492
9493    /**
9494     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9495     * state for this view and its children. May be overridden to modify how restoring
9496     * happens to a view's children; for example, some views may want to not store state
9497     * for their children.
9498     *
9499     * @param container The SparseArray which holds previously saved state.
9500     *
9501     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9502     * @see #restoreHierarchyState(android.util.SparseArray)
9503     * @see #onRestoreInstanceState(android.os.Parcelable)
9504     */
9505    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9506        if (mID != NO_ID) {
9507            Parcelable state = container.get(mID);
9508            if (state != null) {
9509                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9510                // + ": " + state);
9511                mPrivateFlags &= ~SAVE_STATE_CALLED;
9512                onRestoreInstanceState(state);
9513                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9514                    throw new IllegalStateException(
9515                            "Derived class did not call super.onRestoreInstanceState()");
9516                }
9517            }
9518        }
9519    }
9520
9521    /**
9522     * Hook allowing a view to re-apply a representation of its internal state that had previously
9523     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9524     * null state.
9525     *
9526     * @param state The frozen state that had previously been returned by
9527     *        {@link #onSaveInstanceState}.
9528     *
9529     * @see #onSaveInstanceState()
9530     * @see #restoreHierarchyState(android.util.SparseArray)
9531     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9532     */
9533    protected void onRestoreInstanceState(Parcelable state) {
9534        mPrivateFlags |= SAVE_STATE_CALLED;
9535        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9536            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9537                    + "received " + state.getClass().toString() + " instead. This usually happens "
9538                    + "when two views of different type have the same id in the same hierarchy. "
9539                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9540                    + "other views do not use the same id.");
9541        }
9542    }
9543
9544    /**
9545     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9546     *
9547     * @return the drawing start time in milliseconds
9548     */
9549    public long getDrawingTime() {
9550        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9551    }
9552
9553    /**
9554     * <p>Enables or disables the duplication of the parent's state into this view. When
9555     * duplication is enabled, this view gets its drawable state from its parent rather
9556     * than from its own internal properties.</p>
9557     *
9558     * <p>Note: in the current implementation, setting this property to true after the
9559     * view was added to a ViewGroup might have no effect at all. This property should
9560     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9561     *
9562     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9563     * property is enabled, an exception will be thrown.</p>
9564     *
9565     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9566     * parent, these states should not be affected by this method.</p>
9567     *
9568     * @param enabled True to enable duplication of the parent's drawable state, false
9569     *                to disable it.
9570     *
9571     * @see #getDrawableState()
9572     * @see #isDuplicateParentStateEnabled()
9573     */
9574    public void setDuplicateParentStateEnabled(boolean enabled) {
9575        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9576    }
9577
9578    /**
9579     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9580     *
9581     * @return True if this view's drawable state is duplicated from the parent,
9582     *         false otherwise
9583     *
9584     * @see #getDrawableState()
9585     * @see #setDuplicateParentStateEnabled(boolean)
9586     */
9587    public boolean isDuplicateParentStateEnabled() {
9588        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9589    }
9590
9591    /**
9592     * <p>Specifies the type of layer backing this view. The layer can be
9593     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9594     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
9595     *
9596     * <p>A layer is associated with an optional {@link android.graphics.Paint}
9597     * instance that controls how the layer is composed on screen. The following
9598     * properties of the paint are taken into account when composing the layer:</p>
9599     * <ul>
9600     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
9601     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
9602     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
9603     * </ul>
9604     *
9605     * <p>If this view has an alpha value set to < 1.0 by calling
9606     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
9607     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
9608     * equivalent to setting a hardware layer on this view and providing a paint with
9609     * the desired alpha value.<p>
9610     *
9611     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
9612     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
9613     * for more information on when and how to use layers.</p>
9614     *
9615     * @param layerType The ype of layer to use with this view, must be one of
9616     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9617     *        {@link #LAYER_TYPE_HARDWARE}
9618     * @param paint The paint used to compose the layer. This argument is optional
9619     *        and can be null. It is ignored when the layer type is
9620     *        {@link #LAYER_TYPE_NONE}
9621     *
9622     * @see #getLayerType()
9623     * @see #LAYER_TYPE_NONE
9624     * @see #LAYER_TYPE_SOFTWARE
9625     * @see #LAYER_TYPE_HARDWARE
9626     * @see #setAlpha(float)
9627     *
9628     * @attr ref android.R.styleable#View_layerType
9629     */
9630    public void setLayerType(int layerType, Paint paint) {
9631        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
9632            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
9633                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
9634        }
9635
9636        if (layerType == mLayerType) {
9637            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
9638                mLayerPaint = paint == null ? new Paint() : paint;
9639                invalidateParentCaches();
9640                invalidate(true);
9641            }
9642            return;
9643        }
9644
9645        // Destroy any previous software drawing cache if needed
9646        switch (mLayerType) {
9647            case LAYER_TYPE_HARDWARE:
9648                destroyLayer();
9649                // fall through - unaccelerated views may use software layer mechanism instead
9650            case LAYER_TYPE_SOFTWARE:
9651                destroyDrawingCache();
9652                break;
9653            default:
9654                break;
9655        }
9656
9657        mLayerType = layerType;
9658        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
9659        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
9660        mLocalDirtyRect = layerDisabled ? null : new Rect();
9661
9662        invalidateParentCaches();
9663        invalidate(true);
9664    }
9665
9666    /**
9667     * Indicates what type of layer is currently associated with this view. By default
9668     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
9669     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
9670     * for more information on the different types of layers.
9671     *
9672     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9673     *         {@link #LAYER_TYPE_HARDWARE}
9674     *
9675     * @see #setLayerType(int, android.graphics.Paint)
9676     * @see #buildLayer()
9677     * @see #LAYER_TYPE_NONE
9678     * @see #LAYER_TYPE_SOFTWARE
9679     * @see #LAYER_TYPE_HARDWARE
9680     */
9681    public int getLayerType() {
9682        return mLayerType;
9683    }
9684
9685    /**
9686     * Forces this view's layer to be created and this view to be rendered
9687     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
9688     * invoking this method will have no effect.
9689     *
9690     * This method can for instance be used to render a view into its layer before
9691     * starting an animation. If this view is complex, rendering into the layer
9692     * before starting the animation will avoid skipping frames.
9693     *
9694     * @throws IllegalStateException If this view is not attached to a window
9695     *
9696     * @see #setLayerType(int, android.graphics.Paint)
9697     */
9698    public void buildLayer() {
9699        if (mLayerType == LAYER_TYPE_NONE) return;
9700
9701        if (mAttachInfo == null) {
9702            throw new IllegalStateException("This view must be attached to a window first");
9703        }
9704
9705        switch (mLayerType) {
9706            case LAYER_TYPE_HARDWARE:
9707                getHardwareLayer();
9708                break;
9709            case LAYER_TYPE_SOFTWARE:
9710                buildDrawingCache(true);
9711                break;
9712        }
9713    }
9714
9715    /**
9716     * <p>Returns a hardware layer that can be used to draw this view again
9717     * without executing its draw method.</p>
9718     *
9719     * @return A HardwareLayer ready to render, or null if an error occurred.
9720     */
9721    HardwareLayer getHardwareLayer() {
9722        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
9723                !mAttachInfo.mHardwareRenderer.isEnabled()) {
9724            return null;
9725        }
9726
9727        final int width = mRight - mLeft;
9728        final int height = mBottom - mTop;
9729
9730        if (width == 0 || height == 0) {
9731            return null;
9732        }
9733
9734        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
9735            if (mHardwareLayer == null) {
9736                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
9737                        width, height, isOpaque());
9738                mLocalDirtyRect.setEmpty();
9739            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
9740                mHardwareLayer.resize(width, height);
9741                mLocalDirtyRect.setEmpty();
9742            }
9743
9744            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
9745            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
9746            mAttachInfo.mHardwareCanvas = canvas;
9747            try {
9748                canvas.setViewport(width, height);
9749                canvas.onPreDraw(mLocalDirtyRect);
9750                mLocalDirtyRect.setEmpty();
9751
9752                final int restoreCount = canvas.save();
9753
9754                computeScroll();
9755                canvas.translate(-mScrollX, -mScrollY);
9756
9757                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9758
9759                // Fast path for layouts with no backgrounds
9760                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9761                    mPrivateFlags &= ~DIRTY_MASK;
9762                    dispatchDraw(canvas);
9763                } else {
9764                    draw(canvas);
9765                }
9766
9767                canvas.restoreToCount(restoreCount);
9768            } finally {
9769                canvas.onPostDraw();
9770                mHardwareLayer.end(currentCanvas);
9771                mAttachInfo.mHardwareCanvas = currentCanvas;
9772            }
9773        }
9774
9775        return mHardwareLayer;
9776    }
9777
9778    boolean destroyLayer() {
9779        if (mHardwareLayer != null) {
9780            mHardwareLayer.destroy();
9781            mHardwareLayer = null;
9782            return true;
9783        }
9784        return false;
9785    }
9786
9787    /**
9788     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
9789     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
9790     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
9791     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
9792     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
9793     * null.</p>
9794     *
9795     * <p>Enabling the drawing cache is similar to
9796     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
9797     * acceleration is turned off. When hardware acceleration is turned on, enabling the
9798     * drawing cache has no effect on rendering because the system uses a different mechanism
9799     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
9800     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
9801     * for information on how to enable software and hardware layers.</p>
9802     *
9803     * <p>This API can be used to manually generate
9804     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
9805     * {@link #getDrawingCache()}.</p>
9806     *
9807     * @param enabled true to enable the drawing cache, false otherwise
9808     *
9809     * @see #isDrawingCacheEnabled()
9810     * @see #getDrawingCache()
9811     * @see #buildDrawingCache()
9812     * @see #setLayerType(int, android.graphics.Paint)
9813     */
9814    public void setDrawingCacheEnabled(boolean enabled) {
9815        mCachingFailed = false;
9816        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
9817    }
9818
9819    /**
9820     * <p>Indicates whether the drawing cache is enabled for this view.</p>
9821     *
9822     * @return true if the drawing cache is enabled
9823     *
9824     * @see #setDrawingCacheEnabled(boolean)
9825     * @see #getDrawingCache()
9826     */
9827    @ViewDebug.ExportedProperty(category = "drawing")
9828    public boolean isDrawingCacheEnabled() {
9829        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
9830    }
9831
9832    /**
9833     * Debugging utility which recursively outputs the dirty state of a view and its
9834     * descendants.
9835     *
9836     * @hide
9837     */
9838    @SuppressWarnings({"UnusedDeclaration"})
9839    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
9840        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
9841                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
9842                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
9843                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
9844        if (clear) {
9845            mPrivateFlags &= clearMask;
9846        }
9847        if (this instanceof ViewGroup) {
9848            ViewGroup parent = (ViewGroup) this;
9849            final int count = parent.getChildCount();
9850            for (int i = 0; i < count; i++) {
9851                final View child = parent.getChildAt(i);
9852                child.outputDirtyFlags(indent + "  ", clear, clearMask);
9853            }
9854        }
9855    }
9856
9857    /**
9858     * This method is used by ViewGroup to cause its children to restore or recreate their
9859     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
9860     * to recreate its own display list, which would happen if it went through the normal
9861     * draw/dispatchDraw mechanisms.
9862     *
9863     * @hide
9864     */
9865    protected void dispatchGetDisplayList() {}
9866
9867    /**
9868     * A view that is not attached or hardware accelerated cannot create a display list.
9869     * This method checks these conditions and returns the appropriate result.
9870     *
9871     * @return true if view has the ability to create a display list, false otherwise.
9872     *
9873     * @hide
9874     */
9875    public boolean canHaveDisplayList() {
9876        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
9877    }
9878
9879    /**
9880     * <p>Returns a display list that can be used to draw this view again
9881     * without executing its draw method.</p>
9882     *
9883     * @return A DisplayList ready to replay, or null if caching is not enabled.
9884     *
9885     * @hide
9886     */
9887    public DisplayList getDisplayList() {
9888        if (!canHaveDisplayList()) {
9889            return null;
9890        }
9891
9892        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
9893                mDisplayList == null || !mDisplayList.isValid() ||
9894                mRecreateDisplayList)) {
9895            // Don't need to recreate the display list, just need to tell our
9896            // children to restore/recreate theirs
9897            if (mDisplayList != null && mDisplayList.isValid() &&
9898                    !mRecreateDisplayList) {
9899                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9900                mPrivateFlags &= ~DIRTY_MASK;
9901                dispatchGetDisplayList();
9902
9903                return mDisplayList;
9904            }
9905
9906            // If we got here, we're recreating it. Mark it as such to ensure that
9907            // we copy in child display lists into ours in drawChild()
9908            mRecreateDisplayList = true;
9909            if (mDisplayList == null) {
9910                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
9911                // If we're creating a new display list, make sure our parent gets invalidated
9912                // since they will need to recreate their display list to account for this
9913                // new child display list.
9914                invalidateParentCaches();
9915            }
9916
9917            final HardwareCanvas canvas = mDisplayList.start();
9918            try {
9919                int width = mRight - mLeft;
9920                int height = mBottom - mTop;
9921
9922                canvas.setViewport(width, height);
9923                // The dirty rect should always be null for a display list
9924                canvas.onPreDraw(null);
9925
9926                final int restoreCount = canvas.save();
9927
9928                computeScroll();
9929                canvas.translate(-mScrollX, -mScrollY);
9930                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9931                mPrivateFlags &= ~DIRTY_MASK;
9932
9933                // Fast path for layouts with no backgrounds
9934                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
9935                    dispatchDraw(canvas);
9936                } else {
9937                    draw(canvas);
9938                }
9939
9940                canvas.restoreToCount(restoreCount);
9941            } finally {
9942                canvas.onPostDraw();
9943
9944                mDisplayList.end();
9945            }
9946        } else {
9947            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
9948            mPrivateFlags &= ~DIRTY_MASK;
9949        }
9950
9951        return mDisplayList;
9952    }
9953
9954    /**
9955     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
9956     *
9957     * @return A non-scaled bitmap representing this view or null if cache is disabled.
9958     *
9959     * @see #getDrawingCache(boolean)
9960     */
9961    public Bitmap getDrawingCache() {
9962        return getDrawingCache(false);
9963    }
9964
9965    /**
9966     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
9967     * is null when caching is disabled. If caching is enabled and the cache is not ready,
9968     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
9969     * draw from the cache when the cache is enabled. To benefit from the cache, you must
9970     * request the drawing cache by calling this method and draw it on screen if the
9971     * returned bitmap is not null.</p>
9972     *
9973     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
9974     * this method will create a bitmap of the same size as this view. Because this bitmap
9975     * will be drawn scaled by the parent ViewGroup, the result on screen might show
9976     * scaling artifacts. To avoid such artifacts, you should call this method by setting
9977     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
9978     * size than the view. This implies that your application must be able to handle this
9979     * size.</p>
9980     *
9981     * @param autoScale Indicates whether the generated bitmap should be scaled based on
9982     *        the current density of the screen when the application is in compatibility
9983     *        mode.
9984     *
9985     * @return A bitmap representing this view or null if cache is disabled.
9986     *
9987     * @see #setDrawingCacheEnabled(boolean)
9988     * @see #isDrawingCacheEnabled()
9989     * @see #buildDrawingCache(boolean)
9990     * @see #destroyDrawingCache()
9991     */
9992    public Bitmap getDrawingCache(boolean autoScale) {
9993        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
9994            return null;
9995        }
9996        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
9997            buildDrawingCache(autoScale);
9998        }
9999        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10000    }
10001
10002    /**
10003     * <p>Frees the resources used by the drawing cache. If you call
10004     * {@link #buildDrawingCache()} manually without calling
10005     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10006     * should cleanup the cache with this method afterwards.</p>
10007     *
10008     * @see #setDrawingCacheEnabled(boolean)
10009     * @see #buildDrawingCache()
10010     * @see #getDrawingCache()
10011     */
10012    public void destroyDrawingCache() {
10013        if (mDrawingCache != null) {
10014            mDrawingCache.recycle();
10015            mDrawingCache = null;
10016        }
10017        if (mUnscaledDrawingCache != null) {
10018            mUnscaledDrawingCache.recycle();
10019            mUnscaledDrawingCache = null;
10020        }
10021    }
10022
10023    /**
10024     * Setting a solid background color for the drawing cache's bitmaps will improve
10025     * perfromance and memory usage. Note, though that this should only be used if this
10026     * view will always be drawn on top of a solid color.
10027     *
10028     * @param color The background color to use for the drawing cache's bitmap
10029     *
10030     * @see #setDrawingCacheEnabled(boolean)
10031     * @see #buildDrawingCache()
10032     * @see #getDrawingCache()
10033     */
10034    public void setDrawingCacheBackgroundColor(int color) {
10035        if (color != mDrawingCacheBackgroundColor) {
10036            mDrawingCacheBackgroundColor = color;
10037            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10038        }
10039    }
10040
10041    /**
10042     * @see #setDrawingCacheBackgroundColor(int)
10043     *
10044     * @return The background color to used for the drawing cache's bitmap
10045     */
10046    public int getDrawingCacheBackgroundColor() {
10047        return mDrawingCacheBackgroundColor;
10048    }
10049
10050    /**
10051     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10052     *
10053     * @see #buildDrawingCache(boolean)
10054     */
10055    public void buildDrawingCache() {
10056        buildDrawingCache(false);
10057    }
10058
10059    /**
10060     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10061     *
10062     * <p>If you call {@link #buildDrawingCache()} manually without calling
10063     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10064     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10065     *
10066     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10067     * this method will create a bitmap of the same size as this view. Because this bitmap
10068     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10069     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10070     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10071     * size than the view. This implies that your application must be able to handle this
10072     * size.</p>
10073     *
10074     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10075     * you do not need the drawing cache bitmap, calling this method will increase memory
10076     * usage and cause the view to be rendered in software once, thus negatively impacting
10077     * performance.</p>
10078     *
10079     * @see #getDrawingCache()
10080     * @see #destroyDrawingCache()
10081     */
10082    public void buildDrawingCache(boolean autoScale) {
10083        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10084                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10085            mCachingFailed = false;
10086
10087            if (ViewDebug.TRACE_HIERARCHY) {
10088                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10089            }
10090
10091            int width = mRight - mLeft;
10092            int height = mBottom - mTop;
10093
10094            final AttachInfo attachInfo = mAttachInfo;
10095            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10096
10097            if (autoScale && scalingRequired) {
10098                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10099                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10100            }
10101
10102            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10103            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10104            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10105
10106            if (width <= 0 || height <= 0 ||
10107                     // Projected bitmap size in bytes
10108                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10109                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10110                destroyDrawingCache();
10111                mCachingFailed = true;
10112                return;
10113            }
10114
10115            boolean clear = true;
10116            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10117
10118            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10119                Bitmap.Config quality;
10120                if (!opaque) {
10121                    // Never pick ARGB_4444 because it looks awful
10122                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10123                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10124                        case DRAWING_CACHE_QUALITY_AUTO:
10125                            quality = Bitmap.Config.ARGB_8888;
10126                            break;
10127                        case DRAWING_CACHE_QUALITY_LOW:
10128                            quality = Bitmap.Config.ARGB_8888;
10129                            break;
10130                        case DRAWING_CACHE_QUALITY_HIGH:
10131                            quality = Bitmap.Config.ARGB_8888;
10132                            break;
10133                        default:
10134                            quality = Bitmap.Config.ARGB_8888;
10135                            break;
10136                    }
10137                } else {
10138                    // Optimization for translucent windows
10139                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10140                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10141                }
10142
10143                // Try to cleanup memory
10144                if (bitmap != null) bitmap.recycle();
10145
10146                try {
10147                    bitmap = Bitmap.createBitmap(width, height, quality);
10148                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10149                    if (autoScale) {
10150                        mDrawingCache = bitmap;
10151                    } else {
10152                        mUnscaledDrawingCache = bitmap;
10153                    }
10154                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10155                } catch (OutOfMemoryError e) {
10156                    // If there is not enough memory to create the bitmap cache, just
10157                    // ignore the issue as bitmap caches are not required to draw the
10158                    // view hierarchy
10159                    if (autoScale) {
10160                        mDrawingCache = null;
10161                    } else {
10162                        mUnscaledDrawingCache = null;
10163                    }
10164                    mCachingFailed = true;
10165                    return;
10166                }
10167
10168                clear = drawingCacheBackgroundColor != 0;
10169            }
10170
10171            Canvas canvas;
10172            if (attachInfo != null) {
10173                canvas = attachInfo.mCanvas;
10174                if (canvas == null) {
10175                    canvas = new Canvas();
10176                }
10177                canvas.setBitmap(bitmap);
10178                // Temporarily clobber the cached Canvas in case one of our children
10179                // is also using a drawing cache. Without this, the children would
10180                // steal the canvas by attaching their own bitmap to it and bad, bad
10181                // thing would happen (invisible views, corrupted drawings, etc.)
10182                attachInfo.mCanvas = null;
10183            } else {
10184                // This case should hopefully never or seldom happen
10185                canvas = new Canvas(bitmap);
10186            }
10187
10188            if (clear) {
10189                bitmap.eraseColor(drawingCacheBackgroundColor);
10190            }
10191
10192            computeScroll();
10193            final int restoreCount = canvas.save();
10194
10195            if (autoScale && scalingRequired) {
10196                final float scale = attachInfo.mApplicationScale;
10197                canvas.scale(scale, scale);
10198            }
10199
10200            canvas.translate(-mScrollX, -mScrollY);
10201
10202            mPrivateFlags |= DRAWN;
10203            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10204                    mLayerType != LAYER_TYPE_NONE) {
10205                mPrivateFlags |= DRAWING_CACHE_VALID;
10206            }
10207
10208            // Fast path for layouts with no backgrounds
10209            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10210                if (ViewDebug.TRACE_HIERARCHY) {
10211                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10212                }
10213                mPrivateFlags &= ~DIRTY_MASK;
10214                dispatchDraw(canvas);
10215            } else {
10216                draw(canvas);
10217            }
10218
10219            canvas.restoreToCount(restoreCount);
10220
10221            if (attachInfo != null) {
10222                // Restore the cached Canvas for our siblings
10223                attachInfo.mCanvas = canvas;
10224            }
10225        }
10226    }
10227
10228    /**
10229     * Create a snapshot of the view into a bitmap.  We should probably make
10230     * some form of this public, but should think about the API.
10231     */
10232    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10233        int width = mRight - mLeft;
10234        int height = mBottom - mTop;
10235
10236        final AttachInfo attachInfo = mAttachInfo;
10237        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10238        width = (int) ((width * scale) + 0.5f);
10239        height = (int) ((height * scale) + 0.5f);
10240
10241        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10242        if (bitmap == null) {
10243            throw new OutOfMemoryError();
10244        }
10245
10246        bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10247
10248        Canvas canvas;
10249        if (attachInfo != null) {
10250            canvas = attachInfo.mCanvas;
10251            if (canvas == null) {
10252                canvas = new Canvas();
10253            }
10254            canvas.setBitmap(bitmap);
10255            // Temporarily clobber the cached Canvas in case one of our children
10256            // is also using a drawing cache. Without this, the children would
10257            // steal the canvas by attaching their own bitmap to it and bad, bad
10258            // things would happen (invisible views, corrupted drawings, etc.)
10259            attachInfo.mCanvas = null;
10260        } else {
10261            // This case should hopefully never or seldom happen
10262            canvas = new Canvas(bitmap);
10263        }
10264
10265        if ((backgroundColor & 0xff000000) != 0) {
10266            bitmap.eraseColor(backgroundColor);
10267        }
10268
10269        computeScroll();
10270        final int restoreCount = canvas.save();
10271        canvas.scale(scale, scale);
10272        canvas.translate(-mScrollX, -mScrollY);
10273
10274        // Temporarily remove the dirty mask
10275        int flags = mPrivateFlags;
10276        mPrivateFlags &= ~DIRTY_MASK;
10277
10278        // Fast path for layouts with no backgrounds
10279        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10280            dispatchDraw(canvas);
10281        } else {
10282            draw(canvas);
10283        }
10284
10285        mPrivateFlags = flags;
10286
10287        canvas.restoreToCount(restoreCount);
10288
10289        if (attachInfo != null) {
10290            // Restore the cached Canvas for our siblings
10291            attachInfo.mCanvas = canvas;
10292        }
10293
10294        return bitmap;
10295    }
10296
10297    /**
10298     * Indicates whether this View is currently in edit mode. A View is usually
10299     * in edit mode when displayed within a developer tool. For instance, if
10300     * this View is being drawn by a visual user interface builder, this method
10301     * should return true.
10302     *
10303     * Subclasses should check the return value of this method to provide
10304     * different behaviors if their normal behavior might interfere with the
10305     * host environment. For instance: the class spawns a thread in its
10306     * constructor, the drawing code relies on device-specific features, etc.
10307     *
10308     * This method is usually checked in the drawing code of custom widgets.
10309     *
10310     * @return True if this View is in edit mode, false otherwise.
10311     */
10312    public boolean isInEditMode() {
10313        return false;
10314    }
10315
10316    /**
10317     * If the View draws content inside its padding and enables fading edges,
10318     * it needs to support padding offsets. Padding offsets are added to the
10319     * fading edges to extend the length of the fade so that it covers pixels
10320     * drawn inside the padding.
10321     *
10322     * Subclasses of this class should override this method if they need
10323     * to draw content inside the padding.
10324     *
10325     * @return True if padding offset must be applied, false otherwise.
10326     *
10327     * @see #getLeftPaddingOffset()
10328     * @see #getRightPaddingOffset()
10329     * @see #getTopPaddingOffset()
10330     * @see #getBottomPaddingOffset()
10331     *
10332     * @since CURRENT
10333     */
10334    protected boolean isPaddingOffsetRequired() {
10335        return false;
10336    }
10337
10338    /**
10339     * Amount by which to extend the left fading region. Called only when
10340     * {@link #isPaddingOffsetRequired()} returns true.
10341     *
10342     * @return The left padding offset in pixels.
10343     *
10344     * @see #isPaddingOffsetRequired()
10345     *
10346     * @since CURRENT
10347     */
10348    protected int getLeftPaddingOffset() {
10349        return 0;
10350    }
10351
10352    /**
10353     * Amount by which to extend the right fading region. Called only when
10354     * {@link #isPaddingOffsetRequired()} returns true.
10355     *
10356     * @return The right padding offset in pixels.
10357     *
10358     * @see #isPaddingOffsetRequired()
10359     *
10360     * @since CURRENT
10361     */
10362    protected int getRightPaddingOffset() {
10363        return 0;
10364    }
10365
10366    /**
10367     * Amount by which to extend the top fading region. Called only when
10368     * {@link #isPaddingOffsetRequired()} returns true.
10369     *
10370     * @return The top padding offset in pixels.
10371     *
10372     * @see #isPaddingOffsetRequired()
10373     *
10374     * @since CURRENT
10375     */
10376    protected int getTopPaddingOffset() {
10377        return 0;
10378    }
10379
10380    /**
10381     * Amount by which to extend the bottom fading region. Called only when
10382     * {@link #isPaddingOffsetRequired()} returns true.
10383     *
10384     * @return The bottom padding offset in pixels.
10385     *
10386     * @see #isPaddingOffsetRequired()
10387     *
10388     * @since CURRENT
10389     */
10390    protected int getBottomPaddingOffset() {
10391        return 0;
10392    }
10393
10394    /**
10395     * @hide
10396     * @param offsetRequired
10397     */
10398    protected int getFadeTop(boolean offsetRequired) {
10399        int top = mPaddingTop;
10400        if (offsetRequired) top += getTopPaddingOffset();
10401        return top;
10402    }
10403
10404    /**
10405     * @hide
10406     * @param offsetRequired
10407     */
10408    protected int getFadeHeight(boolean offsetRequired) {
10409        int padding = mPaddingTop;
10410        if (offsetRequired) padding += getTopPaddingOffset();
10411        return mBottom - mTop - mPaddingBottom - padding;
10412    }
10413
10414    /**
10415     * <p>Indicates whether this view is attached to an hardware accelerated
10416     * window or not.</p>
10417     *
10418     * <p>Even if this method returns true, it does not mean that every call
10419     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10420     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10421     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10422     * window is hardware accelerated,
10423     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10424     * return false, and this method will return true.</p>
10425     *
10426     * @return True if the view is attached to a window and the window is
10427     *         hardware accelerated; false in any other case.
10428     */
10429    public boolean isHardwareAccelerated() {
10430        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10431    }
10432
10433    /**
10434     * Manually render this view (and all of its children) to the given Canvas.
10435     * The view must have already done a full layout before this function is
10436     * called.  When implementing a view, implement
10437     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
10438     * If you do need to override this method, call the superclass version.
10439     *
10440     * @param canvas The Canvas to which the View is rendered.
10441     */
10442    public void draw(Canvas canvas) {
10443        if (ViewDebug.TRACE_HIERARCHY) {
10444            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10445        }
10446
10447        final int privateFlags = mPrivateFlags;
10448        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
10449                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
10450        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
10451
10452        /*
10453         * Draw traversal performs several drawing steps which must be executed
10454         * in the appropriate order:
10455         *
10456         *      1. Draw the background
10457         *      2. If necessary, save the canvas' layers to prepare for fading
10458         *      3. Draw view's content
10459         *      4. Draw children
10460         *      5. If necessary, draw the fading edges and restore layers
10461         *      6. Draw decorations (scrollbars for instance)
10462         */
10463
10464        // Step 1, draw the background, if needed
10465        int saveCount;
10466
10467        if (!dirtyOpaque) {
10468            final Drawable background = mBGDrawable;
10469            if (background != null) {
10470                final int scrollX = mScrollX;
10471                final int scrollY = mScrollY;
10472
10473                if (mBackgroundSizeChanged) {
10474                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
10475                    mBackgroundSizeChanged = false;
10476                }
10477
10478                if ((scrollX | scrollY) == 0) {
10479                    background.draw(canvas);
10480                } else {
10481                    canvas.translate(scrollX, scrollY);
10482                    background.draw(canvas);
10483                    canvas.translate(-scrollX, -scrollY);
10484                }
10485            }
10486        }
10487
10488        // skip step 2 & 5 if possible (common case)
10489        final int viewFlags = mViewFlags;
10490        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
10491        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
10492        if (!verticalEdges && !horizontalEdges) {
10493            // Step 3, draw the content
10494            if (!dirtyOpaque) onDraw(canvas);
10495
10496            // Step 4, draw the children
10497            dispatchDraw(canvas);
10498
10499            // Step 6, draw decorations (scrollbars)
10500            onDrawScrollBars(canvas);
10501
10502            // we're done...
10503            return;
10504        }
10505
10506        /*
10507         * Here we do the full fledged routine...
10508         * (this is an uncommon case where speed matters less,
10509         * this is why we repeat some of the tests that have been
10510         * done above)
10511         */
10512
10513        boolean drawTop = false;
10514        boolean drawBottom = false;
10515        boolean drawLeft = false;
10516        boolean drawRight = false;
10517
10518        float topFadeStrength = 0.0f;
10519        float bottomFadeStrength = 0.0f;
10520        float leftFadeStrength = 0.0f;
10521        float rightFadeStrength = 0.0f;
10522
10523        // Step 2, save the canvas' layers
10524        int paddingLeft = mPaddingLeft;
10525
10526        final boolean offsetRequired = isPaddingOffsetRequired();
10527        if (offsetRequired) {
10528            paddingLeft += getLeftPaddingOffset();
10529        }
10530
10531        int left = mScrollX + paddingLeft;
10532        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
10533        int top = mScrollY + getFadeTop(offsetRequired);
10534        int bottom = top + getFadeHeight(offsetRequired);
10535
10536        if (offsetRequired) {
10537            right += getRightPaddingOffset();
10538            bottom += getBottomPaddingOffset();
10539        }
10540
10541        final ScrollabilityCache scrollabilityCache = mScrollCache;
10542        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
10543        int length = (int) fadeHeight;
10544
10545        // clip the fade length if top and bottom fades overlap
10546        // overlapping fades produce odd-looking artifacts
10547        if (verticalEdges && (top + length > bottom - length)) {
10548            length = (bottom - top) / 2;
10549        }
10550
10551        // also clip horizontal fades if necessary
10552        if (horizontalEdges && (left + length > right - length)) {
10553            length = (right - left) / 2;
10554        }
10555
10556        if (verticalEdges) {
10557            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
10558            drawTop = topFadeStrength * fadeHeight > 1.0f;
10559            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
10560            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
10561        }
10562
10563        if (horizontalEdges) {
10564            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
10565            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
10566            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
10567            drawRight = rightFadeStrength * fadeHeight > 1.0f;
10568        }
10569
10570        saveCount = canvas.getSaveCount();
10571
10572        int solidColor = getSolidColor();
10573        if (solidColor == 0) {
10574            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
10575
10576            if (drawTop) {
10577                canvas.saveLayer(left, top, right, top + length, null, flags);
10578            }
10579
10580            if (drawBottom) {
10581                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
10582            }
10583
10584            if (drawLeft) {
10585                canvas.saveLayer(left, top, left + length, bottom, null, flags);
10586            }
10587
10588            if (drawRight) {
10589                canvas.saveLayer(right - length, top, right, bottom, null, flags);
10590            }
10591        } else {
10592            scrollabilityCache.setFadeColor(solidColor);
10593        }
10594
10595        // Step 3, draw the content
10596        if (!dirtyOpaque) onDraw(canvas);
10597
10598        // Step 4, draw the children
10599        dispatchDraw(canvas);
10600
10601        // Step 5, draw the fade effect and restore layers
10602        final Paint p = scrollabilityCache.paint;
10603        final Matrix matrix = scrollabilityCache.matrix;
10604        final Shader fade = scrollabilityCache.shader;
10605
10606        if (drawTop) {
10607            matrix.setScale(1, fadeHeight * topFadeStrength);
10608            matrix.postTranslate(left, top);
10609            fade.setLocalMatrix(matrix);
10610            canvas.drawRect(left, top, right, top + length, p);
10611        }
10612
10613        if (drawBottom) {
10614            matrix.setScale(1, fadeHeight * bottomFadeStrength);
10615            matrix.postRotate(180);
10616            matrix.postTranslate(left, bottom);
10617            fade.setLocalMatrix(matrix);
10618            canvas.drawRect(left, bottom - length, right, bottom, p);
10619        }
10620
10621        if (drawLeft) {
10622            matrix.setScale(1, fadeHeight * leftFadeStrength);
10623            matrix.postRotate(-90);
10624            matrix.postTranslate(left, top);
10625            fade.setLocalMatrix(matrix);
10626            canvas.drawRect(left, top, left + length, bottom, p);
10627        }
10628
10629        if (drawRight) {
10630            matrix.setScale(1, fadeHeight * rightFadeStrength);
10631            matrix.postRotate(90);
10632            matrix.postTranslate(right, top);
10633            fade.setLocalMatrix(matrix);
10634            canvas.drawRect(right - length, top, right, bottom, p);
10635        }
10636
10637        canvas.restoreToCount(saveCount);
10638
10639        // Step 6, draw decorations (scrollbars)
10640        onDrawScrollBars(canvas);
10641    }
10642
10643    /**
10644     * Override this if your view is known to always be drawn on top of a solid color background,
10645     * and needs to draw fading edges. Returning a non-zero color enables the view system to
10646     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
10647     * should be set to 0xFF.
10648     *
10649     * @see #setVerticalFadingEdgeEnabled(boolean)
10650     * @see #setHorizontalFadingEdgeEnabled(boolean)
10651     *
10652     * @return The known solid color background for this view, or 0 if the color may vary
10653     */
10654    @ViewDebug.ExportedProperty(category = "drawing")
10655    public int getSolidColor() {
10656        return 0;
10657    }
10658
10659    /**
10660     * Build a human readable string representation of the specified view flags.
10661     *
10662     * @param flags the view flags to convert to a string
10663     * @return a String representing the supplied flags
10664     */
10665    private static String printFlags(int flags) {
10666        String output = "";
10667        int numFlags = 0;
10668        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
10669            output += "TAKES_FOCUS";
10670            numFlags++;
10671        }
10672
10673        switch (flags & VISIBILITY_MASK) {
10674        case INVISIBLE:
10675            if (numFlags > 0) {
10676                output += " ";
10677            }
10678            output += "INVISIBLE";
10679            // USELESS HERE numFlags++;
10680            break;
10681        case GONE:
10682            if (numFlags > 0) {
10683                output += " ";
10684            }
10685            output += "GONE";
10686            // USELESS HERE numFlags++;
10687            break;
10688        default:
10689            break;
10690        }
10691        return output;
10692    }
10693
10694    /**
10695     * Build a human readable string representation of the specified private
10696     * view flags.
10697     *
10698     * @param privateFlags the private view flags to convert to a string
10699     * @return a String representing the supplied flags
10700     */
10701    private static String printPrivateFlags(int privateFlags) {
10702        String output = "";
10703        int numFlags = 0;
10704
10705        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
10706            output += "WANTS_FOCUS";
10707            numFlags++;
10708        }
10709
10710        if ((privateFlags & FOCUSED) == FOCUSED) {
10711            if (numFlags > 0) {
10712                output += " ";
10713            }
10714            output += "FOCUSED";
10715            numFlags++;
10716        }
10717
10718        if ((privateFlags & SELECTED) == SELECTED) {
10719            if (numFlags > 0) {
10720                output += " ";
10721            }
10722            output += "SELECTED";
10723            numFlags++;
10724        }
10725
10726        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
10727            if (numFlags > 0) {
10728                output += " ";
10729            }
10730            output += "IS_ROOT_NAMESPACE";
10731            numFlags++;
10732        }
10733
10734        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
10735            if (numFlags > 0) {
10736                output += " ";
10737            }
10738            output += "HAS_BOUNDS";
10739            numFlags++;
10740        }
10741
10742        if ((privateFlags & DRAWN) == DRAWN) {
10743            if (numFlags > 0) {
10744                output += " ";
10745            }
10746            output += "DRAWN";
10747            // USELESS HERE numFlags++;
10748        }
10749        return output;
10750    }
10751
10752    /**
10753     * <p>Indicates whether or not this view's layout will be requested during
10754     * the next hierarchy layout pass.</p>
10755     *
10756     * @return true if the layout will be forced during next layout pass
10757     */
10758    public boolean isLayoutRequested() {
10759        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
10760    }
10761
10762    /**
10763     * Assign a size and position to a view and all of its
10764     * descendants
10765     *
10766     * <p>This is the second phase of the layout mechanism.
10767     * (The first is measuring). In this phase, each parent calls
10768     * layout on all of its children to position them.
10769     * This is typically done using the child measurements
10770     * that were stored in the measure pass().</p>
10771     *
10772     * <p>Derived classes should not override this method.
10773     * Derived classes with children should override
10774     * onLayout. In that method, they should
10775     * call layout on each of their children.</p>
10776     *
10777     * @param l Left position, relative to parent
10778     * @param t Top position, relative to parent
10779     * @param r Right position, relative to parent
10780     * @param b Bottom position, relative to parent
10781     */
10782    @SuppressWarnings({"unchecked"})
10783    public void layout(int l, int t, int r, int b) {
10784        int oldL = mLeft;
10785        int oldT = mTop;
10786        int oldB = mBottom;
10787        int oldR = mRight;
10788        boolean changed = setFrame(l, t, r, b);
10789        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
10790            if (ViewDebug.TRACE_HIERARCHY) {
10791                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
10792            }
10793
10794            onLayout(changed, l, t, r, b);
10795            mPrivateFlags &= ~LAYOUT_REQUIRED;
10796
10797            if (mOnLayoutChangeListeners != null) {
10798                ArrayList<OnLayoutChangeListener> listenersCopy =
10799                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
10800                int numListeners = listenersCopy.size();
10801                for (int i = 0; i < numListeners; ++i) {
10802                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
10803                }
10804            }
10805        }
10806        mPrivateFlags &= ~FORCE_LAYOUT;
10807    }
10808
10809    /**
10810     * Called from layout when this view should
10811     * assign a size and position to each of its children.
10812     *
10813     * Derived classes with children should override
10814     * this method and call layout on each of
10815     * their children.
10816     * @param changed This is a new size or position for this view
10817     * @param left Left position, relative to parent
10818     * @param top Top position, relative to parent
10819     * @param right Right position, relative to parent
10820     * @param bottom Bottom position, relative to parent
10821     */
10822    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
10823    }
10824
10825    /**
10826     * Assign a size and position to this view.
10827     *
10828     * This is called from layout.
10829     *
10830     * @param left Left position, relative to parent
10831     * @param top Top position, relative to parent
10832     * @param right Right position, relative to parent
10833     * @param bottom Bottom position, relative to parent
10834     * @return true if the new size and position are different than the
10835     *         previous ones
10836     * {@hide}
10837     */
10838    protected boolean setFrame(int left, int top, int right, int bottom) {
10839        boolean changed = false;
10840
10841        if (DBG) {
10842            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
10843                    + right + "," + bottom + ")");
10844        }
10845
10846        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
10847            changed = true;
10848
10849            // Remember our drawn bit
10850            int drawn = mPrivateFlags & DRAWN;
10851
10852            int oldWidth = mRight - mLeft;
10853            int oldHeight = mBottom - mTop;
10854            int newWidth = right - left;
10855            int newHeight = bottom - top;
10856            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
10857
10858            // Invalidate our old position
10859            invalidate(sizeChanged);
10860
10861            mLeft = left;
10862            mTop = top;
10863            mRight = right;
10864            mBottom = bottom;
10865
10866            mPrivateFlags |= HAS_BOUNDS;
10867
10868
10869            if (sizeChanged) {
10870                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
10871                    // A change in dimension means an auto-centered pivot point changes, too
10872                    mMatrixDirty = true;
10873                }
10874                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
10875            }
10876
10877            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
10878                // If we are visible, force the DRAWN bit to on so that
10879                // this invalidate will go through (at least to our parent).
10880                // This is because someone may have invalidated this view
10881                // before this call to setFrame came in, thereby clearing
10882                // the DRAWN bit.
10883                mPrivateFlags |= DRAWN;
10884                invalidate(sizeChanged);
10885                // parent display list may need to be recreated based on a change in the bounds
10886                // of any child
10887                invalidateParentCaches();
10888            }
10889
10890            // Reset drawn bit to original value (invalidate turns it off)
10891            mPrivateFlags |= drawn;
10892
10893            mBackgroundSizeChanged = true;
10894        }
10895        return changed;
10896    }
10897
10898    /**
10899     * Finalize inflating a view from XML.  This is called as the last phase
10900     * of inflation, after all child views have been added.
10901     *
10902     * <p>Even if the subclass overrides onFinishInflate, they should always be
10903     * sure to call the super method, so that we get called.
10904     */
10905    protected void onFinishInflate() {
10906    }
10907
10908    /**
10909     * Returns the resources associated with this view.
10910     *
10911     * @return Resources object.
10912     */
10913    public Resources getResources() {
10914        return mResources;
10915    }
10916
10917    /**
10918     * Invalidates the specified Drawable.
10919     *
10920     * @param drawable the drawable to invalidate
10921     */
10922    public void invalidateDrawable(Drawable drawable) {
10923        if (verifyDrawable(drawable)) {
10924            final Rect dirty = drawable.getBounds();
10925            final int scrollX = mScrollX;
10926            final int scrollY = mScrollY;
10927
10928            invalidate(dirty.left + scrollX, dirty.top + scrollY,
10929                    dirty.right + scrollX, dirty.bottom + scrollY);
10930        }
10931    }
10932
10933    /**
10934     * Schedules an action on a drawable to occur at a specified time.
10935     *
10936     * @param who the recipient of the action
10937     * @param what the action to run on the drawable
10938     * @param when the time at which the action must occur. Uses the
10939     *        {@link SystemClock#uptimeMillis} timebase.
10940     */
10941    public void scheduleDrawable(Drawable who, Runnable what, long when) {
10942        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
10943            mAttachInfo.mHandler.postAtTime(what, who, when);
10944        }
10945    }
10946
10947    /**
10948     * Cancels a scheduled action on a drawable.
10949     *
10950     * @param who the recipient of the action
10951     * @param what the action to cancel
10952     */
10953    public void unscheduleDrawable(Drawable who, Runnable what) {
10954        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
10955            mAttachInfo.mHandler.removeCallbacks(what, who);
10956        }
10957    }
10958
10959    /**
10960     * Unschedule any events associated with the given Drawable.  This can be
10961     * used when selecting a new Drawable into a view, so that the previous
10962     * one is completely unscheduled.
10963     *
10964     * @param who The Drawable to unschedule.
10965     *
10966     * @see #drawableStateChanged
10967     */
10968    public void unscheduleDrawable(Drawable who) {
10969        if (mAttachInfo != null) {
10970            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
10971        }
10972    }
10973
10974    /**
10975    * Return the layout direction of a given Drawable.
10976    *
10977    * @param who the Drawable to query
10978    *
10979    * @hide
10980    */
10981    public int getResolvedLayoutDirection(Drawable who) {
10982        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
10983    }
10984
10985    /**
10986     * If your view subclass is displaying its own Drawable objects, it should
10987     * override this function and return true for any Drawable it is
10988     * displaying.  This allows animations for those drawables to be
10989     * scheduled.
10990     *
10991     * <p>Be sure to call through to the super class when overriding this
10992     * function.
10993     *
10994     * @param who The Drawable to verify.  Return true if it is one you are
10995     *            displaying, else return the result of calling through to the
10996     *            super class.
10997     *
10998     * @return boolean If true than the Drawable is being displayed in the
10999     *         view; else false and it is not allowed to animate.
11000     *
11001     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11002     * @see #drawableStateChanged()
11003     */
11004    protected boolean verifyDrawable(Drawable who) {
11005        return who == mBGDrawable;
11006    }
11007
11008    /**
11009     * This function is called whenever the state of the view changes in such
11010     * a way that it impacts the state of drawables being shown.
11011     *
11012     * <p>Be sure to call through to the superclass when overriding this
11013     * function.
11014     *
11015     * @see Drawable#setState(int[])
11016     */
11017    protected void drawableStateChanged() {
11018        Drawable d = mBGDrawable;
11019        if (d != null && d.isStateful()) {
11020            d.setState(getDrawableState());
11021        }
11022    }
11023
11024    /**
11025     * Call this to force a view to update its drawable state. This will cause
11026     * drawableStateChanged to be called on this view. Views that are interested
11027     * in the new state should call getDrawableState.
11028     *
11029     * @see #drawableStateChanged
11030     * @see #getDrawableState
11031     */
11032    public void refreshDrawableState() {
11033        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11034        drawableStateChanged();
11035
11036        ViewParent parent = mParent;
11037        if (parent != null) {
11038            parent.childDrawableStateChanged(this);
11039        }
11040    }
11041
11042    /**
11043     * Return an array of resource IDs of the drawable states representing the
11044     * current state of the view.
11045     *
11046     * @return The current drawable state
11047     *
11048     * @see Drawable#setState(int[])
11049     * @see #drawableStateChanged()
11050     * @see #onCreateDrawableState(int)
11051     */
11052    public final int[] getDrawableState() {
11053        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11054            return mDrawableState;
11055        } else {
11056            mDrawableState = onCreateDrawableState(0);
11057            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11058            return mDrawableState;
11059        }
11060    }
11061
11062    /**
11063     * Generate the new {@link android.graphics.drawable.Drawable} state for
11064     * this view. This is called by the view
11065     * system when the cached Drawable state is determined to be invalid.  To
11066     * retrieve the current state, you should use {@link #getDrawableState}.
11067     *
11068     * @param extraSpace if non-zero, this is the number of extra entries you
11069     * would like in the returned array in which you can place your own
11070     * states.
11071     *
11072     * @return Returns an array holding the current {@link Drawable} state of
11073     * the view.
11074     *
11075     * @see #mergeDrawableStates(int[], int[])
11076     */
11077    protected int[] onCreateDrawableState(int extraSpace) {
11078        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11079                mParent instanceof View) {
11080            return ((View) mParent).onCreateDrawableState(extraSpace);
11081        }
11082
11083        int[] drawableState;
11084
11085        int privateFlags = mPrivateFlags;
11086
11087        int viewStateIndex = 0;
11088        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11089        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11090        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11091        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11092        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11093        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11094        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11095                HardwareRenderer.isAvailable()) {
11096            // This is set if HW acceleration is requested, even if the current
11097            // process doesn't allow it.  This is just to allow app preview
11098            // windows to better match their app.
11099            viewStateIndex |= VIEW_STATE_ACCELERATED;
11100        }
11101        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11102
11103        final int privateFlags2 = mPrivateFlags2;
11104        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11105        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11106
11107        drawableState = VIEW_STATE_SETS[viewStateIndex];
11108
11109        //noinspection ConstantIfStatement
11110        if (false) {
11111            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11112            Log.i("View", toString()
11113                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11114                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11115                    + " fo=" + hasFocus()
11116                    + " sl=" + ((privateFlags & SELECTED) != 0)
11117                    + " wf=" + hasWindowFocus()
11118                    + ": " + Arrays.toString(drawableState));
11119        }
11120
11121        if (extraSpace == 0) {
11122            return drawableState;
11123        }
11124
11125        final int[] fullState;
11126        if (drawableState != null) {
11127            fullState = new int[drawableState.length + extraSpace];
11128            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11129        } else {
11130            fullState = new int[extraSpace];
11131        }
11132
11133        return fullState;
11134    }
11135
11136    /**
11137     * Merge your own state values in <var>additionalState</var> into the base
11138     * state values <var>baseState</var> that were returned by
11139     * {@link #onCreateDrawableState(int)}.
11140     *
11141     * @param baseState The base state values returned by
11142     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11143     * own additional state values.
11144     *
11145     * @param additionalState The additional state values you would like
11146     * added to <var>baseState</var>; this array is not modified.
11147     *
11148     * @return As a convenience, the <var>baseState</var> array you originally
11149     * passed into the function is returned.
11150     *
11151     * @see #onCreateDrawableState(int)
11152     */
11153    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11154        final int N = baseState.length;
11155        int i = N - 1;
11156        while (i >= 0 && baseState[i] == 0) {
11157            i--;
11158        }
11159        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11160        return baseState;
11161    }
11162
11163    /**
11164     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
11165     * on all Drawable objects associated with this view.
11166     */
11167    public void jumpDrawablesToCurrentState() {
11168        if (mBGDrawable != null) {
11169            mBGDrawable.jumpToCurrentState();
11170        }
11171    }
11172
11173    /**
11174     * Sets the background color for this view.
11175     * @param color the color of the background
11176     */
11177    @RemotableViewMethod
11178    public void setBackgroundColor(int color) {
11179        if (mBGDrawable instanceof ColorDrawable) {
11180            ((ColorDrawable) mBGDrawable).setColor(color);
11181        } else {
11182            setBackgroundDrawable(new ColorDrawable(color));
11183        }
11184    }
11185
11186    /**
11187     * Set the background to a given resource. The resource should refer to
11188     * a Drawable object or 0 to remove the background.
11189     * @param resid The identifier of the resource.
11190     * @attr ref android.R.styleable#View_background
11191     */
11192    @RemotableViewMethod
11193    public void setBackgroundResource(int resid) {
11194        if (resid != 0 && resid == mBackgroundResource) {
11195            return;
11196        }
11197
11198        Drawable d= null;
11199        if (resid != 0) {
11200            d = mResources.getDrawable(resid);
11201        }
11202        setBackgroundDrawable(d);
11203
11204        mBackgroundResource = resid;
11205    }
11206
11207    /**
11208     * Set the background to a given Drawable, or remove the background. If the
11209     * background has padding, this View's padding is set to the background's
11210     * padding. However, when a background is removed, this View's padding isn't
11211     * touched. If setting the padding is desired, please use
11212     * {@link #setPadding(int, int, int, int)}.
11213     *
11214     * @param d The Drawable to use as the background, or null to remove the
11215     *        background
11216     */
11217    public void setBackgroundDrawable(Drawable d) {
11218        if (d == mBGDrawable) {
11219            return;
11220        }
11221
11222        boolean requestLayout = false;
11223
11224        mBackgroundResource = 0;
11225
11226        /*
11227         * Regardless of whether we're setting a new background or not, we want
11228         * to clear the previous drawable.
11229         */
11230        if (mBGDrawable != null) {
11231            mBGDrawable.setCallback(null);
11232            unscheduleDrawable(mBGDrawable);
11233        }
11234
11235        if (d != null) {
11236            Rect padding = sThreadLocal.get();
11237            if (padding == null) {
11238                padding = new Rect();
11239                sThreadLocal.set(padding);
11240            }
11241            if (d.getPadding(padding)) {
11242                switch (d.getResolvedLayoutDirectionSelf()) {
11243                    case LAYOUT_DIRECTION_RTL:
11244                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
11245                        break;
11246                    case LAYOUT_DIRECTION_LTR:
11247                    default:
11248                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
11249                }
11250            }
11251
11252            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
11253            // if it has a different minimum size, we should layout again
11254            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
11255                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
11256                requestLayout = true;
11257            }
11258
11259            d.setCallback(this);
11260            if (d.isStateful()) {
11261                d.setState(getDrawableState());
11262            }
11263            d.setVisible(getVisibility() == VISIBLE, false);
11264            mBGDrawable = d;
11265
11266            if ((mPrivateFlags & SKIP_DRAW) != 0) {
11267                mPrivateFlags &= ~SKIP_DRAW;
11268                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
11269                requestLayout = true;
11270            }
11271        } else {
11272            /* Remove the background */
11273            mBGDrawable = null;
11274
11275            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
11276                /*
11277                 * This view ONLY drew the background before and we're removing
11278                 * the background, so now it won't draw anything
11279                 * (hence we SKIP_DRAW)
11280                 */
11281                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
11282                mPrivateFlags |= SKIP_DRAW;
11283            }
11284
11285            /*
11286             * When the background is set, we try to apply its padding to this
11287             * View. When the background is removed, we don't touch this View's
11288             * padding. This is noted in the Javadocs. Hence, we don't need to
11289             * requestLayout(), the invalidate() below is sufficient.
11290             */
11291
11292            // The old background's minimum size could have affected this
11293            // View's layout, so let's requestLayout
11294            requestLayout = true;
11295        }
11296
11297        computeOpaqueFlags();
11298
11299        if (requestLayout) {
11300            requestLayout();
11301        }
11302
11303        mBackgroundSizeChanged = true;
11304        invalidate(true);
11305    }
11306
11307    /**
11308     * Gets the background drawable
11309     * @return The drawable used as the background for this view, if any.
11310     */
11311    public Drawable getBackground() {
11312        return mBGDrawable;
11313    }
11314
11315    /**
11316     * Sets the padding. The view may add on the space required to display
11317     * the scrollbars, depending on the style and visibility of the scrollbars.
11318     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
11319     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
11320     * from the values set in this call.
11321     *
11322     * @attr ref android.R.styleable#View_padding
11323     * @attr ref android.R.styleable#View_paddingBottom
11324     * @attr ref android.R.styleable#View_paddingLeft
11325     * @attr ref android.R.styleable#View_paddingRight
11326     * @attr ref android.R.styleable#View_paddingTop
11327     * @param left the left padding in pixels
11328     * @param top the top padding in pixels
11329     * @param right the right padding in pixels
11330     * @param bottom the bottom padding in pixels
11331     */
11332    public void setPadding(int left, int top, int right, int bottom) {
11333        boolean changed = false;
11334
11335        mUserPaddingRelative = false;
11336
11337        mUserPaddingLeft = left;
11338        mUserPaddingRight = right;
11339        mUserPaddingBottom = bottom;
11340
11341        final int viewFlags = mViewFlags;
11342
11343        // Common case is there are no scroll bars.
11344        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
11345            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
11346                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
11347                        ? 0 : getVerticalScrollbarWidth();
11348                switch (mVerticalScrollbarPosition) {
11349                    case SCROLLBAR_POSITION_DEFAULT:
11350                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11351                            left += offset;
11352                        } else {
11353                            right += offset;
11354                        }
11355                        break;
11356                    case SCROLLBAR_POSITION_RIGHT:
11357                        right += offset;
11358                        break;
11359                    case SCROLLBAR_POSITION_LEFT:
11360                        left += offset;
11361                        break;
11362                }
11363            }
11364            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
11365                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
11366                        ? 0 : getHorizontalScrollbarHeight();
11367            }
11368        }
11369
11370        if (mPaddingLeft != left) {
11371            changed = true;
11372            mPaddingLeft = left;
11373        }
11374        if (mPaddingTop != top) {
11375            changed = true;
11376            mPaddingTop = top;
11377        }
11378        if (mPaddingRight != right) {
11379            changed = true;
11380            mPaddingRight = right;
11381        }
11382        if (mPaddingBottom != bottom) {
11383            changed = true;
11384            mPaddingBottom = bottom;
11385        }
11386
11387        if (changed) {
11388            requestLayout();
11389        }
11390    }
11391
11392    /**
11393     * Sets the relative padding. The view may add on the space required to display
11394     * the scrollbars, depending on the style and visibility of the scrollbars.
11395     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
11396     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
11397     * from the values set in this call.
11398     *
11399     * @attr ref android.R.styleable#View_padding
11400     * @attr ref android.R.styleable#View_paddingBottom
11401     * @attr ref android.R.styleable#View_paddingStart
11402     * @attr ref android.R.styleable#View_paddingEnd
11403     * @attr ref android.R.styleable#View_paddingTop
11404     * @param start the start padding in pixels
11405     * @param top the top padding in pixels
11406     * @param end the end padding in pixels
11407     * @param bottom the bottom padding in pixels
11408     *
11409     * @hide
11410     */
11411    public void setPaddingRelative(int start, int top, int end, int bottom) {
11412        mUserPaddingRelative = true;
11413
11414        mUserPaddingStart = start;
11415        mUserPaddingEnd = end;
11416
11417        switch(getResolvedLayoutDirection()) {
11418            case LAYOUT_DIRECTION_RTL:
11419                setPadding(end, top, start, bottom);
11420                break;
11421            case LAYOUT_DIRECTION_LTR:
11422            default:
11423                setPadding(start, top, end, bottom);
11424        }
11425    }
11426
11427    /**
11428     * Returns the top padding of this view.
11429     *
11430     * @return the top padding in pixels
11431     */
11432    public int getPaddingTop() {
11433        return mPaddingTop;
11434    }
11435
11436    /**
11437     * Returns the bottom padding of this view. If there are inset and enabled
11438     * scrollbars, this value may include the space required to display the
11439     * scrollbars as well.
11440     *
11441     * @return the bottom padding in pixels
11442     */
11443    public int getPaddingBottom() {
11444        return mPaddingBottom;
11445    }
11446
11447    /**
11448     * Returns the left padding of this view. If there are inset and enabled
11449     * scrollbars, this value may include the space required to display the
11450     * scrollbars as well.
11451     *
11452     * @return the left padding in pixels
11453     */
11454    public int getPaddingLeft() {
11455        return mPaddingLeft;
11456    }
11457
11458    /**
11459     * Returns the start padding of this view. If there are inset and enabled
11460     * scrollbars, this value may include the space required to display the
11461     * scrollbars as well.
11462     *
11463     * @return the start padding in pixels
11464     *
11465     * @hide
11466     */
11467    public int getPaddingStart() {
11468        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11469                mPaddingRight : mPaddingLeft;
11470    }
11471
11472    /**
11473     * Returns the right padding of this view. If there are inset and enabled
11474     * scrollbars, this value may include the space required to display the
11475     * scrollbars as well.
11476     *
11477     * @return the right padding in pixels
11478     */
11479    public int getPaddingRight() {
11480        return mPaddingRight;
11481    }
11482
11483    /**
11484     * Returns the end padding of this view. If there are inset and enabled
11485     * scrollbars, this value may include the space required to display the
11486     * scrollbars as well.
11487     *
11488     * @return the end padding in pixels
11489     *
11490     * @hide
11491     */
11492    public int getPaddingEnd() {
11493        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11494                mPaddingLeft : mPaddingRight;
11495    }
11496
11497    /**
11498     * Return if the padding as been set thru relative values
11499     * {@link #setPaddingRelative(int, int, int, int)} or thru
11500     * @attr ref android.R.styleable#View_paddingStart or
11501     * @attr ref android.R.styleable#View_paddingEnd
11502     *
11503     * @return true if the padding is relative or false if it is not.
11504     *
11505     * @hide
11506     */
11507    public boolean isPaddingRelative() {
11508        return mUserPaddingRelative;
11509    }
11510
11511    /**
11512     * Changes the selection state of this view. A view can be selected or not.
11513     * Note that selection is not the same as focus. Views are typically
11514     * selected in the context of an AdapterView like ListView or GridView;
11515     * the selected view is the view that is highlighted.
11516     *
11517     * @param selected true if the view must be selected, false otherwise
11518     */
11519    public void setSelected(boolean selected) {
11520        if (((mPrivateFlags & SELECTED) != 0) != selected) {
11521            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
11522            if (!selected) resetPressedState();
11523            invalidate(true);
11524            refreshDrawableState();
11525            dispatchSetSelected(selected);
11526        }
11527    }
11528
11529    /**
11530     * Dispatch setSelected to all of this View's children.
11531     *
11532     * @see #setSelected(boolean)
11533     *
11534     * @param selected The new selected state
11535     */
11536    protected void dispatchSetSelected(boolean selected) {
11537    }
11538
11539    /**
11540     * Indicates the selection state of this view.
11541     *
11542     * @return true if the view is selected, false otherwise
11543     */
11544    @ViewDebug.ExportedProperty
11545    public boolean isSelected() {
11546        return (mPrivateFlags & SELECTED) != 0;
11547    }
11548
11549    /**
11550     * Changes the activated state of this view. A view can be activated or not.
11551     * Note that activation is not the same as selection.  Selection is
11552     * a transient property, representing the view (hierarchy) the user is
11553     * currently interacting with.  Activation is a longer-term state that the
11554     * user can move views in and out of.  For example, in a list view with
11555     * single or multiple selection enabled, the views in the current selection
11556     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
11557     * here.)  The activated state is propagated down to children of the view it
11558     * is set on.
11559     *
11560     * @param activated true if the view must be activated, false otherwise
11561     */
11562    public void setActivated(boolean activated) {
11563        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
11564            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
11565            invalidate(true);
11566            refreshDrawableState();
11567            dispatchSetActivated(activated);
11568        }
11569    }
11570
11571    /**
11572     * Dispatch setActivated to all of this View's children.
11573     *
11574     * @see #setActivated(boolean)
11575     *
11576     * @param activated The new activated state
11577     */
11578    protected void dispatchSetActivated(boolean activated) {
11579    }
11580
11581    /**
11582     * Indicates the activation state of this view.
11583     *
11584     * @return true if the view is activated, false otherwise
11585     */
11586    @ViewDebug.ExportedProperty
11587    public boolean isActivated() {
11588        return (mPrivateFlags & ACTIVATED) != 0;
11589    }
11590
11591    /**
11592     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
11593     * observer can be used to get notifications when global events, like
11594     * layout, happen.
11595     *
11596     * The returned ViewTreeObserver observer is not guaranteed to remain
11597     * valid for the lifetime of this View. If the caller of this method keeps
11598     * a long-lived reference to ViewTreeObserver, it should always check for
11599     * the return value of {@link ViewTreeObserver#isAlive()}.
11600     *
11601     * @return The ViewTreeObserver for this view's hierarchy.
11602     */
11603    public ViewTreeObserver getViewTreeObserver() {
11604        if (mAttachInfo != null) {
11605            return mAttachInfo.mTreeObserver;
11606        }
11607        if (mFloatingTreeObserver == null) {
11608            mFloatingTreeObserver = new ViewTreeObserver();
11609        }
11610        return mFloatingTreeObserver;
11611    }
11612
11613    /**
11614     * <p>Finds the topmost view in the current view hierarchy.</p>
11615     *
11616     * @return the topmost view containing this view
11617     */
11618    public View getRootView() {
11619        if (mAttachInfo != null) {
11620            final View v = mAttachInfo.mRootView;
11621            if (v != null) {
11622                return v;
11623            }
11624        }
11625
11626        View parent = this;
11627
11628        while (parent.mParent != null && parent.mParent instanceof View) {
11629            parent = (View) parent.mParent;
11630        }
11631
11632        return parent;
11633    }
11634
11635    /**
11636     * <p>Computes the coordinates of this view on the screen. The argument
11637     * must be an array of two integers. After the method returns, the array
11638     * contains the x and y location in that order.</p>
11639     *
11640     * @param location an array of two integers in which to hold the coordinates
11641     */
11642    public void getLocationOnScreen(int[] location) {
11643        getLocationInWindow(location);
11644
11645        final AttachInfo info = mAttachInfo;
11646        if (info != null) {
11647            location[0] += info.mWindowLeft;
11648            location[1] += info.mWindowTop;
11649        }
11650    }
11651
11652    /**
11653     * <p>Computes the coordinates of this view in its window. The argument
11654     * must be an array of two integers. After the method returns, the array
11655     * contains the x and y location in that order.</p>
11656     *
11657     * @param location an array of two integers in which to hold the coordinates
11658     */
11659    public void getLocationInWindow(int[] location) {
11660        if (location == null || location.length < 2) {
11661            throw new IllegalArgumentException("location must be an array of "
11662                    + "two integers");
11663        }
11664
11665        location[0] = mLeft + (int) (mTranslationX + 0.5f);
11666        location[1] = mTop + (int) (mTranslationY + 0.5f);
11667
11668        ViewParent viewParent = mParent;
11669        while (viewParent instanceof View) {
11670            final View view = (View)viewParent;
11671            location[0] += view.mLeft + (int) (view.mTranslationX + 0.5f) - view.mScrollX;
11672            location[1] += view.mTop + (int) (view.mTranslationY + 0.5f) - view.mScrollY;
11673            viewParent = view.mParent;
11674        }
11675
11676        if (viewParent instanceof ViewRootImpl) {
11677            // *cough*
11678            final ViewRootImpl vr = (ViewRootImpl)viewParent;
11679            location[1] -= vr.mCurScrollY;
11680        }
11681    }
11682
11683    /**
11684     * {@hide}
11685     * @param id the id of the view to be found
11686     * @return the view of the specified id, null if cannot be found
11687     */
11688    protected View findViewTraversal(int id) {
11689        if (id == mID) {
11690            return this;
11691        }
11692        return null;
11693    }
11694
11695    /**
11696     * {@hide}
11697     * @param tag the tag of the view to be found
11698     * @return the view of specified tag, null if cannot be found
11699     */
11700    protected View findViewWithTagTraversal(Object tag) {
11701        if (tag != null && tag.equals(mTag)) {
11702            return this;
11703        }
11704        return null;
11705    }
11706
11707    /**
11708     * {@hide}
11709     * @param predicate The predicate to evaluate.
11710     * @return The first view that matches the predicate or null.
11711     */
11712    protected View findViewByPredicateTraversal(Predicate<View> predicate) {
11713        if (predicate.apply(this)) {
11714            return this;
11715        }
11716        return null;
11717    }
11718
11719    /**
11720     * Look for a child view with the given id.  If this view has the given
11721     * id, return this view.
11722     *
11723     * @param id The id to search for.
11724     * @return The view that has the given id in the hierarchy or null
11725     */
11726    public final View findViewById(int id) {
11727        if (id < 0) {
11728            return null;
11729        }
11730        return findViewTraversal(id);
11731    }
11732
11733    /**
11734     * Look for a child view with the given tag.  If this view has the given
11735     * tag, return this view.
11736     *
11737     * @param tag The tag to search for, using "tag.equals(getTag())".
11738     * @return The View that has the given tag in the hierarchy or null
11739     */
11740    public final View findViewWithTag(Object tag) {
11741        if (tag == null) {
11742            return null;
11743        }
11744        return findViewWithTagTraversal(tag);
11745    }
11746
11747    /**
11748     * {@hide}
11749     * Look for a child view that matches the specified predicate.
11750     * If this view matches the predicate, return this view.
11751     *
11752     * @param predicate The predicate to evaluate.
11753     * @return The first view that matches the predicate or null.
11754     */
11755    public final View findViewByPredicate(Predicate<View> predicate) {
11756        return findViewByPredicateTraversal(predicate);
11757    }
11758
11759    /**
11760     * Sets the identifier for this view. The identifier does not have to be
11761     * unique in this view's hierarchy. The identifier should be a positive
11762     * number.
11763     *
11764     * @see #NO_ID
11765     * @see #getId()
11766     * @see #findViewById(int)
11767     *
11768     * @param id a number used to identify the view
11769     *
11770     * @attr ref android.R.styleable#View_id
11771     */
11772    public void setId(int id) {
11773        mID = id;
11774    }
11775
11776    /**
11777     * {@hide}
11778     *
11779     * @param isRoot true if the view belongs to the root namespace, false
11780     *        otherwise
11781     */
11782    public void setIsRootNamespace(boolean isRoot) {
11783        if (isRoot) {
11784            mPrivateFlags |= IS_ROOT_NAMESPACE;
11785        } else {
11786            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
11787        }
11788    }
11789
11790    /**
11791     * {@hide}
11792     *
11793     * @return true if the view belongs to the root namespace, false otherwise
11794     */
11795    public boolean isRootNamespace() {
11796        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
11797    }
11798
11799    /**
11800     * Returns this view's identifier.
11801     *
11802     * @return a positive integer used to identify the view or {@link #NO_ID}
11803     *         if the view has no ID
11804     *
11805     * @see #setId(int)
11806     * @see #findViewById(int)
11807     * @attr ref android.R.styleable#View_id
11808     */
11809    @ViewDebug.CapturedViewProperty
11810    public int getId() {
11811        return mID;
11812    }
11813
11814    /**
11815     * Returns this view's tag.
11816     *
11817     * @return the Object stored in this view as a tag
11818     *
11819     * @see #setTag(Object)
11820     * @see #getTag(int)
11821     */
11822    @ViewDebug.ExportedProperty
11823    public Object getTag() {
11824        return mTag;
11825    }
11826
11827    /**
11828     * Sets the tag associated with this view. A tag can be used to mark
11829     * a view in its hierarchy and does not have to be unique within the
11830     * hierarchy. Tags can also be used to store data within a view without
11831     * resorting to another data structure.
11832     *
11833     * @param tag an Object to tag the view with
11834     *
11835     * @see #getTag()
11836     * @see #setTag(int, Object)
11837     */
11838    public void setTag(final Object tag) {
11839        mTag = tag;
11840    }
11841
11842    /**
11843     * Returns the tag associated with this view and the specified key.
11844     *
11845     * @param key The key identifying the tag
11846     *
11847     * @return the Object stored in this view as a tag
11848     *
11849     * @see #setTag(int, Object)
11850     * @see #getTag()
11851     */
11852    public Object getTag(int key) {
11853        SparseArray<Object> tags = null;
11854        synchronized (sTagsLock) {
11855            if (sTags != null) {
11856                tags = sTags.get(this);
11857            }
11858        }
11859
11860        if (tags != null) return tags.get(key);
11861        return null;
11862    }
11863
11864    /**
11865     * Sets a tag associated with this view and a key. A tag can be used
11866     * to mark a view in its hierarchy and does not have to be unique within
11867     * the hierarchy. Tags can also be used to store data within a view
11868     * without resorting to another data structure.
11869     *
11870     * The specified key should be an id declared in the resources of the
11871     * application to ensure it is unique (see the <a
11872     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
11873     * Keys identified as belonging to
11874     * the Android framework or not associated with any package will cause
11875     * an {@link IllegalArgumentException} to be thrown.
11876     *
11877     * @param key The key identifying the tag
11878     * @param tag An Object to tag the view with
11879     *
11880     * @throws IllegalArgumentException If they specified key is not valid
11881     *
11882     * @see #setTag(Object)
11883     * @see #getTag(int)
11884     */
11885    public void setTag(int key, final Object tag) {
11886        // If the package id is 0x00 or 0x01, it's either an undefined package
11887        // or a framework id
11888        if ((key >>> 24) < 2) {
11889            throw new IllegalArgumentException("The key must be an application-specific "
11890                    + "resource id.");
11891        }
11892
11893        setTagInternal(this, key, tag);
11894    }
11895
11896    /**
11897     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
11898     * framework id.
11899     *
11900     * @hide
11901     */
11902    public void setTagInternal(int key, Object tag) {
11903        if ((key >>> 24) != 0x1) {
11904            throw new IllegalArgumentException("The key must be a framework-specific "
11905                    + "resource id.");
11906        }
11907
11908        setTagInternal(this, key, tag);
11909    }
11910
11911    private static void setTagInternal(View view, int key, Object tag) {
11912        SparseArray<Object> tags = null;
11913        synchronized (sTagsLock) {
11914            if (sTags == null) {
11915                sTags = new WeakHashMap<View, SparseArray<Object>>();
11916            } else {
11917                tags = sTags.get(view);
11918            }
11919        }
11920
11921        if (tags == null) {
11922            tags = new SparseArray<Object>(2);
11923            synchronized (sTagsLock) {
11924                sTags.put(view, tags);
11925            }
11926        }
11927
11928        tags.put(key, tag);
11929    }
11930
11931    /**
11932     * @param consistency The type of consistency. See ViewDebug for more information.
11933     *
11934     * @hide
11935     */
11936    protected boolean dispatchConsistencyCheck(int consistency) {
11937        return onConsistencyCheck(consistency);
11938    }
11939
11940    /**
11941     * Method that subclasses should implement to check their consistency. The type of
11942     * consistency check is indicated by the bit field passed as a parameter.
11943     *
11944     * @param consistency The type of consistency. See ViewDebug for more information.
11945     *
11946     * @throws IllegalStateException if the view is in an inconsistent state.
11947     *
11948     * @hide
11949     */
11950    protected boolean onConsistencyCheck(int consistency) {
11951        boolean result = true;
11952
11953        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
11954        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
11955
11956        if (checkLayout) {
11957            if (getParent() == null) {
11958                result = false;
11959                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
11960                        "View " + this + " does not have a parent.");
11961            }
11962
11963            if (mAttachInfo == null) {
11964                result = false;
11965                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
11966                        "View " + this + " is not attached to a window.");
11967            }
11968        }
11969
11970        if (checkDrawing) {
11971            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
11972            // from their draw() method
11973
11974            if ((mPrivateFlags & DRAWN) != DRAWN &&
11975                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
11976                result = false;
11977                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
11978                        "View " + this + " was invalidated but its drawing cache is valid.");
11979            }
11980        }
11981
11982        return result;
11983    }
11984
11985    /**
11986     * Prints information about this view in the log output, with the tag
11987     * {@link #VIEW_LOG_TAG}.
11988     *
11989     * @hide
11990     */
11991    public void debug() {
11992        debug(0);
11993    }
11994
11995    /**
11996     * Prints information about this view in the log output, with the tag
11997     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
11998     * indentation defined by the <code>depth</code>.
11999     *
12000     * @param depth the indentation level
12001     *
12002     * @hide
12003     */
12004    protected void debug(int depth) {
12005        String output = debugIndent(depth - 1);
12006
12007        output += "+ " + this;
12008        int id = getId();
12009        if (id != -1) {
12010            output += " (id=" + id + ")";
12011        }
12012        Object tag = getTag();
12013        if (tag != null) {
12014            output += " (tag=" + tag + ")";
12015        }
12016        Log.d(VIEW_LOG_TAG, output);
12017
12018        if ((mPrivateFlags & FOCUSED) != 0) {
12019            output = debugIndent(depth) + " FOCUSED";
12020            Log.d(VIEW_LOG_TAG, output);
12021        }
12022
12023        output = debugIndent(depth);
12024        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12025                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12026                + "} ";
12027        Log.d(VIEW_LOG_TAG, output);
12028
12029        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12030                || mPaddingBottom != 0) {
12031            output = debugIndent(depth);
12032            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12033                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12034            Log.d(VIEW_LOG_TAG, output);
12035        }
12036
12037        output = debugIndent(depth);
12038        output += "mMeasureWidth=" + mMeasuredWidth +
12039                " mMeasureHeight=" + mMeasuredHeight;
12040        Log.d(VIEW_LOG_TAG, output);
12041
12042        output = debugIndent(depth);
12043        if (mLayoutParams == null) {
12044            output += "BAD! no layout params";
12045        } else {
12046            output = mLayoutParams.debug(output);
12047        }
12048        Log.d(VIEW_LOG_TAG, output);
12049
12050        output = debugIndent(depth);
12051        output += "flags={";
12052        output += View.printFlags(mViewFlags);
12053        output += "}";
12054        Log.d(VIEW_LOG_TAG, output);
12055
12056        output = debugIndent(depth);
12057        output += "privateFlags={";
12058        output += View.printPrivateFlags(mPrivateFlags);
12059        output += "}";
12060        Log.d(VIEW_LOG_TAG, output);
12061    }
12062
12063    /**
12064     * Creates an string of whitespaces used for indentation.
12065     *
12066     * @param depth the indentation level
12067     * @return a String containing (depth * 2 + 3) * 2 white spaces
12068     *
12069     * @hide
12070     */
12071    protected static String debugIndent(int depth) {
12072        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12073        for (int i = 0; i < (depth * 2) + 3; i++) {
12074            spaces.append(' ').append(' ');
12075        }
12076        return spaces.toString();
12077    }
12078
12079    /**
12080     * <p>Return the offset of the widget's text baseline from the widget's top
12081     * boundary. If this widget does not support baseline alignment, this
12082     * method returns -1. </p>
12083     *
12084     * @return the offset of the baseline within the widget's bounds or -1
12085     *         if baseline alignment is not supported
12086     */
12087    @ViewDebug.ExportedProperty(category = "layout")
12088    public int getBaseline() {
12089        return -1;
12090    }
12091
12092    /**
12093     * Call this when something has changed which has invalidated the
12094     * layout of this view. This will schedule a layout pass of the view
12095     * tree.
12096     */
12097    public void requestLayout() {
12098        if (ViewDebug.TRACE_HIERARCHY) {
12099            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
12100        }
12101
12102        mPrivateFlags |= FORCE_LAYOUT;
12103        mPrivateFlags |= INVALIDATED;
12104
12105        if (mParent != null) {
12106            if (mLayoutParams != null) {
12107                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
12108            }
12109            if (!mParent.isLayoutRequested()) {
12110                mParent.requestLayout();
12111            }
12112        }
12113    }
12114
12115    /**
12116     * Forces this view to be laid out during the next layout pass.
12117     * This method does not call requestLayout() or forceLayout()
12118     * on the parent.
12119     */
12120    public void forceLayout() {
12121        mPrivateFlags |= FORCE_LAYOUT;
12122        mPrivateFlags |= INVALIDATED;
12123    }
12124
12125    /**
12126     * <p>
12127     * This is called to find out how big a view should be. The parent
12128     * supplies constraint information in the width and height parameters.
12129     * </p>
12130     *
12131     * <p>
12132     * The actual mesurement work of a view is performed in
12133     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
12134     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
12135     * </p>
12136     *
12137     *
12138     * @param widthMeasureSpec Horizontal space requirements as imposed by the
12139     *        parent
12140     * @param heightMeasureSpec Vertical space requirements as imposed by the
12141     *        parent
12142     *
12143     * @see #onMeasure(int, int)
12144     */
12145    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
12146        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
12147                widthMeasureSpec != mOldWidthMeasureSpec ||
12148                heightMeasureSpec != mOldHeightMeasureSpec) {
12149
12150            // first clears the measured dimension flag
12151            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
12152
12153            if (ViewDebug.TRACE_HIERARCHY) {
12154                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
12155            }
12156
12157            // measure ourselves, this should set the measured dimension flag back
12158            onMeasure(widthMeasureSpec, heightMeasureSpec);
12159
12160            // flag not set, setMeasuredDimension() was not invoked, we raise
12161            // an exception to warn the developer
12162            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
12163                throw new IllegalStateException("onMeasure() did not set the"
12164                        + " measured dimension by calling"
12165                        + " setMeasuredDimension()");
12166            }
12167
12168            mPrivateFlags |= LAYOUT_REQUIRED;
12169        }
12170
12171        mOldWidthMeasureSpec = widthMeasureSpec;
12172        mOldHeightMeasureSpec = heightMeasureSpec;
12173    }
12174
12175    /**
12176     * <p>
12177     * Measure the view and its content to determine the measured width and the
12178     * measured height. This method is invoked by {@link #measure(int, int)} and
12179     * should be overriden by subclasses to provide accurate and efficient
12180     * measurement of their contents.
12181     * </p>
12182     *
12183     * <p>
12184     * <strong>CONTRACT:</strong> When overriding this method, you
12185     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
12186     * measured width and height of this view. Failure to do so will trigger an
12187     * <code>IllegalStateException</code>, thrown by
12188     * {@link #measure(int, int)}. Calling the superclass'
12189     * {@link #onMeasure(int, int)} is a valid use.
12190     * </p>
12191     *
12192     * <p>
12193     * The base class implementation of measure defaults to the background size,
12194     * unless a larger size is allowed by the MeasureSpec. Subclasses should
12195     * override {@link #onMeasure(int, int)} to provide better measurements of
12196     * their content.
12197     * </p>
12198     *
12199     * <p>
12200     * If this method is overridden, it is the subclass's responsibility to make
12201     * sure the measured height and width are at least the view's minimum height
12202     * and width ({@link #getSuggestedMinimumHeight()} and
12203     * {@link #getSuggestedMinimumWidth()}).
12204     * </p>
12205     *
12206     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
12207     *                         The requirements are encoded with
12208     *                         {@link android.view.View.MeasureSpec}.
12209     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
12210     *                         The requirements are encoded with
12211     *                         {@link android.view.View.MeasureSpec}.
12212     *
12213     * @see #getMeasuredWidth()
12214     * @see #getMeasuredHeight()
12215     * @see #setMeasuredDimension(int, int)
12216     * @see #getSuggestedMinimumHeight()
12217     * @see #getSuggestedMinimumWidth()
12218     * @see android.view.View.MeasureSpec#getMode(int)
12219     * @see android.view.View.MeasureSpec#getSize(int)
12220     */
12221    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12222        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
12223                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
12224    }
12225
12226    /**
12227     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
12228     * measured width and measured height. Failing to do so will trigger an
12229     * exception at measurement time.</p>
12230     *
12231     * @param measuredWidth The measured width of this view.  May be a complex
12232     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12233     * {@link #MEASURED_STATE_TOO_SMALL}.
12234     * @param measuredHeight The measured height of this view.  May be a complex
12235     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12236     * {@link #MEASURED_STATE_TOO_SMALL}.
12237     */
12238    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
12239        mMeasuredWidth = measuredWidth;
12240        mMeasuredHeight = measuredHeight;
12241
12242        mPrivateFlags |= MEASURED_DIMENSION_SET;
12243    }
12244
12245    /**
12246     * Merge two states as returned by {@link #getMeasuredState()}.
12247     * @param curState The current state as returned from a view or the result
12248     * of combining multiple views.
12249     * @param newState The new view state to combine.
12250     * @return Returns a new integer reflecting the combination of the two
12251     * states.
12252     */
12253    public static int combineMeasuredStates(int curState, int newState) {
12254        return curState | newState;
12255    }
12256
12257    /**
12258     * Version of {@link #resolveSizeAndState(int, int, int)}
12259     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
12260     */
12261    public static int resolveSize(int size, int measureSpec) {
12262        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
12263    }
12264
12265    /**
12266     * Utility to reconcile a desired size and state, with constraints imposed
12267     * by a MeasureSpec.  Will take the desired size, unless a different size
12268     * is imposed by the constraints.  The returned value is a compound integer,
12269     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
12270     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
12271     * size is smaller than the size the view wants to be.
12272     *
12273     * @param size How big the view wants to be
12274     * @param measureSpec Constraints imposed by the parent
12275     * @return Size information bit mask as defined by
12276     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12277     */
12278    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
12279        int result = size;
12280        int specMode = MeasureSpec.getMode(measureSpec);
12281        int specSize =  MeasureSpec.getSize(measureSpec);
12282        switch (specMode) {
12283        case MeasureSpec.UNSPECIFIED:
12284            result = size;
12285            break;
12286        case MeasureSpec.AT_MOST:
12287            if (specSize < size) {
12288                result = specSize | MEASURED_STATE_TOO_SMALL;
12289            } else {
12290                result = size;
12291            }
12292            break;
12293        case MeasureSpec.EXACTLY:
12294            result = specSize;
12295            break;
12296        }
12297        return result | (childMeasuredState&MEASURED_STATE_MASK);
12298    }
12299
12300    /**
12301     * Utility to return a default size. Uses the supplied size if the
12302     * MeasureSpec imposed no constraints. Will get larger if allowed
12303     * by the MeasureSpec.
12304     *
12305     * @param size Default size for this view
12306     * @param measureSpec Constraints imposed by the parent
12307     * @return The size this view should be.
12308     */
12309    public static int getDefaultSize(int size, int measureSpec) {
12310        int result = size;
12311        int specMode = MeasureSpec.getMode(measureSpec);
12312        int specSize = MeasureSpec.getSize(measureSpec);
12313
12314        switch (specMode) {
12315        case MeasureSpec.UNSPECIFIED:
12316            result = size;
12317            break;
12318        case MeasureSpec.AT_MOST:
12319        case MeasureSpec.EXACTLY:
12320            result = specSize;
12321            break;
12322        }
12323        return result;
12324    }
12325
12326    /**
12327     * Returns the suggested minimum height that the view should use. This
12328     * returns the maximum of the view's minimum height
12329     * and the background's minimum height
12330     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
12331     * <p>
12332     * When being used in {@link #onMeasure(int, int)}, the caller should still
12333     * ensure the returned height is within the requirements of the parent.
12334     *
12335     * @return The suggested minimum height of the view.
12336     */
12337    protected int getSuggestedMinimumHeight() {
12338        int suggestedMinHeight = mMinHeight;
12339
12340        if (mBGDrawable != null) {
12341            final int bgMinHeight = mBGDrawable.getMinimumHeight();
12342            if (suggestedMinHeight < bgMinHeight) {
12343                suggestedMinHeight = bgMinHeight;
12344            }
12345        }
12346
12347        return suggestedMinHeight;
12348    }
12349
12350    /**
12351     * Returns the suggested minimum width that the view should use. This
12352     * returns the maximum of the view's minimum width)
12353     * and the background's minimum width
12354     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
12355     * <p>
12356     * When being used in {@link #onMeasure(int, int)}, the caller should still
12357     * ensure the returned width is within the requirements of the parent.
12358     *
12359     * @return The suggested minimum width of the view.
12360     */
12361    protected int getSuggestedMinimumWidth() {
12362        int suggestedMinWidth = mMinWidth;
12363
12364        if (mBGDrawable != null) {
12365            final int bgMinWidth = mBGDrawable.getMinimumWidth();
12366            if (suggestedMinWidth < bgMinWidth) {
12367                suggestedMinWidth = bgMinWidth;
12368            }
12369        }
12370
12371        return suggestedMinWidth;
12372    }
12373
12374    /**
12375     * Sets the minimum height of the view. It is not guaranteed the view will
12376     * be able to achieve this minimum height (for example, if its parent layout
12377     * constrains it with less available height).
12378     *
12379     * @param minHeight The minimum height the view will try to be.
12380     */
12381    public void setMinimumHeight(int minHeight) {
12382        mMinHeight = minHeight;
12383    }
12384
12385    /**
12386     * Sets the minimum width of the view. It is not guaranteed the view will
12387     * be able to achieve this minimum width (for example, if its parent layout
12388     * constrains it with less available width).
12389     *
12390     * @param minWidth The minimum width the view will try to be.
12391     */
12392    public void setMinimumWidth(int minWidth) {
12393        mMinWidth = minWidth;
12394    }
12395
12396    /**
12397     * Get the animation currently associated with this view.
12398     *
12399     * @return The animation that is currently playing or
12400     *         scheduled to play for this view.
12401     */
12402    public Animation getAnimation() {
12403        return mCurrentAnimation;
12404    }
12405
12406    /**
12407     * Start the specified animation now.
12408     *
12409     * @param animation the animation to start now
12410     */
12411    public void startAnimation(Animation animation) {
12412        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
12413        setAnimation(animation);
12414        invalidateParentCaches();
12415        invalidate(true);
12416    }
12417
12418    /**
12419     * Cancels any animations for this view.
12420     */
12421    public void clearAnimation() {
12422        if (mCurrentAnimation != null) {
12423            mCurrentAnimation.detach();
12424        }
12425        mCurrentAnimation = null;
12426        invalidateParentIfNeeded();
12427    }
12428
12429    /**
12430     * Sets the next animation to play for this view.
12431     * If you want the animation to play immediately, use
12432     * startAnimation. This method provides allows fine-grained
12433     * control over the start time and invalidation, but you
12434     * must make sure that 1) the animation has a start time set, and
12435     * 2) the view will be invalidated when the animation is supposed to
12436     * start.
12437     *
12438     * @param animation The next animation, or null.
12439     */
12440    public void setAnimation(Animation animation) {
12441        mCurrentAnimation = animation;
12442        if (animation != null) {
12443            animation.reset();
12444        }
12445    }
12446
12447    /**
12448     * Invoked by a parent ViewGroup to notify the start of the animation
12449     * currently associated with this view. If you override this method,
12450     * always call super.onAnimationStart();
12451     *
12452     * @see #setAnimation(android.view.animation.Animation)
12453     * @see #getAnimation()
12454     */
12455    protected void onAnimationStart() {
12456        mPrivateFlags |= ANIMATION_STARTED;
12457    }
12458
12459    /**
12460     * Invoked by a parent ViewGroup to notify the end of the animation
12461     * currently associated with this view. If you override this method,
12462     * always call super.onAnimationEnd();
12463     *
12464     * @see #setAnimation(android.view.animation.Animation)
12465     * @see #getAnimation()
12466     */
12467    protected void onAnimationEnd() {
12468        mPrivateFlags &= ~ANIMATION_STARTED;
12469    }
12470
12471    /**
12472     * Invoked if there is a Transform that involves alpha. Subclass that can
12473     * draw themselves with the specified alpha should return true, and then
12474     * respect that alpha when their onDraw() is called. If this returns false
12475     * then the view may be redirected to draw into an offscreen buffer to
12476     * fulfill the request, which will look fine, but may be slower than if the
12477     * subclass handles it internally. The default implementation returns false.
12478     *
12479     * @param alpha The alpha (0..255) to apply to the view's drawing
12480     * @return true if the view can draw with the specified alpha.
12481     */
12482    protected boolean onSetAlpha(int alpha) {
12483        return false;
12484    }
12485
12486    /**
12487     * This is used by the RootView to perform an optimization when
12488     * the view hierarchy contains one or several SurfaceView.
12489     * SurfaceView is always considered transparent, but its children are not,
12490     * therefore all View objects remove themselves from the global transparent
12491     * region (passed as a parameter to this function).
12492     *
12493     * @param region The transparent region for this ViewAncestor (window).
12494     *
12495     * @return Returns true if the effective visibility of the view at this
12496     * point is opaque, regardless of the transparent region; returns false
12497     * if it is possible for underlying windows to be seen behind the view.
12498     *
12499     * {@hide}
12500     */
12501    public boolean gatherTransparentRegion(Region region) {
12502        final AttachInfo attachInfo = mAttachInfo;
12503        if (region != null && attachInfo != null) {
12504            final int pflags = mPrivateFlags;
12505            if ((pflags & SKIP_DRAW) == 0) {
12506                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
12507                // remove it from the transparent region.
12508                final int[] location = attachInfo.mTransparentLocation;
12509                getLocationInWindow(location);
12510                region.op(location[0], location[1], location[0] + mRight - mLeft,
12511                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
12512            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
12513                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
12514                // exists, so we remove the background drawable's non-transparent
12515                // parts from this transparent region.
12516                applyDrawableToTransparentRegion(mBGDrawable, region);
12517            }
12518        }
12519        return true;
12520    }
12521
12522    /**
12523     * Play a sound effect for this view.
12524     *
12525     * <p>The framework will play sound effects for some built in actions, such as
12526     * clicking, but you may wish to play these effects in your widget,
12527     * for instance, for internal navigation.
12528     *
12529     * <p>The sound effect will only be played if sound effects are enabled by the user, and
12530     * {@link #isSoundEffectsEnabled()} is true.
12531     *
12532     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
12533     */
12534    public void playSoundEffect(int soundConstant) {
12535        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
12536            return;
12537        }
12538        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
12539    }
12540
12541    /**
12542     * BZZZTT!!1!
12543     *
12544     * <p>Provide haptic feedback to the user for this view.
12545     *
12546     * <p>The framework will provide haptic feedback for some built in actions,
12547     * such as long presses, but you may wish to provide feedback for your
12548     * own widget.
12549     *
12550     * <p>The feedback will only be performed if
12551     * {@link #isHapticFeedbackEnabled()} is true.
12552     *
12553     * @param feedbackConstant One of the constants defined in
12554     * {@link HapticFeedbackConstants}
12555     */
12556    public boolean performHapticFeedback(int feedbackConstant) {
12557        return performHapticFeedback(feedbackConstant, 0);
12558    }
12559
12560    /**
12561     * BZZZTT!!1!
12562     *
12563     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
12564     *
12565     * @param feedbackConstant One of the constants defined in
12566     * {@link HapticFeedbackConstants}
12567     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
12568     */
12569    public boolean performHapticFeedback(int feedbackConstant, int flags) {
12570        if (mAttachInfo == null) {
12571            return false;
12572        }
12573        //noinspection SimplifiableIfStatement
12574        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
12575                && !isHapticFeedbackEnabled()) {
12576            return false;
12577        }
12578        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
12579                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
12580    }
12581
12582    /**
12583     * Request that the visibility of the status bar be changed.
12584     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12585     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12586     */
12587    public void setSystemUiVisibility(int visibility) {
12588        if (visibility != mSystemUiVisibility) {
12589            mSystemUiVisibility = visibility;
12590            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12591                mParent.recomputeViewAttributes(this);
12592            }
12593        }
12594    }
12595
12596    /**
12597     * Returns the status bar visibility that this view has requested.
12598     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
12599     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
12600     */
12601    public int getSystemUiVisibility() {
12602        return mSystemUiVisibility;
12603    }
12604
12605    /**
12606     * Set a listener to receive callbacks when the visibility of the system bar changes.
12607     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
12608     */
12609    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
12610        mOnSystemUiVisibilityChangeListener = l;
12611        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
12612            mParent.recomputeViewAttributes(this);
12613        }
12614    }
12615
12616    /**
12617     */
12618    public void dispatchSystemUiVisibilityChanged(int visibility) {
12619        if (mOnSystemUiVisibilityChangeListener != null) {
12620            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
12621                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
12622        }
12623    }
12624
12625    /**
12626     * Creates an image that the system displays during the drag and drop
12627     * operation. This is called a &quot;drag shadow&quot;. The default implementation
12628     * for a DragShadowBuilder based on a View returns an image that has exactly the same
12629     * appearance as the given View. The default also positions the center of the drag shadow
12630     * directly under the touch point. If no View is provided (the constructor with no parameters
12631     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
12632     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
12633     * default is an invisible drag shadow.
12634     * <p>
12635     * You are not required to use the View you provide to the constructor as the basis of the
12636     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
12637     * anything you want as the drag shadow.
12638     * </p>
12639     * <p>
12640     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
12641     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
12642     *  size and position of the drag shadow. It uses this data to construct a
12643     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
12644     *  so that your application can draw the shadow image in the Canvas.
12645     * </p>
12646     */
12647    public static class DragShadowBuilder {
12648        private final WeakReference<View> mView;
12649
12650        /**
12651         * Constructs a shadow image builder based on a View. By default, the resulting drag
12652         * shadow will have the same appearance and dimensions as the View, with the touch point
12653         * over the center of the View.
12654         * @param view A View. Any View in scope can be used.
12655         */
12656        public DragShadowBuilder(View view) {
12657            mView = new WeakReference<View>(view);
12658        }
12659
12660        /**
12661         * Construct a shadow builder object with no associated View.  This
12662         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
12663         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
12664         * to supply the drag shadow's dimensions and appearance without
12665         * reference to any View object. If they are not overridden, then the result is an
12666         * invisible drag shadow.
12667         */
12668        public DragShadowBuilder() {
12669            mView = new WeakReference<View>(null);
12670        }
12671
12672        /**
12673         * Returns the View object that had been passed to the
12674         * {@link #View.DragShadowBuilder(View)}
12675         * constructor.  If that View parameter was {@code null} or if the
12676         * {@link #View.DragShadowBuilder()}
12677         * constructor was used to instantiate the builder object, this method will return
12678         * null.
12679         *
12680         * @return The View object associate with this builder object.
12681         */
12682        @SuppressWarnings({"JavadocReference"})
12683        final public View getView() {
12684            return mView.get();
12685        }
12686
12687        /**
12688         * Provides the metrics for the shadow image. These include the dimensions of
12689         * the shadow image, and the point within that shadow that should
12690         * be centered under the touch location while dragging.
12691         * <p>
12692         * The default implementation sets the dimensions of the shadow to be the
12693         * same as the dimensions of the View itself and centers the shadow under
12694         * the touch point.
12695         * </p>
12696         *
12697         * @param shadowSize A {@link android.graphics.Point} containing the width and height
12698         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
12699         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
12700         * image.
12701         *
12702         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
12703         * shadow image that should be underneath the touch point during the drag and drop
12704         * operation. Your application must set {@link android.graphics.Point#x} to the
12705         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
12706         */
12707        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
12708            final View view = mView.get();
12709            if (view != null) {
12710                shadowSize.set(view.getWidth(), view.getHeight());
12711                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
12712            } else {
12713                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
12714            }
12715        }
12716
12717        /**
12718         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
12719         * based on the dimensions it received from the
12720         * {@link #onProvideShadowMetrics(Point, Point)} callback.
12721         *
12722         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
12723         */
12724        public void onDrawShadow(Canvas canvas) {
12725            final View view = mView.get();
12726            if (view != null) {
12727                view.draw(canvas);
12728            } else {
12729                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
12730            }
12731        }
12732    }
12733
12734    /**
12735     * Starts a drag and drop operation. When your application calls this method, it passes a
12736     * {@link android.view.View.DragShadowBuilder} object to the system. The
12737     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
12738     * to get metrics for the drag shadow, and then calls the object's
12739     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
12740     * <p>
12741     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
12742     *  drag events to all the View objects in your application that are currently visible. It does
12743     *  this either by calling the View object's drag listener (an implementation of
12744     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
12745     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
12746     *  Both are passed a {@link android.view.DragEvent} object that has a
12747     *  {@link android.view.DragEvent#getAction()} value of
12748     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
12749     * </p>
12750     * <p>
12751     * Your application can invoke startDrag() on any attached View object. The View object does not
12752     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
12753     * be related to the View the user selected for dragging.
12754     * </p>
12755     * @param data A {@link android.content.ClipData} object pointing to the data to be
12756     * transferred by the drag and drop operation.
12757     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
12758     * drag shadow.
12759     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
12760     * drop operation. This Object is put into every DragEvent object sent by the system during the
12761     * current drag.
12762     * <p>
12763     * myLocalState is a lightweight mechanism for the sending information from the dragged View
12764     * to the target Views. For example, it can contain flags that differentiate between a
12765     * a copy operation and a move operation.
12766     * </p>
12767     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
12768     * so the parameter should be set to 0.
12769     * @return {@code true} if the method completes successfully, or
12770     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
12771     * do a drag, and so no drag operation is in progress.
12772     */
12773    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
12774            Object myLocalState, int flags) {
12775        if (ViewDebug.DEBUG_DRAG) {
12776            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
12777        }
12778        boolean okay = false;
12779
12780        Point shadowSize = new Point();
12781        Point shadowTouchPoint = new Point();
12782        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
12783
12784        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
12785                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
12786            throw new IllegalStateException("Drag shadow dimensions must not be negative");
12787        }
12788
12789        if (ViewDebug.DEBUG_DRAG) {
12790            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
12791                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
12792        }
12793        Surface surface = new Surface();
12794        try {
12795            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
12796                    flags, shadowSize.x, shadowSize.y, surface);
12797            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
12798                    + " surface=" + surface);
12799            if (token != null) {
12800                Canvas canvas = surface.lockCanvas(null);
12801                try {
12802                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
12803                    shadowBuilder.onDrawShadow(canvas);
12804                } finally {
12805                    surface.unlockCanvasAndPost(canvas);
12806                }
12807
12808                final ViewRootImpl root = getViewRootImpl();
12809
12810                // Cache the local state object for delivery with DragEvents
12811                root.setLocalDragState(myLocalState);
12812
12813                // repurpose 'shadowSize' for the last touch point
12814                root.getLastTouchPoint(shadowSize);
12815
12816                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
12817                        shadowSize.x, shadowSize.y,
12818                        shadowTouchPoint.x, shadowTouchPoint.y, data);
12819                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
12820            }
12821        } catch (Exception e) {
12822            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
12823            surface.destroy();
12824        }
12825
12826        return okay;
12827    }
12828
12829    /**
12830     * Handles drag events sent by the system following a call to
12831     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
12832     *<p>
12833     * When the system calls this method, it passes a
12834     * {@link android.view.DragEvent} object. A call to
12835     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
12836     * in DragEvent. The method uses these to determine what is happening in the drag and drop
12837     * operation.
12838     * @param event The {@link android.view.DragEvent} sent by the system.
12839     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
12840     * in DragEvent, indicating the type of drag event represented by this object.
12841     * @return {@code true} if the method was successful, otherwise {@code false}.
12842     * <p>
12843     *  The method should return {@code true} in response to an action type of
12844     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
12845     *  operation.
12846     * </p>
12847     * <p>
12848     *  The method should also return {@code true} in response to an action type of
12849     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
12850     *  {@code false} if it didn't.
12851     * </p>
12852     */
12853    public boolean onDragEvent(DragEvent event) {
12854        return false;
12855    }
12856
12857    /**
12858     * Detects if this View is enabled and has a drag event listener.
12859     * If both are true, then it calls the drag event listener with the
12860     * {@link android.view.DragEvent} it received. If the drag event listener returns
12861     * {@code true}, then dispatchDragEvent() returns {@code true}.
12862     * <p>
12863     * For all other cases, the method calls the
12864     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
12865     * method and returns its result.
12866     * </p>
12867     * <p>
12868     * This ensures that a drag event is always consumed, even if the View does not have a drag
12869     * event listener. However, if the View has a listener and the listener returns true, then
12870     * onDragEvent() is not called.
12871     * </p>
12872     */
12873    public boolean dispatchDragEvent(DragEvent event) {
12874        //noinspection SimplifiableIfStatement
12875        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
12876                && mOnDragListener.onDrag(this, event)) {
12877            return true;
12878        }
12879        return onDragEvent(event);
12880    }
12881
12882    boolean canAcceptDrag() {
12883        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
12884    }
12885
12886    /**
12887     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
12888     * it is ever exposed at all.
12889     * @hide
12890     */
12891    public void onCloseSystemDialogs(String reason) {
12892    }
12893
12894    /**
12895     * Given a Drawable whose bounds have been set to draw into this view,
12896     * update a Region being computed for
12897     * {@link #gatherTransparentRegion(android.graphics.Region)} so
12898     * that any non-transparent parts of the Drawable are removed from the
12899     * given transparent region.
12900     *
12901     * @param dr The Drawable whose transparency is to be applied to the region.
12902     * @param region A Region holding the current transparency information,
12903     * where any parts of the region that are set are considered to be
12904     * transparent.  On return, this region will be modified to have the
12905     * transparency information reduced by the corresponding parts of the
12906     * Drawable that are not transparent.
12907     * {@hide}
12908     */
12909    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
12910        if (DBG) {
12911            Log.i("View", "Getting transparent region for: " + this);
12912        }
12913        final Region r = dr.getTransparentRegion();
12914        final Rect db = dr.getBounds();
12915        final AttachInfo attachInfo = mAttachInfo;
12916        if (r != null && attachInfo != null) {
12917            final int w = getRight()-getLeft();
12918            final int h = getBottom()-getTop();
12919            if (db.left > 0) {
12920                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
12921                r.op(0, 0, db.left, h, Region.Op.UNION);
12922            }
12923            if (db.right < w) {
12924                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
12925                r.op(db.right, 0, w, h, Region.Op.UNION);
12926            }
12927            if (db.top > 0) {
12928                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
12929                r.op(0, 0, w, db.top, Region.Op.UNION);
12930            }
12931            if (db.bottom < h) {
12932                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
12933                r.op(0, db.bottom, w, h, Region.Op.UNION);
12934            }
12935            final int[] location = attachInfo.mTransparentLocation;
12936            getLocationInWindow(location);
12937            r.translate(location[0], location[1]);
12938            region.op(r, Region.Op.INTERSECT);
12939        } else {
12940            region.op(db, Region.Op.DIFFERENCE);
12941        }
12942    }
12943
12944    private void checkForLongClick(int delayOffset) {
12945        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
12946            mHasPerformedLongPress = false;
12947
12948            if (mPendingCheckForLongPress == null) {
12949                mPendingCheckForLongPress = new CheckForLongPress();
12950            }
12951            mPendingCheckForLongPress.rememberWindowAttachCount();
12952            postDelayed(mPendingCheckForLongPress,
12953                    ViewConfiguration.getLongPressTimeout() - delayOffset);
12954        }
12955    }
12956
12957    /**
12958     * Inflate a view from an XML resource.  This convenience method wraps the {@link
12959     * LayoutInflater} class, which provides a full range of options for view inflation.
12960     *
12961     * @param context The Context object for your activity or application.
12962     * @param resource The resource ID to inflate
12963     * @param root A view group that will be the parent.  Used to properly inflate the
12964     * layout_* parameters.
12965     * @see LayoutInflater
12966     */
12967    public static View inflate(Context context, int resource, ViewGroup root) {
12968        LayoutInflater factory = LayoutInflater.from(context);
12969        return factory.inflate(resource, root);
12970    }
12971
12972    /**
12973     * Scroll the view with standard behavior for scrolling beyond the normal
12974     * content boundaries. Views that call this method should override
12975     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
12976     * results of an over-scroll operation.
12977     *
12978     * Views can use this method to handle any touch or fling-based scrolling.
12979     *
12980     * @param deltaX Change in X in pixels
12981     * @param deltaY Change in Y in pixels
12982     * @param scrollX Current X scroll value in pixels before applying deltaX
12983     * @param scrollY Current Y scroll value in pixels before applying deltaY
12984     * @param scrollRangeX Maximum content scroll range along the X axis
12985     * @param scrollRangeY Maximum content scroll range along the Y axis
12986     * @param maxOverScrollX Number of pixels to overscroll by in either direction
12987     *          along the X axis.
12988     * @param maxOverScrollY Number of pixels to overscroll by in either direction
12989     *          along the Y axis.
12990     * @param isTouchEvent true if this scroll operation is the result of a touch event.
12991     * @return true if scrolling was clamped to an over-scroll boundary along either
12992     *          axis, false otherwise.
12993     */
12994    @SuppressWarnings({"UnusedParameters"})
12995    protected boolean overScrollBy(int deltaX, int deltaY,
12996            int scrollX, int scrollY,
12997            int scrollRangeX, int scrollRangeY,
12998            int maxOverScrollX, int maxOverScrollY,
12999            boolean isTouchEvent) {
13000        final int overScrollMode = mOverScrollMode;
13001        final boolean canScrollHorizontal =
13002                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13003        final boolean canScrollVertical =
13004                computeVerticalScrollRange() > computeVerticalScrollExtent();
13005        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13006                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13007        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13008                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13009
13010        int newScrollX = scrollX + deltaX;
13011        if (!overScrollHorizontal) {
13012            maxOverScrollX = 0;
13013        }
13014
13015        int newScrollY = scrollY + deltaY;
13016        if (!overScrollVertical) {
13017            maxOverScrollY = 0;
13018        }
13019
13020        // Clamp values if at the limits and record
13021        final int left = -maxOverScrollX;
13022        final int right = maxOverScrollX + scrollRangeX;
13023        final int top = -maxOverScrollY;
13024        final int bottom = maxOverScrollY + scrollRangeY;
13025
13026        boolean clampedX = false;
13027        if (newScrollX > right) {
13028            newScrollX = right;
13029            clampedX = true;
13030        } else if (newScrollX < left) {
13031            newScrollX = left;
13032            clampedX = true;
13033        }
13034
13035        boolean clampedY = false;
13036        if (newScrollY > bottom) {
13037            newScrollY = bottom;
13038            clampedY = true;
13039        } else if (newScrollY < top) {
13040            newScrollY = top;
13041            clampedY = true;
13042        }
13043
13044        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13045
13046        return clampedX || clampedY;
13047    }
13048
13049    /**
13050     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13051     * respond to the results of an over-scroll operation.
13052     *
13053     * @param scrollX New X scroll value in pixels
13054     * @param scrollY New Y scroll value in pixels
13055     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13056     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13057     */
13058    protected void onOverScrolled(int scrollX, int scrollY,
13059            boolean clampedX, boolean clampedY) {
13060        // Intentionally empty.
13061    }
13062
13063    /**
13064     * Returns the over-scroll mode for this view. The result will be
13065     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13066     * (allow over-scrolling only if the view content is larger than the container),
13067     * or {@link #OVER_SCROLL_NEVER}.
13068     *
13069     * @return This view's over-scroll mode.
13070     */
13071    public int getOverScrollMode() {
13072        return mOverScrollMode;
13073    }
13074
13075    /**
13076     * Set the over-scroll mode for this view. Valid over-scroll modes are
13077     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13078     * (allow over-scrolling only if the view content is larger than the container),
13079     * or {@link #OVER_SCROLL_NEVER}.
13080     *
13081     * Setting the over-scroll mode of a view will have an effect only if the
13082     * view is capable of scrolling.
13083     *
13084     * @param overScrollMode The new over-scroll mode for this view.
13085     */
13086    public void setOverScrollMode(int overScrollMode) {
13087        if (overScrollMode != OVER_SCROLL_ALWAYS &&
13088                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
13089                overScrollMode != OVER_SCROLL_NEVER) {
13090            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
13091        }
13092        mOverScrollMode = overScrollMode;
13093    }
13094
13095    /**
13096     * Gets a scale factor that determines the distance the view should scroll
13097     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
13098     * @return The vertical scroll scale factor.
13099     * @hide
13100     */
13101    protected float getVerticalScrollFactor() {
13102        if (mVerticalScrollFactor == 0) {
13103            TypedValue outValue = new TypedValue();
13104            if (!mContext.getTheme().resolveAttribute(
13105                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
13106                throw new IllegalStateException(
13107                        "Expected theme to define listPreferredItemHeight.");
13108            }
13109            mVerticalScrollFactor = outValue.getDimension(
13110                    mContext.getResources().getDisplayMetrics());
13111        }
13112        return mVerticalScrollFactor;
13113    }
13114
13115    /**
13116     * Gets a scale factor that determines the distance the view should scroll
13117     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
13118     * @return The horizontal scroll scale factor.
13119     * @hide
13120     */
13121    protected float getHorizontalScrollFactor() {
13122        // TODO: Should use something else.
13123        return getVerticalScrollFactor();
13124    }
13125
13126    /**
13127     * Return the value specifying the text direction or policy that was set with
13128     * {@link #setTextDirection(int)}.
13129     *
13130     * @return the defined text direction. It can be one of:
13131     *
13132     * {@link #TEXT_DIRECTION_INHERIT},
13133     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13134     * {@link #TEXT_DIRECTION_ANY_RTL},
13135     * {@link #TEXT_DIRECTION_CHAR_COUNT},
13136     * {@link #TEXT_DIRECTION_LTR},
13137     * {@link #TEXT_DIRECTION_RTL},
13138     *
13139     * @hide
13140     */
13141    public int getTextDirection() {
13142        return mTextDirection;
13143    }
13144
13145    /**
13146     * Set the text direction.
13147     *
13148     * @param textDirection the direction to set. Should be one of:
13149     *
13150     * {@link #TEXT_DIRECTION_INHERIT},
13151     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13152     * {@link #TEXT_DIRECTION_ANY_RTL},
13153     * {@link #TEXT_DIRECTION_CHAR_COUNT},
13154     * {@link #TEXT_DIRECTION_LTR},
13155     * {@link #TEXT_DIRECTION_RTL},
13156     *
13157     * @hide
13158     */
13159    public void setTextDirection(int textDirection) {
13160        if (textDirection != mTextDirection) {
13161            mTextDirection = textDirection;
13162            resetResolvedTextDirection();
13163            requestLayout();
13164        }
13165    }
13166
13167    /**
13168     * Return the resolved text direction.
13169     *
13170     * @return the resolved text direction. Return one of:
13171     *
13172     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13173     * {@link #TEXT_DIRECTION_ANY_RTL},
13174     * {@link #TEXT_DIRECTION_CHAR_COUNT},
13175     * {@link #TEXT_DIRECTION_LTR},
13176     * {@link #TEXT_DIRECTION_RTL},
13177     *
13178     * @hide
13179     */
13180    public int getResolvedTextDirection() {
13181        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
13182            resolveTextDirection();
13183        }
13184        return mResolvedTextDirection;
13185    }
13186
13187    /**
13188     * Resolve the text direction.
13189     */
13190    protected void resolveTextDirection() {
13191        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
13192            mResolvedTextDirection = mTextDirection;
13193            return;
13194        }
13195        if (mParent != null && mParent instanceof ViewGroup) {
13196            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
13197            return;
13198        }
13199        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
13200    }
13201
13202    /**
13203     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
13204     */
13205    protected void resetResolvedTextDirection() {
13206        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
13207    }
13208
13209    //
13210    // Properties
13211    //
13212    /**
13213     * A Property wrapper around the <code>alpha</code> functionality handled by the
13214     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
13215     */
13216    public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
13217        @Override
13218        public void setValue(View object, float value) {
13219            object.setAlpha(value);
13220        }
13221
13222        @Override
13223        public Float get(View object) {
13224            return object.getAlpha();
13225        }
13226    };
13227
13228    /**
13229     * A Property wrapper around the <code>translationX</code> functionality handled by the
13230     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
13231     */
13232    public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
13233        @Override
13234        public void setValue(View object, float value) {
13235            object.setTranslationX(value);
13236        }
13237
13238                @Override
13239        public Float get(View object) {
13240            return object.getTranslationX();
13241        }
13242    };
13243
13244    /**
13245     * A Property wrapper around the <code>translationY</code> functionality handled by the
13246     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
13247     */
13248    public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
13249        @Override
13250        public void setValue(View object, float value) {
13251            object.setTranslationY(value);
13252        }
13253
13254        @Override
13255        public Float get(View object) {
13256            return object.getTranslationY();
13257        }
13258    };
13259
13260    /**
13261     * A Property wrapper around the <code>x</code> functionality handled by the
13262     * {@link View#setX(float)} and {@link View#getX()} methods.
13263     */
13264    public static Property<View, Float> X = new FloatProperty<View>("x") {
13265        @Override
13266        public void setValue(View object, float value) {
13267            object.setX(value);
13268        }
13269
13270        @Override
13271        public Float get(View object) {
13272            return object.getX();
13273        }
13274    };
13275
13276    /**
13277     * A Property wrapper around the <code>y</code> functionality handled by the
13278     * {@link View#setY(float)} and {@link View#getY()} methods.
13279     */
13280    public static Property<View, Float> Y = new FloatProperty<View>("y") {
13281        @Override
13282        public void setValue(View object, float value) {
13283            object.setY(value);
13284        }
13285
13286        @Override
13287        public Float get(View object) {
13288            return object.getY();
13289        }
13290    };
13291
13292    /**
13293     * A Property wrapper around the <code>rotation</code> functionality handled by the
13294     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
13295     */
13296    public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
13297        @Override
13298        public void setValue(View object, float value) {
13299            object.setRotation(value);
13300        }
13301
13302        @Override
13303        public Float get(View object) {
13304            return object.getRotation();
13305        }
13306    };
13307
13308    /**
13309     * A Property wrapper around the <code>rotationX</code> functionality handled by the
13310     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
13311     */
13312    public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
13313        @Override
13314        public void setValue(View object, float value) {
13315            object.setRotationX(value);
13316        }
13317
13318        @Override
13319        public Float get(View object) {
13320            return object.getRotationX();
13321        }
13322    };
13323
13324    /**
13325     * A Property wrapper around the <code>rotationY</code> functionality handled by the
13326     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
13327     */
13328    public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
13329        @Override
13330        public void setValue(View object, float value) {
13331            object.setRotationY(value);
13332        }
13333
13334        @Override
13335        public Float get(View object) {
13336            return object.getRotationY();
13337        }
13338    };
13339
13340    /**
13341     * A Property wrapper around the <code>scaleX</code> functionality handled by the
13342     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
13343     */
13344    public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
13345        @Override
13346        public void setValue(View object, float value) {
13347            object.setScaleX(value);
13348        }
13349
13350        @Override
13351        public Float get(View object) {
13352            return object.getScaleX();
13353        }
13354    };
13355
13356    /**
13357     * A Property wrapper around the <code>scaleY</code> functionality handled by the
13358     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
13359     */
13360    public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
13361        @Override
13362        public void setValue(View object, float value) {
13363            object.setScaleY(value);
13364        }
13365
13366        @Override
13367        public Float get(View object) {
13368            return object.getScaleY();
13369        }
13370    };
13371
13372    /**
13373     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
13374     * Each MeasureSpec represents a requirement for either the width or the height.
13375     * A MeasureSpec is comprised of a size and a mode. There are three possible
13376     * modes:
13377     * <dl>
13378     * <dt>UNSPECIFIED</dt>
13379     * <dd>
13380     * The parent has not imposed any constraint on the child. It can be whatever size
13381     * it wants.
13382     * </dd>
13383     *
13384     * <dt>EXACTLY</dt>
13385     * <dd>
13386     * The parent has determined an exact size for the child. The child is going to be
13387     * given those bounds regardless of how big it wants to be.
13388     * </dd>
13389     *
13390     * <dt>AT_MOST</dt>
13391     * <dd>
13392     * The child can be as large as it wants up to the specified size.
13393     * </dd>
13394     * </dl>
13395     *
13396     * MeasureSpecs are implemented as ints to reduce object allocation. This class
13397     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
13398     */
13399    public static class MeasureSpec {
13400        private static final int MODE_SHIFT = 30;
13401        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
13402
13403        /**
13404         * Measure specification mode: The parent has not imposed any constraint
13405         * on the child. It can be whatever size it wants.
13406         */
13407        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
13408
13409        /**
13410         * Measure specification mode: The parent has determined an exact size
13411         * for the child. The child is going to be given those bounds regardless
13412         * of how big it wants to be.
13413         */
13414        public static final int EXACTLY     = 1 << MODE_SHIFT;
13415
13416        /**
13417         * Measure specification mode: The child can be as large as it wants up
13418         * to the specified size.
13419         */
13420        public static final int AT_MOST     = 2 << MODE_SHIFT;
13421
13422        /**
13423         * Creates a measure specification based on the supplied size and mode.
13424         *
13425         * The mode must always be one of the following:
13426         * <ul>
13427         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
13428         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
13429         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
13430         * </ul>
13431         *
13432         * @param size the size of the measure specification
13433         * @param mode the mode of the measure specification
13434         * @return the measure specification based on size and mode
13435         */
13436        public static int makeMeasureSpec(int size, int mode) {
13437            return size + mode;
13438        }
13439
13440        /**
13441         * Extracts the mode from the supplied measure specification.
13442         *
13443         * @param measureSpec the measure specification to extract the mode from
13444         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
13445         *         {@link android.view.View.MeasureSpec#AT_MOST} or
13446         *         {@link android.view.View.MeasureSpec#EXACTLY}
13447         */
13448        public static int getMode(int measureSpec) {
13449            return (measureSpec & MODE_MASK);
13450        }
13451
13452        /**
13453         * Extracts the size from the supplied measure specification.
13454         *
13455         * @param measureSpec the measure specification to extract the size from
13456         * @return the size in pixels defined in the supplied measure specification
13457         */
13458        public static int getSize(int measureSpec) {
13459            return (measureSpec & ~MODE_MASK);
13460        }
13461
13462        /**
13463         * Returns a String representation of the specified measure
13464         * specification.
13465         *
13466         * @param measureSpec the measure specification to convert to a String
13467         * @return a String with the following format: "MeasureSpec: MODE SIZE"
13468         */
13469        public static String toString(int measureSpec) {
13470            int mode = getMode(measureSpec);
13471            int size = getSize(measureSpec);
13472
13473            StringBuilder sb = new StringBuilder("MeasureSpec: ");
13474
13475            if (mode == UNSPECIFIED)
13476                sb.append("UNSPECIFIED ");
13477            else if (mode == EXACTLY)
13478                sb.append("EXACTLY ");
13479            else if (mode == AT_MOST)
13480                sb.append("AT_MOST ");
13481            else
13482                sb.append(mode).append(" ");
13483
13484            sb.append(size);
13485            return sb.toString();
13486        }
13487    }
13488
13489    class CheckForLongPress implements Runnable {
13490
13491        private int mOriginalWindowAttachCount;
13492
13493        public void run() {
13494            if (isPressed() && (mParent != null)
13495                    && mOriginalWindowAttachCount == mWindowAttachCount) {
13496                if (performLongClick()) {
13497                    mHasPerformedLongPress = true;
13498                }
13499            }
13500        }
13501
13502        public void rememberWindowAttachCount() {
13503            mOriginalWindowAttachCount = mWindowAttachCount;
13504        }
13505    }
13506
13507    private final class CheckForTap implements Runnable {
13508        public void run() {
13509            mPrivateFlags &= ~PREPRESSED;
13510            mPrivateFlags |= PRESSED;
13511            refreshDrawableState();
13512            checkForLongClick(ViewConfiguration.getTapTimeout());
13513        }
13514    }
13515
13516    private final class PerformClick implements Runnable {
13517        public void run() {
13518            performClick();
13519        }
13520    }
13521
13522    /** @hide */
13523    public void hackTurnOffWindowResizeAnim(boolean off) {
13524        mAttachInfo.mTurnOffWindowResizeAnim = off;
13525    }
13526
13527    /**
13528     * This method returns a ViewPropertyAnimator object, which can be used to animate
13529     * specific properties on this View.
13530     *
13531     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
13532     */
13533    public ViewPropertyAnimator animate() {
13534        if (mAnimator == null) {
13535            mAnimator = new ViewPropertyAnimator(this);
13536        }
13537        return mAnimator;
13538    }
13539
13540    /**
13541     * Interface definition for a callback to be invoked when a key event is
13542     * dispatched to this view. The callback will be invoked before the key
13543     * event is given to the view.
13544     */
13545    public interface OnKeyListener {
13546        /**
13547         * Called when a key is dispatched to a view. This allows listeners to
13548         * get a chance to respond before the target view.
13549         *
13550         * @param v The view the key has been dispatched to.
13551         * @param keyCode The code for the physical key that was pressed
13552         * @param event The KeyEvent object containing full information about
13553         *        the event.
13554         * @return True if the listener has consumed the event, false otherwise.
13555         */
13556        boolean onKey(View v, int keyCode, KeyEvent event);
13557    }
13558
13559    /**
13560     * Interface definition for a callback to be invoked when a touch event is
13561     * dispatched to this view. The callback will be invoked before the touch
13562     * event is given to the view.
13563     */
13564    public interface OnTouchListener {
13565        /**
13566         * Called when a touch event is dispatched to a view. This allows listeners to
13567         * get a chance to respond before the target view.
13568         *
13569         * @param v The view the touch event has been dispatched to.
13570         * @param event The MotionEvent object containing full information about
13571         *        the event.
13572         * @return True if the listener has consumed the event, false otherwise.
13573         */
13574        boolean onTouch(View v, MotionEvent event);
13575    }
13576
13577    /**
13578     * Interface definition for a callback to be invoked when a hover event is
13579     * dispatched to this view. The callback will be invoked before the hover
13580     * event is given to the view.
13581     */
13582    public interface OnHoverListener {
13583        /**
13584         * Called when a hover event is dispatched to a view. This allows listeners to
13585         * get a chance to respond before the target view.
13586         *
13587         * @param v The view the hover event has been dispatched to.
13588         * @param event The MotionEvent object containing full information about
13589         *        the event.
13590         * @return True if the listener has consumed the event, false otherwise.
13591         */
13592        boolean onHover(View v, MotionEvent event);
13593    }
13594
13595    /**
13596     * Interface definition for a callback to be invoked when a generic motion event is
13597     * dispatched to this view. The callback will be invoked before the generic motion
13598     * event is given to the view.
13599     */
13600    public interface OnGenericMotionListener {
13601        /**
13602         * Called when a generic motion event is dispatched to a view. This allows listeners to
13603         * get a chance to respond before the target view.
13604         *
13605         * @param v The view the generic motion event has been dispatched to.
13606         * @param event The MotionEvent object containing full information about
13607         *        the event.
13608         * @return True if the listener has consumed the event, false otherwise.
13609         */
13610        boolean onGenericMotion(View v, MotionEvent event);
13611    }
13612
13613    /**
13614     * Interface definition for a callback to be invoked when a view has been clicked and held.
13615     */
13616    public interface OnLongClickListener {
13617        /**
13618         * Called when a view has been clicked and held.
13619         *
13620         * @param v The view that was clicked and held.
13621         *
13622         * @return true if the callback consumed the long click, false otherwise.
13623         */
13624        boolean onLongClick(View v);
13625    }
13626
13627    /**
13628     * Interface definition for a callback to be invoked when a drag is being dispatched
13629     * to this view.  The callback will be invoked before the hosting view's own
13630     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
13631     * onDrag(event) behavior, it should return 'false' from this callback.
13632     */
13633    public interface OnDragListener {
13634        /**
13635         * Called when a drag event is dispatched to a view. This allows listeners
13636         * to get a chance to override base View behavior.
13637         *
13638         * @param v The View that received the drag event.
13639         * @param event The {@link android.view.DragEvent} object for the drag event.
13640         * @return {@code true} if the drag event was handled successfully, or {@code false}
13641         * if the drag event was not handled. Note that {@code false} will trigger the View
13642         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
13643         */
13644        boolean onDrag(View v, DragEvent event);
13645    }
13646
13647    /**
13648     * Interface definition for a callback to be invoked when the focus state of
13649     * a view changed.
13650     */
13651    public interface OnFocusChangeListener {
13652        /**
13653         * Called when the focus state of a view has changed.
13654         *
13655         * @param v The view whose state has changed.
13656         * @param hasFocus The new focus state of v.
13657         */
13658        void onFocusChange(View v, boolean hasFocus);
13659    }
13660
13661    /**
13662     * Interface definition for a callback to be invoked when a view is clicked.
13663     */
13664    public interface OnClickListener {
13665        /**
13666         * Called when a view has been clicked.
13667         *
13668         * @param v The view that was clicked.
13669         */
13670        void onClick(View v);
13671    }
13672
13673    /**
13674     * Interface definition for a callback to be invoked when the context menu
13675     * for this view is being built.
13676     */
13677    public interface OnCreateContextMenuListener {
13678        /**
13679         * Called when the context menu for this view is being built. It is not
13680         * safe to hold onto the menu after this method returns.
13681         *
13682         * @param menu The context menu that is being built
13683         * @param v The view for which the context menu is being built
13684         * @param menuInfo Extra information about the item for which the
13685         *            context menu should be shown. This information will vary
13686         *            depending on the class of v.
13687         */
13688        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
13689    }
13690
13691    /**
13692     * Interface definition for a callback to be invoked when the status bar changes
13693     * visibility.
13694     *
13695     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
13696     */
13697    public interface OnSystemUiVisibilityChangeListener {
13698        /**
13699         * Called when the status bar changes visibility because of a call to
13700         * {@link View#setSystemUiVisibility(int)}.
13701         *
13702         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13703         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13704         */
13705        public void onSystemUiVisibilityChange(int visibility);
13706    }
13707
13708    /**
13709     * Interface definition for a callback to be invoked when this view is attached
13710     * or detached from its window.
13711     */
13712    public interface OnAttachStateChangeListener {
13713        /**
13714         * Called when the view is attached to a window.
13715         * @param v The view that was attached
13716         */
13717        public void onViewAttachedToWindow(View v);
13718        /**
13719         * Called when the view is detached from a window.
13720         * @param v The view that was detached
13721         */
13722        public void onViewDetachedFromWindow(View v);
13723    }
13724
13725    private final class UnsetPressedState implements Runnable {
13726        public void run() {
13727            setPressed(false);
13728        }
13729    }
13730
13731    /**
13732     * Base class for derived classes that want to save and restore their own
13733     * state in {@link android.view.View#onSaveInstanceState()}.
13734     */
13735    public static class BaseSavedState extends AbsSavedState {
13736        /**
13737         * Constructor used when reading from a parcel. Reads the state of the superclass.
13738         *
13739         * @param source
13740         */
13741        public BaseSavedState(Parcel source) {
13742            super(source);
13743        }
13744
13745        /**
13746         * Constructor called by derived classes when creating their SavedState objects
13747         *
13748         * @param superState The state of the superclass of this view
13749         */
13750        public BaseSavedState(Parcelable superState) {
13751            super(superState);
13752        }
13753
13754        public static final Parcelable.Creator<BaseSavedState> CREATOR =
13755                new Parcelable.Creator<BaseSavedState>() {
13756            public BaseSavedState createFromParcel(Parcel in) {
13757                return new BaseSavedState(in);
13758            }
13759
13760            public BaseSavedState[] newArray(int size) {
13761                return new BaseSavedState[size];
13762            }
13763        };
13764    }
13765
13766    /**
13767     * A set of information given to a view when it is attached to its parent
13768     * window.
13769     */
13770    static class AttachInfo {
13771        interface Callbacks {
13772            void playSoundEffect(int effectId);
13773            boolean performHapticFeedback(int effectId, boolean always);
13774        }
13775
13776        /**
13777         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
13778         * to a Handler. This class contains the target (View) to invalidate and
13779         * the coordinates of the dirty rectangle.
13780         *
13781         * For performance purposes, this class also implements a pool of up to
13782         * POOL_LIMIT objects that get reused. This reduces memory allocations
13783         * whenever possible.
13784         */
13785        static class InvalidateInfo implements Poolable<InvalidateInfo> {
13786            private static final int POOL_LIMIT = 10;
13787            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
13788                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
13789                        public InvalidateInfo newInstance() {
13790                            return new InvalidateInfo();
13791                        }
13792
13793                        public void onAcquired(InvalidateInfo element) {
13794                        }
13795
13796                        public void onReleased(InvalidateInfo element) {
13797                        }
13798                    }, POOL_LIMIT)
13799            );
13800
13801            private InvalidateInfo mNext;
13802            private boolean mIsPooled;
13803
13804            View target;
13805
13806            int left;
13807            int top;
13808            int right;
13809            int bottom;
13810
13811            public void setNextPoolable(InvalidateInfo element) {
13812                mNext = element;
13813            }
13814
13815            public InvalidateInfo getNextPoolable() {
13816                return mNext;
13817            }
13818
13819            static InvalidateInfo acquire() {
13820                return sPool.acquire();
13821            }
13822
13823            void release() {
13824                sPool.release(this);
13825            }
13826
13827            public boolean isPooled() {
13828                return mIsPooled;
13829            }
13830
13831            public void setPooled(boolean isPooled) {
13832                mIsPooled = isPooled;
13833            }
13834        }
13835
13836        final IWindowSession mSession;
13837
13838        final IWindow mWindow;
13839
13840        final IBinder mWindowToken;
13841
13842        final Callbacks mRootCallbacks;
13843
13844        HardwareCanvas mHardwareCanvas;
13845
13846        /**
13847         * The top view of the hierarchy.
13848         */
13849        View mRootView;
13850
13851        IBinder mPanelParentWindowToken;
13852        Surface mSurface;
13853
13854        boolean mHardwareAccelerated;
13855        boolean mHardwareAccelerationRequested;
13856        HardwareRenderer mHardwareRenderer;
13857
13858        /**
13859         * Scale factor used by the compatibility mode
13860         */
13861        float mApplicationScale;
13862
13863        /**
13864         * Indicates whether the application is in compatibility mode
13865         */
13866        boolean mScalingRequired;
13867
13868        /**
13869         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
13870         */
13871        boolean mTurnOffWindowResizeAnim;
13872
13873        /**
13874         * Left position of this view's window
13875         */
13876        int mWindowLeft;
13877
13878        /**
13879         * Top position of this view's window
13880         */
13881        int mWindowTop;
13882
13883        /**
13884         * Indicates whether views need to use 32-bit drawing caches
13885         */
13886        boolean mUse32BitDrawingCache;
13887
13888        /**
13889         * For windows that are full-screen but using insets to layout inside
13890         * of the screen decorations, these are the current insets for the
13891         * content of the window.
13892         */
13893        final Rect mContentInsets = new Rect();
13894
13895        /**
13896         * For windows that are full-screen but using insets to layout inside
13897         * of the screen decorations, these are the current insets for the
13898         * actual visible parts of the window.
13899         */
13900        final Rect mVisibleInsets = new Rect();
13901
13902        /**
13903         * The internal insets given by this window.  This value is
13904         * supplied by the client (through
13905         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
13906         * be given to the window manager when changed to be used in laying
13907         * out windows behind it.
13908         */
13909        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
13910                = new ViewTreeObserver.InternalInsetsInfo();
13911
13912        /**
13913         * All views in the window's hierarchy that serve as scroll containers,
13914         * used to determine if the window can be resized or must be panned
13915         * to adjust for a soft input area.
13916         */
13917        final ArrayList<View> mScrollContainers = new ArrayList<View>();
13918
13919        final KeyEvent.DispatcherState mKeyDispatchState
13920                = new KeyEvent.DispatcherState();
13921
13922        /**
13923         * Indicates whether the view's window currently has the focus.
13924         */
13925        boolean mHasWindowFocus;
13926
13927        /**
13928         * The current visibility of the window.
13929         */
13930        int mWindowVisibility;
13931
13932        /**
13933         * Indicates the time at which drawing started to occur.
13934         */
13935        long mDrawingTime;
13936
13937        /**
13938         * Indicates whether or not ignoring the DIRTY_MASK flags.
13939         */
13940        boolean mIgnoreDirtyState;
13941
13942        /**
13943         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
13944         * to avoid clearing that flag prematurely.
13945         */
13946        boolean mSetIgnoreDirtyState = false;
13947
13948        /**
13949         * Indicates whether the view's window is currently in touch mode.
13950         */
13951        boolean mInTouchMode;
13952
13953        /**
13954         * Indicates that ViewAncestor should trigger a global layout change
13955         * the next time it performs a traversal
13956         */
13957        boolean mRecomputeGlobalAttributes;
13958
13959        /**
13960         * Set during a traveral if any views want to keep the screen on.
13961         */
13962        boolean mKeepScreenOn;
13963
13964        /**
13965         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
13966         */
13967        int mSystemUiVisibility;
13968
13969        /**
13970         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
13971         * attached.
13972         */
13973        boolean mHasSystemUiListeners;
13974
13975        /**
13976         * Set if the visibility of any views has changed.
13977         */
13978        boolean mViewVisibilityChanged;
13979
13980        /**
13981         * Set to true if a view has been scrolled.
13982         */
13983        boolean mViewScrollChanged;
13984
13985        /**
13986         * Global to the view hierarchy used as a temporary for dealing with
13987         * x/y points in the transparent region computations.
13988         */
13989        final int[] mTransparentLocation = new int[2];
13990
13991        /**
13992         * Global to the view hierarchy used as a temporary for dealing with
13993         * x/y points in the ViewGroup.invalidateChild implementation.
13994         */
13995        final int[] mInvalidateChildLocation = new int[2];
13996
13997
13998        /**
13999         * Global to the view hierarchy used as a temporary for dealing with
14000         * x/y location when view is transformed.
14001         */
14002        final float[] mTmpTransformLocation = new float[2];
14003
14004        /**
14005         * The view tree observer used to dispatch global events like
14006         * layout, pre-draw, touch mode change, etc.
14007         */
14008        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14009
14010        /**
14011         * A Canvas used by the view hierarchy to perform bitmap caching.
14012         */
14013        Canvas mCanvas;
14014
14015        /**
14016         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14017         * handler can be used to pump events in the UI events queue.
14018         */
14019        final Handler mHandler;
14020
14021        /**
14022         * Identifier for messages requesting the view to be invalidated.
14023         * Such messages should be sent to {@link #mHandler}.
14024         */
14025        static final int INVALIDATE_MSG = 0x1;
14026
14027        /**
14028         * Identifier for messages requesting the view to invalidate a region.
14029         * Such messages should be sent to {@link #mHandler}.
14030         */
14031        static final int INVALIDATE_RECT_MSG = 0x2;
14032
14033        /**
14034         * Temporary for use in computing invalidate rectangles while
14035         * calling up the hierarchy.
14036         */
14037        final Rect mTmpInvalRect = new Rect();
14038
14039        /**
14040         * Temporary for use in computing hit areas with transformed views
14041         */
14042        final RectF mTmpTransformRect = new RectF();
14043
14044        /**
14045         * Temporary list for use in collecting focusable descendents of a view.
14046         */
14047        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14048
14049        /**
14050         * The id of the window for accessibility purposes.
14051         */
14052        int mAccessibilityWindowId = View.NO_ID;
14053
14054        /**
14055         * Creates a new set of attachment information with the specified
14056         * events handler and thread.
14057         *
14058         * @param handler the events handler the view must use
14059         */
14060        AttachInfo(IWindowSession session, IWindow window,
14061                Handler handler, Callbacks effectPlayer) {
14062            mSession = session;
14063            mWindow = window;
14064            mWindowToken = window.asBinder();
14065            mHandler = handler;
14066            mRootCallbacks = effectPlayer;
14067        }
14068    }
14069
14070    /**
14071     * <p>ScrollabilityCache holds various fields used by a View when scrolling
14072     * is supported. This avoids keeping too many unused fields in most
14073     * instances of View.</p>
14074     */
14075    private static class ScrollabilityCache implements Runnable {
14076
14077        /**
14078         * Scrollbars are not visible
14079         */
14080        public static final int OFF = 0;
14081
14082        /**
14083         * Scrollbars are visible
14084         */
14085        public static final int ON = 1;
14086
14087        /**
14088         * Scrollbars are fading away
14089         */
14090        public static final int FADING = 2;
14091
14092        public boolean fadeScrollBars;
14093
14094        public int fadingEdgeLength;
14095        public int scrollBarDefaultDelayBeforeFade;
14096        public int scrollBarFadeDuration;
14097
14098        public int scrollBarSize;
14099        public ScrollBarDrawable scrollBar;
14100        public float[] interpolatorValues;
14101        public View host;
14102
14103        public final Paint paint;
14104        public final Matrix matrix;
14105        public Shader shader;
14106
14107        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
14108
14109        private static final float[] OPAQUE = { 255 };
14110        private static final float[] TRANSPARENT = { 0.0f };
14111
14112        /**
14113         * When fading should start. This time moves into the future every time
14114         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
14115         */
14116        public long fadeStartTime;
14117
14118
14119        /**
14120         * The current state of the scrollbars: ON, OFF, or FADING
14121         */
14122        public int state = OFF;
14123
14124        private int mLastColor;
14125
14126        public ScrollabilityCache(ViewConfiguration configuration, View host) {
14127            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
14128            scrollBarSize = configuration.getScaledScrollBarSize();
14129            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
14130            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
14131
14132            paint = new Paint();
14133            matrix = new Matrix();
14134            // use use a height of 1, and then wack the matrix each time we
14135            // actually use it.
14136            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
14137
14138            paint.setShader(shader);
14139            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
14140            this.host = host;
14141        }
14142
14143        public void setFadeColor(int color) {
14144            if (color != 0 && color != mLastColor) {
14145                mLastColor = color;
14146                color |= 0xFF000000;
14147
14148                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
14149                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
14150
14151                paint.setShader(shader);
14152                // Restore the default transfer mode (src_over)
14153                paint.setXfermode(null);
14154            }
14155        }
14156
14157        public void run() {
14158            long now = AnimationUtils.currentAnimationTimeMillis();
14159            if (now >= fadeStartTime) {
14160
14161                // the animation fades the scrollbars out by changing
14162                // the opacity (alpha) from fully opaque to fully
14163                // transparent
14164                int nextFrame = (int) now;
14165                int framesCount = 0;
14166
14167                Interpolator interpolator = scrollBarInterpolator;
14168
14169                // Start opaque
14170                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
14171
14172                // End transparent
14173                nextFrame += scrollBarFadeDuration;
14174                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
14175
14176                state = FADING;
14177
14178                // Kick off the fade animation
14179                host.invalidate(true);
14180            }
14181        }
14182    }
14183
14184    /**
14185     * Resuable callback for sending
14186     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
14187     */
14188    private class SendViewScrolledAccessibilityEvent implements Runnable {
14189        public volatile boolean mIsPending;
14190
14191        public void run() {
14192            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
14193            mIsPending = false;
14194        }
14195    }
14196}
14197