View.java revision 2588a07730ff511329c87b5f61b20419b2443d48
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.text.TextUtils;
49import android.util.AttributeSet;
50import android.util.FloatProperty;
51import android.util.LocaleUtil;
52import android.util.Log;
53import android.util.Pool;
54import android.util.Poolable;
55import android.util.PoolableManager;
56import android.util.Pools;
57import android.util.Property;
58import android.util.SparseArray;
59import android.util.TypedValue;
60import android.view.ContextMenu.ContextMenuInfo;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityEventSource;
63import android.view.accessibility.AccessibilityManager;
64import android.view.accessibility.AccessibilityNodeInfo;
65import android.view.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.inputmethod.EditorInfo;
68import android.view.inputmethod.InputConnection;
69import android.view.inputmethod.InputMethodManager;
70import android.widget.ScrollBarDrawable;
71
72import static android.os.Build.VERSION_CODES.*;
73
74import com.android.internal.R;
75import com.android.internal.util.Predicate;
76import com.android.internal.view.menu.MenuBuilder;
77
78import java.lang.ref.WeakReference;
79import java.lang.reflect.InvocationTargetException;
80import java.lang.reflect.Method;
81import java.util.ArrayList;
82import java.util.Arrays;
83import java.util.Locale;
84import java.util.concurrent.CopyOnWriteArrayList;
85
86/**
87 * <p>
88 * This class represents the basic building block for user interface components. A View
89 * occupies a rectangular area on the screen and is responsible for drawing and
90 * event handling. View is the base class for <em>widgets</em>, which are
91 * used to create interactive UI components (buttons, text fields, etc.). The
92 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
93 * are invisible containers that hold other Views (or other ViewGroups) and define
94 * their layout properties.
95 * </p>
96 *
97 * <div class="special">
98 * <p>For an introduction to using this class to develop your
99 * application's user interface, read the Developer Guide documentation on
100 * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
101 * include:
102 * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
103 * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
104 * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
105 * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
106 * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
107 * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
108 * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
109 * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
110 * </p>
111 * </div>
112 *
113 * <a name="Using"></a>
114 * <h3>Using Views</h3>
115 * <p>
116 * All of the views in a window are arranged in a single tree. You can add views
117 * either from code or by specifying a tree of views in one or more XML layout
118 * files. There are many specialized subclasses of views that act as controls or
119 * are capable of displaying text, images, or other content.
120 * </p>
121 * <p>
122 * Once you have created a tree of views, there are typically a few types of
123 * common operations you may wish to perform:
124 * <ul>
125 * <li><strong>Set properties:</strong> for example setting the text of a
126 * {@link android.widget.TextView}. The available properties and the methods
127 * that set them will vary among the different subclasses of views. Note that
128 * properties that are known at build time can be set in the XML layout
129 * files.</li>
130 * <li><strong>Set focus:</strong> The framework will handled moving focus in
131 * response to user input. To force focus to a specific view, call
132 * {@link #requestFocus}.</li>
133 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
134 * that will be notified when something interesting happens to the view. For
135 * example, all views will let you set a listener to be notified when the view
136 * gains or loses focus. You can register such a listener using
137 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
138 * Other view subclasses offer more specialized listeners. For example, a Button
139 * exposes a listener to notify clients when the button is clicked.</li>
140 * <li><strong>Set visibility:</strong> You can hide or show views using
141 * {@link #setVisibility(int)}.</li>
142 * </ul>
143 * </p>
144 * <p><em>
145 * Note: The Android framework is responsible for measuring, laying out and
146 * drawing views. You should not call methods that perform these actions on
147 * views yourself unless you are actually implementing a
148 * {@link android.view.ViewGroup}.
149 * </em></p>
150 *
151 * <a name="Lifecycle"></a>
152 * <h3>Implementing a Custom View</h3>
153 *
154 * <p>
155 * To implement a custom view, you will usually begin by providing overrides for
156 * some of the standard methods that the framework calls on all views. You do
157 * not need to override all of these methods. In fact, you can start by just
158 * overriding {@link #onDraw(android.graphics.Canvas)}.
159 * <table border="2" width="85%" align="center" cellpadding="5">
160 *     <thead>
161 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
162 *     </thead>
163 *
164 *     <tbody>
165 *     <tr>
166 *         <td rowspan="2">Creation</td>
167 *         <td>Constructors</td>
168 *         <td>There is a form of the constructor that are called when the view
169 *         is created from code and a form that is called when the view is
170 *         inflated from a layout file. The second form should parse and apply
171 *         any attributes defined in the layout file.
172 *         </td>
173 *     </tr>
174 *     <tr>
175 *         <td><code>{@link #onFinishInflate()}</code></td>
176 *         <td>Called after a view and all of its children has been inflated
177 *         from XML.</td>
178 *     </tr>
179 *
180 *     <tr>
181 *         <td rowspan="3">Layout</td>
182 *         <td><code>{@link #onMeasure(int, int)}</code></td>
183 *         <td>Called to determine the size requirements for this view and all
184 *         of its children.
185 *         </td>
186 *     </tr>
187 *     <tr>
188 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
189 *         <td>Called when this view should assign a size and position to all
190 *         of its children.
191 *         </td>
192 *     </tr>
193 *     <tr>
194 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
195 *         <td>Called when the size of this view has changed.
196 *         </td>
197 *     </tr>
198 *
199 *     <tr>
200 *         <td>Drawing</td>
201 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
202 *         <td>Called when the view should render its content.
203 *         </td>
204 *     </tr>
205 *
206 *     <tr>
207 *         <td rowspan="4">Event processing</td>
208 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
209 *         <td>Called when a new key event occurs.
210 *         </td>
211 *     </tr>
212 *     <tr>
213 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
214 *         <td>Called when a key up event occurs.
215 *         </td>
216 *     </tr>
217 *     <tr>
218 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
219 *         <td>Called when a trackball motion event occurs.
220 *         </td>
221 *     </tr>
222 *     <tr>
223 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
224 *         <td>Called when a touch screen motion event occurs.
225 *         </td>
226 *     </tr>
227 *
228 *     <tr>
229 *         <td rowspan="2">Focus</td>
230 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
231 *         <td>Called when the view gains or loses focus.
232 *         </td>
233 *     </tr>
234 *
235 *     <tr>
236 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
237 *         <td>Called when the window containing the view gains or loses focus.
238 *         </td>
239 *     </tr>
240 *
241 *     <tr>
242 *         <td rowspan="3">Attaching</td>
243 *         <td><code>{@link #onAttachedToWindow()}</code></td>
244 *         <td>Called when the view is attached to a window.
245 *         </td>
246 *     </tr>
247 *
248 *     <tr>
249 *         <td><code>{@link #onDetachedFromWindow}</code></td>
250 *         <td>Called when the view is detached from its window.
251 *         </td>
252 *     </tr>
253 *
254 *     <tr>
255 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
256 *         <td>Called when the visibility of the window containing the view
257 *         has changed.
258 *         </td>
259 *     </tr>
260 *     </tbody>
261 *
262 * </table>
263 * </p>
264 *
265 * <a name="IDs"></a>
266 * <h3>IDs</h3>
267 * Views may have an integer id associated with them. These ids are typically
268 * assigned in the layout XML files, and are used to find specific views within
269 * the view tree. A common pattern is to:
270 * <ul>
271 * <li>Define a Button in the layout file and assign it a unique ID.
272 * <pre>
273 * &lt;Button
274 *     android:id="@+id/my_button"
275 *     android:layout_width="wrap_content"
276 *     android:layout_height="wrap_content"
277 *     android:text="@string/my_button_text"/&gt;
278 * </pre></li>
279 * <li>From the onCreate method of an Activity, find the Button
280 * <pre class="prettyprint">
281 *      Button myButton = (Button) findViewById(R.id.my_button);
282 * </pre></li>
283 * </ul>
284 * <p>
285 * View IDs need not be unique throughout the tree, but it is good practice to
286 * ensure that they are at least unique within the part of the tree you are
287 * searching.
288 * </p>
289 *
290 * <a name="Position"></a>
291 * <h3>Position</h3>
292 * <p>
293 * The geometry of a view is that of a rectangle. A view has a location,
294 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
295 * two dimensions, expressed as a width and a height. The unit for location
296 * and dimensions is the pixel.
297 * </p>
298 *
299 * <p>
300 * It is possible to retrieve the location of a view by invoking the methods
301 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
302 * coordinate of the rectangle representing the view. The latter returns the
303 * top, or Y, coordinate of the rectangle representing the view. These methods
304 * both return the location of the view relative to its parent. For instance,
305 * when getLeft() returns 20, that means the view is located 20 pixels to the
306 * right of the left edge of its direct parent.
307 * </p>
308 *
309 * <p>
310 * In addition, several convenience methods are offered to avoid unnecessary
311 * computations, namely {@link #getRight()} and {@link #getBottom()}.
312 * These methods return the coordinates of the right and bottom edges of the
313 * rectangle representing the view. For instance, calling {@link #getRight()}
314 * is similar to the following computation: <code>getLeft() + getWidth()</code>
315 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
316 * </p>
317 *
318 * <a name="SizePaddingMargins"></a>
319 * <h3>Size, padding and margins</h3>
320 * <p>
321 * The size of a view is expressed with a width and a height. A view actually
322 * possess two pairs of width and height values.
323 * </p>
324 *
325 * <p>
326 * The first pair is known as <em>measured width</em> and
327 * <em>measured height</em>. These dimensions define how big a view wants to be
328 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
329 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
330 * and {@link #getMeasuredHeight()}.
331 * </p>
332 *
333 * <p>
334 * The second pair is simply known as <em>width</em> and <em>height</em>, or
335 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
336 * dimensions define the actual size of the view on screen, at drawing time and
337 * after layout. These values may, but do not have to, be different from the
338 * measured width and height. The width and height can be obtained by calling
339 * {@link #getWidth()} and {@link #getHeight()}.
340 * </p>
341 *
342 * <p>
343 * To measure its dimensions, a view takes into account its padding. The padding
344 * is expressed in pixels for the left, top, right and bottom parts of the view.
345 * Padding can be used to offset the content of the view by a specific amount of
346 * pixels. For instance, a left padding of 2 will push the view's content by
347 * 2 pixels to the right of the left edge. Padding can be set using the
348 * {@link #setPadding(int, int, int, int)} method and queried by calling
349 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
350 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
351 * </p>
352 *
353 * <p>
354 * Even though a view can define a padding, it does not provide any support for
355 * margins. However, view groups provide such a support. Refer to
356 * {@link android.view.ViewGroup} and
357 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
358 * </p>
359 *
360 * <a name="Layout"></a>
361 * <h3>Layout</h3>
362 * <p>
363 * Layout is a two pass process: a measure pass and a layout pass. The measuring
364 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
365 * of the view tree. Each view pushes dimension specifications down the tree
366 * during the recursion. At the end of the measure pass, every view has stored
367 * its measurements. The second pass happens in
368 * {@link #layout(int,int,int,int)} and is also top-down. During
369 * this pass each parent is responsible for positioning all of its children
370 * using the sizes computed in the measure pass.
371 * </p>
372 *
373 * <p>
374 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
375 * {@link #getMeasuredHeight()} values must be set, along with those for all of
376 * that view's descendants. A view's measured width and measured height values
377 * must respect the constraints imposed by the view's parents. This guarantees
378 * that at the end of the measure pass, all parents accept all of their
379 * children's measurements. A parent view may call measure() more than once on
380 * its children. For example, the parent may measure each child once with
381 * unspecified dimensions to find out how big they want to be, then call
382 * measure() on them again with actual numbers if the sum of all the children's
383 * unconstrained sizes is too big or too small.
384 * </p>
385 *
386 * <p>
387 * The measure pass uses two classes to communicate dimensions. The
388 * {@link MeasureSpec} class is used by views to tell their parents how they
389 * want to be measured and positioned. The base LayoutParams class just
390 * describes how big the view wants to be for both width and height. For each
391 * dimension, it can specify one of:
392 * <ul>
393 * <li> an exact number
394 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
395 * (minus padding)
396 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
397 * enclose its content (plus padding).
398 * </ul>
399 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
400 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
401 * an X and Y value.
402 * </p>
403 *
404 * <p>
405 * MeasureSpecs are used to push requirements down the tree from parent to
406 * child. A MeasureSpec can be in one of three modes:
407 * <ul>
408 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
409 * of a child view. For example, a LinearLayout may call measure() on its child
410 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
411 * tall the child view wants to be given a width of 240 pixels.
412 * <li>EXACTLY: This is used by the parent to impose an exact size on the
413 * child. The child must use this size, and guarantee that all of its
414 * descendants will fit within this size.
415 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
416 * child. The child must gurantee that it and all of its descendants will fit
417 * within this size.
418 * </ul>
419 * </p>
420 *
421 * <p>
422 * To intiate a layout, call {@link #requestLayout}. This method is typically
423 * called by a view on itself when it believes that is can no longer fit within
424 * its current bounds.
425 * </p>
426 *
427 * <a name="Drawing"></a>
428 * <h3>Drawing</h3>
429 * <p>
430 * Drawing is handled by walking the tree and rendering each view that
431 * intersects the the invalid region. Because the tree is traversed in-order,
432 * this means that parents will draw before (i.e., behind) their children, with
433 * siblings drawn in the order they appear in the tree.
434 * If you set a background drawable for a View, then the View will draw it for you
435 * before calling back to its <code>onDraw()</code> method.
436 * </p>
437 *
438 * <p>
439 * Note that the framework will not draw views that are not in the invalid region.
440 * </p>
441 *
442 * <p>
443 * To force a view to draw, call {@link #invalidate()}.
444 * </p>
445 *
446 * <a name="EventHandlingThreading"></a>
447 * <h3>Event Handling and Threading</h3>
448 * <p>
449 * The basic cycle of a view is as follows:
450 * <ol>
451 * <li>An event comes in and is dispatched to the appropriate view. The view
452 * handles the event and notifies any listeners.</li>
453 * <li>If in the course of processing the event, the view's bounds may need
454 * to be changed, the view will call {@link #requestLayout()}.</li>
455 * <li>Similarly, if in the course of processing the event the view's appearance
456 * may need to be changed, the view will call {@link #invalidate()}.</li>
457 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
458 * the framework will take care of measuring, laying out, and drawing the tree
459 * as appropriate.</li>
460 * </ol>
461 * </p>
462 *
463 * <p><em>Note: The entire view tree is single threaded. You must always be on
464 * the UI thread when calling any method on any view.</em>
465 * If you are doing work on other threads and want to update the state of a view
466 * from that thread, you should use a {@link Handler}.
467 * </p>
468 *
469 * <a name="FocusHandling"></a>
470 * <h3>Focus Handling</h3>
471 * <p>
472 * The framework will handle routine focus movement in response to user input.
473 * This includes changing the focus as views are removed or hidden, or as new
474 * views become available. Views indicate their willingness to take focus
475 * through the {@link #isFocusable} method. To change whether a view can take
476 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
477 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
478 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
479 * </p>
480 * <p>
481 * Focus movement is based on an algorithm which finds the nearest neighbor in a
482 * given direction. In rare cases, the default algorithm may not match the
483 * intended behavior of the developer. In these situations, you can provide
484 * explicit overrides by using these XML attributes in the layout file:
485 * <pre>
486 * nextFocusDown
487 * nextFocusLeft
488 * nextFocusRight
489 * nextFocusUp
490 * </pre>
491 * </p>
492 *
493 *
494 * <p>
495 * To get a particular view to take focus, call {@link #requestFocus()}.
496 * </p>
497 *
498 * <a name="TouchMode"></a>
499 * <h3>Touch Mode</h3>
500 * <p>
501 * When a user is navigating a user interface via directional keys such as a D-pad, it is
502 * necessary to give focus to actionable items such as buttons so the user can see
503 * what will take input.  If the device has touch capabilities, however, and the user
504 * begins interacting with the interface by touching it, it is no longer necessary to
505 * always highlight, or give focus to, a particular view.  This motivates a mode
506 * for interaction named 'touch mode'.
507 * </p>
508 * <p>
509 * For a touch capable device, once the user touches the screen, the device
510 * will enter touch mode.  From this point onward, only views for which
511 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
512 * Other views that are touchable, like buttons, will not take focus when touched; they will
513 * only fire the on click listeners.
514 * </p>
515 * <p>
516 * Any time a user hits a directional key, such as a D-pad direction, the view device will
517 * exit touch mode, and find a view to take focus, so that the user may resume interacting
518 * with the user interface without touching the screen again.
519 * </p>
520 * <p>
521 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
522 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
523 * </p>
524 *
525 * <a name="Scrolling"></a>
526 * <h3>Scrolling</h3>
527 * <p>
528 * The framework provides basic support for views that wish to internally
529 * scroll their content. This includes keeping track of the X and Y scroll
530 * offset as well as mechanisms for drawing scrollbars. See
531 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
532 * {@link #awakenScrollBars()} for more details.
533 * </p>
534 *
535 * <a name="Tags"></a>
536 * <h3>Tags</h3>
537 * <p>
538 * Unlike IDs, tags are not used to identify views. Tags are essentially an
539 * extra piece of information that can be associated with a view. They are most
540 * often used as a convenience to store data related to views in the views
541 * themselves rather than by putting them in a separate structure.
542 * </p>
543 *
544 * <a name="Animation"></a>
545 * <h3>Animation</h3>
546 * <p>
547 * You can attach an {@link Animation} object to a view using
548 * {@link #setAnimation(Animation)} or
549 * {@link #startAnimation(Animation)}. The animation can alter the scale,
550 * rotation, translation and alpha of a view over time. If the animation is
551 * attached to a view that has children, the animation will affect the entire
552 * subtree rooted by that node. When an animation is started, the framework will
553 * take care of redrawing the appropriate views until the animation completes.
554 * </p>
555 * <p>
556 * Starting with Android 3.0, the preferred way of animating views is to use the
557 * {@link android.animation} package APIs.
558 * </p>
559 *
560 * <a name="Security"></a>
561 * <h3>Security</h3>
562 * <p>
563 * Sometimes it is essential that an application be able to verify that an action
564 * is being performed with the full knowledge and consent of the user, such as
565 * granting a permission request, making a purchase or clicking on an advertisement.
566 * Unfortunately, a malicious application could try to spoof the user into
567 * performing these actions, unaware, by concealing the intended purpose of the view.
568 * As a remedy, the framework offers a touch filtering mechanism that can be used to
569 * improve the security of views that provide access to sensitive functionality.
570 * </p><p>
571 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
572 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
573 * will discard touches that are received whenever the view's window is obscured by
574 * another visible window.  As a result, the view will not receive touches whenever a
575 * toast, dialog or other window appears above the view's window.
576 * </p><p>
577 * For more fine-grained control over security, consider overriding the
578 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
579 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
580 * </p>
581 *
582 * @attr ref android.R.styleable#View_alpha
583 * @attr ref android.R.styleable#View_background
584 * @attr ref android.R.styleable#View_clickable
585 * @attr ref android.R.styleable#View_contentDescription
586 * @attr ref android.R.styleable#View_drawingCacheQuality
587 * @attr ref android.R.styleable#View_duplicateParentState
588 * @attr ref android.R.styleable#View_id
589 * @attr ref android.R.styleable#View_requiresFadingEdge
590 * @attr ref android.R.styleable#View_fadingEdgeLength
591 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
592 * @attr ref android.R.styleable#View_fitsSystemWindows
593 * @attr ref android.R.styleable#View_isScrollContainer
594 * @attr ref android.R.styleable#View_focusable
595 * @attr ref android.R.styleable#View_focusableInTouchMode
596 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
597 * @attr ref android.R.styleable#View_keepScreenOn
598 * @attr ref android.R.styleable#View_layerType
599 * @attr ref android.R.styleable#View_longClickable
600 * @attr ref android.R.styleable#View_minHeight
601 * @attr ref android.R.styleable#View_minWidth
602 * @attr ref android.R.styleable#View_nextFocusDown
603 * @attr ref android.R.styleable#View_nextFocusLeft
604 * @attr ref android.R.styleable#View_nextFocusRight
605 * @attr ref android.R.styleable#View_nextFocusUp
606 * @attr ref android.R.styleable#View_onClick
607 * @attr ref android.R.styleable#View_padding
608 * @attr ref android.R.styleable#View_paddingBottom
609 * @attr ref android.R.styleable#View_paddingLeft
610 * @attr ref android.R.styleable#View_paddingRight
611 * @attr ref android.R.styleable#View_paddingTop
612 * @attr ref android.R.styleable#View_saveEnabled
613 * @attr ref android.R.styleable#View_rotation
614 * @attr ref android.R.styleable#View_rotationX
615 * @attr ref android.R.styleable#View_rotationY
616 * @attr ref android.R.styleable#View_scaleX
617 * @attr ref android.R.styleable#View_scaleY
618 * @attr ref android.R.styleable#View_scrollX
619 * @attr ref android.R.styleable#View_scrollY
620 * @attr ref android.R.styleable#View_scrollbarSize
621 * @attr ref android.R.styleable#View_scrollbarStyle
622 * @attr ref android.R.styleable#View_scrollbars
623 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
624 * @attr ref android.R.styleable#View_scrollbarFadeDuration
625 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
626 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
627 * @attr ref android.R.styleable#View_scrollbarThumbVertical
628 * @attr ref android.R.styleable#View_scrollbarTrackVertical
629 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
630 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
631 * @attr ref android.R.styleable#View_soundEffectsEnabled
632 * @attr ref android.R.styleable#View_tag
633 * @attr ref android.R.styleable#View_transformPivotX
634 * @attr ref android.R.styleable#View_transformPivotY
635 * @attr ref android.R.styleable#View_translationX
636 * @attr ref android.R.styleable#View_translationY
637 * @attr ref android.R.styleable#View_visibility
638 *
639 * @see android.view.ViewGroup
640 */
641public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
642        AccessibilityEventSource {
643    private static final boolean DBG = false;
644
645    /**
646     * The logging tag used by this class with android.util.Log.
647     */
648    protected static final String VIEW_LOG_TAG = "View";
649
650    /**
651     * Used to mark a View that has no ID.
652     */
653    public static final int NO_ID = -1;
654
655    /**
656     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
657     * calling setFlags.
658     */
659    private static final int NOT_FOCUSABLE = 0x00000000;
660
661    /**
662     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
663     * setFlags.
664     */
665    private static final int FOCUSABLE = 0x00000001;
666
667    /**
668     * Mask for use with setFlags indicating bits used for focus.
669     */
670    private static final int FOCUSABLE_MASK = 0x00000001;
671
672    /**
673     * This view will adjust its padding to fit sytem windows (e.g. status bar)
674     */
675    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
676
677    /**
678     * This view is visible.
679     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
680     * android:visibility}.
681     */
682    public static final int VISIBLE = 0x00000000;
683
684    /**
685     * This view is invisible, but it still takes up space for layout purposes.
686     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
687     * android:visibility}.
688     */
689    public static final int INVISIBLE = 0x00000004;
690
691    /**
692     * This view is invisible, and it doesn't take any space for layout
693     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
694     * android:visibility}.
695     */
696    public static final int GONE = 0x00000008;
697
698    /**
699     * Mask for use with setFlags indicating bits used for visibility.
700     * {@hide}
701     */
702    static final int VISIBILITY_MASK = 0x0000000C;
703
704    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
705
706    /**
707     * This view is enabled. Intrepretation varies by subclass.
708     * Use with ENABLED_MASK when calling setFlags.
709     * {@hide}
710     */
711    static final int ENABLED = 0x00000000;
712
713    /**
714     * This view is disabled. Intrepretation varies by subclass.
715     * Use with ENABLED_MASK when calling setFlags.
716     * {@hide}
717     */
718    static final int DISABLED = 0x00000020;
719
720   /**
721    * Mask for use with setFlags indicating bits used for indicating whether
722    * this view is enabled
723    * {@hide}
724    */
725    static final int ENABLED_MASK = 0x00000020;
726
727    /**
728     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
729     * called and further optimizations will be performed. It is okay to have
730     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
731     * {@hide}
732     */
733    static final int WILL_NOT_DRAW = 0x00000080;
734
735    /**
736     * Mask for use with setFlags indicating bits used for indicating whether
737     * this view is will draw
738     * {@hide}
739     */
740    static final int DRAW_MASK = 0x00000080;
741
742    /**
743     * <p>This view doesn't show scrollbars.</p>
744     * {@hide}
745     */
746    static final int SCROLLBARS_NONE = 0x00000000;
747
748    /**
749     * <p>This view shows horizontal scrollbars.</p>
750     * {@hide}
751     */
752    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
753
754    /**
755     * <p>This view shows vertical scrollbars.</p>
756     * {@hide}
757     */
758    static final int SCROLLBARS_VERTICAL = 0x00000200;
759
760    /**
761     * <p>Mask for use with setFlags indicating bits used for indicating which
762     * scrollbars are enabled.</p>
763     * {@hide}
764     */
765    static final int SCROLLBARS_MASK = 0x00000300;
766
767    /**
768     * Indicates that the view should filter touches when its window is obscured.
769     * Refer to the class comments for more information about this security feature.
770     * {@hide}
771     */
772    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
773
774    // note flag value 0x00000800 is now available for next flags...
775
776    /**
777     * <p>This view doesn't show fading edges.</p>
778     * {@hide}
779     */
780    static final int FADING_EDGE_NONE = 0x00000000;
781
782    /**
783     * <p>This view shows horizontal fading edges.</p>
784     * {@hide}
785     */
786    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
787
788    /**
789     * <p>This view shows vertical fading edges.</p>
790     * {@hide}
791     */
792    static final int FADING_EDGE_VERTICAL = 0x00002000;
793
794    /**
795     * <p>Mask for use with setFlags indicating bits used for indicating which
796     * fading edges are enabled.</p>
797     * {@hide}
798     */
799    static final int FADING_EDGE_MASK = 0x00003000;
800
801    /**
802     * <p>Indicates this view can be clicked. When clickable, a View reacts
803     * to clicks by notifying the OnClickListener.<p>
804     * {@hide}
805     */
806    static final int CLICKABLE = 0x00004000;
807
808    /**
809     * <p>Indicates this view is caching its drawing into a bitmap.</p>
810     * {@hide}
811     */
812    static final int DRAWING_CACHE_ENABLED = 0x00008000;
813
814    /**
815     * <p>Indicates that no icicle should be saved for this view.<p>
816     * {@hide}
817     */
818    static final int SAVE_DISABLED = 0x000010000;
819
820    /**
821     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
822     * property.</p>
823     * {@hide}
824     */
825    static final int SAVE_DISABLED_MASK = 0x000010000;
826
827    /**
828     * <p>Indicates that no drawing cache should ever be created for this view.<p>
829     * {@hide}
830     */
831    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
832
833    /**
834     * <p>Indicates this view can take / keep focus when int touch mode.</p>
835     * {@hide}
836     */
837    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
838
839    /**
840     * <p>Enables low quality mode for the drawing cache.</p>
841     */
842    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
843
844    /**
845     * <p>Enables high quality mode for the drawing cache.</p>
846     */
847    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
848
849    /**
850     * <p>Enables automatic quality mode for the drawing cache.</p>
851     */
852    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
853
854    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
855            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
856    };
857
858    /**
859     * <p>Mask for use with setFlags indicating bits used for the cache
860     * quality property.</p>
861     * {@hide}
862     */
863    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
864
865    /**
866     * <p>
867     * Indicates this view can be long clicked. When long clickable, a View
868     * reacts to long clicks by notifying the OnLongClickListener or showing a
869     * context menu.
870     * </p>
871     * {@hide}
872     */
873    static final int LONG_CLICKABLE = 0x00200000;
874
875    /**
876     * <p>Indicates that this view gets its drawable states from its direct parent
877     * and ignores its original internal states.</p>
878     *
879     * @hide
880     */
881    static final int DUPLICATE_PARENT_STATE = 0x00400000;
882
883    /**
884     * The scrollbar style to display the scrollbars inside the content area,
885     * without increasing the padding. The scrollbars will be overlaid with
886     * translucency on the view's content.
887     */
888    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
889
890    /**
891     * The scrollbar style to display the scrollbars inside the padded area,
892     * increasing the padding of the view. The scrollbars will not overlap the
893     * content area of the view.
894     */
895    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
896
897    /**
898     * The scrollbar style to display the scrollbars at the edge of the view,
899     * without increasing the padding. The scrollbars will be overlaid with
900     * translucency.
901     */
902    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
903
904    /**
905     * The scrollbar style to display the scrollbars at the edge of the view,
906     * increasing the padding of the view. The scrollbars will only overlap the
907     * background, if any.
908     */
909    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
910
911    /**
912     * Mask to check if the scrollbar style is overlay or inset.
913     * {@hide}
914     */
915    static final int SCROLLBARS_INSET_MASK = 0x01000000;
916
917    /**
918     * Mask to check if the scrollbar style is inside or outside.
919     * {@hide}
920     */
921    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
922
923    /**
924     * Mask for scrollbar style.
925     * {@hide}
926     */
927    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
928
929    /**
930     * View flag indicating that the screen should remain on while the
931     * window containing this view is visible to the user.  This effectively
932     * takes care of automatically setting the WindowManager's
933     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
934     */
935    public static final int KEEP_SCREEN_ON = 0x04000000;
936
937    /**
938     * View flag indicating whether this view should have sound effects enabled
939     * for events such as clicking and touching.
940     */
941    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
942
943    /**
944     * View flag indicating whether this view should have haptic feedback
945     * enabled for events such as long presses.
946     */
947    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
948
949    /**
950     * <p>Indicates that the view hierarchy should stop saving state when
951     * it reaches this view.  If state saving is initiated immediately at
952     * the view, it will be allowed.
953     * {@hide}
954     */
955    static final int PARENT_SAVE_DISABLED = 0x20000000;
956
957    /**
958     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
959     * {@hide}
960     */
961    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
962
963    /**
964     * Horizontal direction of this view is from Left to Right.
965     * Use with {@link #setLayoutDirection}.
966     * {@hide}
967     */
968    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
969
970    /**
971     * Horizontal direction of this view is from Right to Left.
972     * Use with {@link #setLayoutDirection}.
973     * {@hide}
974     */
975    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
976
977    /**
978     * Horizontal direction of this view is inherited from its parent.
979     * Use with {@link #setLayoutDirection}.
980     * {@hide}
981     */
982    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
983
984    /**
985     * Horizontal direction of this view is from deduced from the default language
986     * script for the locale. Use with {@link #setLayoutDirection}.
987     * {@hide}
988     */
989    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
990
991    /**
992     * Mask for use with setFlags indicating bits used for horizontalDirection.
993     * {@hide}
994     */
995    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
996
997    /*
998     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
999     * flag value.
1000     * {@hide}
1001     */
1002    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
1003        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
1004
1005    /**
1006     * Default horizontalDirection.
1007     * {@hide}
1008     */
1009    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1010
1011    /**
1012     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1013     * should add all focusable Views regardless if they are focusable in touch mode.
1014     */
1015    public static final int FOCUSABLES_ALL = 0x00000000;
1016
1017    /**
1018     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1019     * should add only Views focusable in touch mode.
1020     */
1021    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1022
1023    /**
1024     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1025     * item.
1026     */
1027    public static final int FOCUS_BACKWARD = 0x00000001;
1028
1029    /**
1030     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1031     * item.
1032     */
1033    public static final int FOCUS_FORWARD = 0x00000002;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move focus to the left.
1037     */
1038    public static final int FOCUS_LEFT = 0x00000011;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move focus up.
1042     */
1043    public static final int FOCUS_UP = 0x00000021;
1044
1045    /**
1046     * Use with {@link #focusSearch(int)}. Move focus to the right.
1047     */
1048    public static final int FOCUS_RIGHT = 0x00000042;
1049
1050    /**
1051     * Use with {@link #focusSearch(int)}. Move focus down.
1052     */
1053    public static final int FOCUS_DOWN = 0x00000082;
1054
1055    /**
1056     * Bits of {@link #getMeasuredWidthAndState()} and
1057     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1058     */
1059    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1060
1061    /**
1062     * Bits of {@link #getMeasuredWidthAndState()} and
1063     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1064     */
1065    public static final int MEASURED_STATE_MASK = 0xff000000;
1066
1067    /**
1068     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1069     * for functions that combine both width and height into a single int,
1070     * such as {@link #getMeasuredState()} and the childState argument of
1071     * {@link #resolveSizeAndState(int, int, int)}.
1072     */
1073    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1074
1075    /**
1076     * Bit of {@link #getMeasuredWidthAndState()} and
1077     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1078     * is smaller that the space the view would like to have.
1079     */
1080    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1081
1082    /**
1083     * Base View state sets
1084     */
1085    // Singles
1086    /**
1087     * Indicates the view has no states set. States are used with
1088     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1089     * view depending on its state.
1090     *
1091     * @see android.graphics.drawable.Drawable
1092     * @see #getDrawableState()
1093     */
1094    protected static final int[] EMPTY_STATE_SET;
1095    /**
1096     * Indicates the view is enabled. States are used with
1097     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1098     * view depending on its state.
1099     *
1100     * @see android.graphics.drawable.Drawable
1101     * @see #getDrawableState()
1102     */
1103    protected static final int[] ENABLED_STATE_SET;
1104    /**
1105     * Indicates the view is focused. States are used with
1106     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1107     * view depending on its state.
1108     *
1109     * @see android.graphics.drawable.Drawable
1110     * @see #getDrawableState()
1111     */
1112    protected static final int[] FOCUSED_STATE_SET;
1113    /**
1114     * Indicates the view is selected. States are used with
1115     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1116     * view depending on its state.
1117     *
1118     * @see android.graphics.drawable.Drawable
1119     * @see #getDrawableState()
1120     */
1121    protected static final int[] SELECTED_STATE_SET;
1122    /**
1123     * Indicates the view is pressed. States are used with
1124     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1125     * view depending on its state.
1126     *
1127     * @see android.graphics.drawable.Drawable
1128     * @see #getDrawableState()
1129     * @hide
1130     */
1131    protected static final int[] PRESSED_STATE_SET;
1132    /**
1133     * Indicates the view's window has focus. States are used with
1134     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1135     * view depending on its state.
1136     *
1137     * @see android.graphics.drawable.Drawable
1138     * @see #getDrawableState()
1139     */
1140    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1141    // Doubles
1142    /**
1143     * Indicates the view is enabled and has the focus.
1144     *
1145     * @see #ENABLED_STATE_SET
1146     * @see #FOCUSED_STATE_SET
1147     */
1148    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1149    /**
1150     * Indicates the view is enabled and selected.
1151     *
1152     * @see #ENABLED_STATE_SET
1153     * @see #SELECTED_STATE_SET
1154     */
1155    protected static final int[] ENABLED_SELECTED_STATE_SET;
1156    /**
1157     * Indicates the view is enabled and that its window has focus.
1158     *
1159     * @see #ENABLED_STATE_SET
1160     * @see #WINDOW_FOCUSED_STATE_SET
1161     */
1162    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1163    /**
1164     * Indicates the view is focused and selected.
1165     *
1166     * @see #FOCUSED_STATE_SET
1167     * @see #SELECTED_STATE_SET
1168     */
1169    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1170    /**
1171     * Indicates the view has the focus and that its window has the focus.
1172     *
1173     * @see #FOCUSED_STATE_SET
1174     * @see #WINDOW_FOCUSED_STATE_SET
1175     */
1176    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1177    /**
1178     * Indicates the view is selected and that its window has the focus.
1179     *
1180     * @see #SELECTED_STATE_SET
1181     * @see #WINDOW_FOCUSED_STATE_SET
1182     */
1183    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1184    // Triples
1185    /**
1186     * Indicates the view is enabled, focused and selected.
1187     *
1188     * @see #ENABLED_STATE_SET
1189     * @see #FOCUSED_STATE_SET
1190     * @see #SELECTED_STATE_SET
1191     */
1192    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1193    /**
1194     * Indicates the view is enabled, focused and its window has the focus.
1195     *
1196     * @see #ENABLED_STATE_SET
1197     * @see #FOCUSED_STATE_SET
1198     * @see #WINDOW_FOCUSED_STATE_SET
1199     */
1200    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is enabled, selected and its window has the focus.
1203     *
1204     * @see #ENABLED_STATE_SET
1205     * @see #SELECTED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is focused, selected and its window has the focus.
1211     *
1212     * @see #FOCUSED_STATE_SET
1213     * @see #SELECTED_STATE_SET
1214     * @see #WINDOW_FOCUSED_STATE_SET
1215     */
1216    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1217    /**
1218     * Indicates the view is enabled, focused, selected and its window
1219     * has the focus.
1220     *
1221     * @see #ENABLED_STATE_SET
1222     * @see #FOCUSED_STATE_SET
1223     * @see #SELECTED_STATE_SET
1224     * @see #WINDOW_FOCUSED_STATE_SET
1225     */
1226    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1227    /**
1228     * Indicates the view is pressed and its window has the focus.
1229     *
1230     * @see #PRESSED_STATE_SET
1231     * @see #WINDOW_FOCUSED_STATE_SET
1232     */
1233    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1234    /**
1235     * Indicates the view is pressed and selected.
1236     *
1237     * @see #PRESSED_STATE_SET
1238     * @see #SELECTED_STATE_SET
1239     */
1240    protected static final int[] PRESSED_SELECTED_STATE_SET;
1241    /**
1242     * Indicates the view is pressed, selected and its window has the focus.
1243     *
1244     * @see #PRESSED_STATE_SET
1245     * @see #SELECTED_STATE_SET
1246     * @see #WINDOW_FOCUSED_STATE_SET
1247     */
1248    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1249    /**
1250     * Indicates the view is pressed and focused.
1251     *
1252     * @see #PRESSED_STATE_SET
1253     * @see #FOCUSED_STATE_SET
1254     */
1255    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1256    /**
1257     * Indicates the view is pressed, focused and its window has the focus.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #FOCUSED_STATE_SET
1261     * @see #WINDOW_FOCUSED_STATE_SET
1262     */
1263    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1264    /**
1265     * Indicates the view is pressed, focused and selected.
1266     *
1267     * @see #PRESSED_STATE_SET
1268     * @see #SELECTED_STATE_SET
1269     * @see #FOCUSED_STATE_SET
1270     */
1271    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1272    /**
1273     * Indicates the view is pressed, focused, selected and its window has the focus.
1274     *
1275     * @see #PRESSED_STATE_SET
1276     * @see #FOCUSED_STATE_SET
1277     * @see #SELECTED_STATE_SET
1278     * @see #WINDOW_FOCUSED_STATE_SET
1279     */
1280    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1281    /**
1282     * Indicates the view is pressed and enabled.
1283     *
1284     * @see #PRESSED_STATE_SET
1285     * @see #ENABLED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_ENABLED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, enabled and its window has the focus.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #ENABLED_STATE_SET
1293     * @see #WINDOW_FOCUSED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, enabled and selected.
1298     *
1299     * @see #PRESSED_STATE_SET
1300     * @see #ENABLED_STATE_SET
1301     * @see #SELECTED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed, enabled, selected and its window has the
1306     * focus.
1307     *
1308     * @see #PRESSED_STATE_SET
1309     * @see #ENABLED_STATE_SET
1310     * @see #SELECTED_STATE_SET
1311     * @see #WINDOW_FOCUSED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, enabled and focused.
1316     *
1317     * @see #PRESSED_STATE_SET
1318     * @see #ENABLED_STATE_SET
1319     * @see #FOCUSED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed, enabled, focused and its window has the
1324     * focus.
1325     *
1326     * @see #PRESSED_STATE_SET
1327     * @see #ENABLED_STATE_SET
1328     * @see #FOCUSED_STATE_SET
1329     * @see #WINDOW_FOCUSED_STATE_SET
1330     */
1331    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1332    /**
1333     * Indicates the view is pressed, enabled, focused and selected.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #ENABLED_STATE_SET
1337     * @see #SELECTED_STATE_SET
1338     * @see #FOCUSED_STATE_SET
1339     */
1340    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1341    /**
1342     * Indicates the view is pressed, enabled, focused, selected and its window
1343     * has the focus.
1344     *
1345     * @see #PRESSED_STATE_SET
1346     * @see #ENABLED_STATE_SET
1347     * @see #SELECTED_STATE_SET
1348     * @see #FOCUSED_STATE_SET
1349     * @see #WINDOW_FOCUSED_STATE_SET
1350     */
1351    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1352
1353    /**
1354     * The order here is very important to {@link #getDrawableState()}
1355     */
1356    private static final int[][] VIEW_STATE_SETS;
1357
1358    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1359    static final int VIEW_STATE_SELECTED = 1 << 1;
1360    static final int VIEW_STATE_FOCUSED = 1 << 2;
1361    static final int VIEW_STATE_ENABLED = 1 << 3;
1362    static final int VIEW_STATE_PRESSED = 1 << 4;
1363    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1364    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1365    static final int VIEW_STATE_HOVERED = 1 << 7;
1366    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1367    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1368
1369    static final int[] VIEW_STATE_IDS = new int[] {
1370        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1371        R.attr.state_selected,          VIEW_STATE_SELECTED,
1372        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1373        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1374        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1375        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1376        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1377        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1378        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1379        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1380    };
1381
1382    static {
1383        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1384            throw new IllegalStateException(
1385                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1386        }
1387        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1388        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1389            int viewState = R.styleable.ViewDrawableStates[i];
1390            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1391                if (VIEW_STATE_IDS[j] == viewState) {
1392                    orderedIds[i * 2] = viewState;
1393                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1394                }
1395            }
1396        }
1397        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1398        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1399        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1400            int numBits = Integer.bitCount(i);
1401            int[] set = new int[numBits];
1402            int pos = 0;
1403            for (int j = 0; j < orderedIds.length; j += 2) {
1404                if ((i & orderedIds[j+1]) != 0) {
1405                    set[pos++] = orderedIds[j];
1406                }
1407            }
1408            VIEW_STATE_SETS[i] = set;
1409        }
1410
1411        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1412        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1413        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1414        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1415                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1416        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1417        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1419        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1421        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1423                | VIEW_STATE_FOCUSED];
1424        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1425        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1426                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1427        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1428                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1429        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1431                | VIEW_STATE_ENABLED];
1432        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1434        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1435                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1436                | VIEW_STATE_ENABLED];
1437        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1439                | VIEW_STATE_ENABLED];
1440        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1441                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1442                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1443
1444        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1445        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1446                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1447        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1449        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1451                | VIEW_STATE_PRESSED];
1452        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1454        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1455                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1456                | VIEW_STATE_PRESSED];
1457        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1459                | VIEW_STATE_PRESSED];
1460        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1462                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1465        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1466                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1467                | VIEW_STATE_PRESSED];
1468        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1469                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1470                | VIEW_STATE_PRESSED];
1471        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1472                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1473                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1474        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1475                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1476                | VIEW_STATE_PRESSED];
1477        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1478                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1479                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1480        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1481                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1482                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1483        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1484                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1485                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1486                | VIEW_STATE_PRESSED];
1487    }
1488
1489    /**
1490     * Accessibility event types that are dispatched for text population.
1491     */
1492    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1493            AccessibilityEvent.TYPE_VIEW_CLICKED
1494            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1495            | AccessibilityEvent.TYPE_VIEW_SELECTED
1496            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1497            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1498            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1499            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT;
1500
1501    /**
1502     * Temporary Rect currently for use in setBackground().  This will probably
1503     * be extended in the future to hold our own class with more than just
1504     * a Rect. :)
1505     */
1506    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1507
1508    /**
1509     * Map used to store views' tags.
1510     */
1511    private SparseArray<Object> mKeyedTags;
1512
1513    /**
1514     * The next available accessiiblity id.
1515     */
1516    private static int sNextAccessibilityViewId;
1517
1518    /**
1519     * The animation currently associated with this view.
1520     * @hide
1521     */
1522    protected Animation mCurrentAnimation = null;
1523
1524    /**
1525     * Width as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredWidth;
1530
1531    /**
1532     * Height as measured during measure pass.
1533     * {@hide}
1534     */
1535    @ViewDebug.ExportedProperty(category = "measurement")
1536    int mMeasuredHeight;
1537
1538    /**
1539     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1540     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1541     * its display list. This flag, used only when hw accelerated, allows us to clear the
1542     * flag while retaining this information until it's needed (at getDisplayList() time and
1543     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1544     *
1545     * {@hide}
1546     */
1547    boolean mRecreateDisplayList = false;
1548
1549    /**
1550     * The view's identifier.
1551     * {@hide}
1552     *
1553     * @see #setId(int)
1554     * @see #getId()
1555     */
1556    @ViewDebug.ExportedProperty(resolveId = true)
1557    int mID = NO_ID;
1558
1559    /**
1560     * The stable ID of this view for accessibility porposes.
1561     */
1562    int mAccessibilityViewId = NO_ID;
1563
1564    /**
1565     * The view's tag.
1566     * {@hide}
1567     *
1568     * @see #setTag(Object)
1569     * @see #getTag()
1570     */
1571    protected Object mTag;
1572
1573    // for mPrivateFlags:
1574    /** {@hide} */
1575    static final int WANTS_FOCUS                    = 0x00000001;
1576    /** {@hide} */
1577    static final int FOCUSED                        = 0x00000002;
1578    /** {@hide} */
1579    static final int SELECTED                       = 0x00000004;
1580    /** {@hide} */
1581    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1582    /** {@hide} */
1583    static final int HAS_BOUNDS                     = 0x00000010;
1584    /** {@hide} */
1585    static final int DRAWN                          = 0x00000020;
1586    /**
1587     * When this flag is set, this view is running an animation on behalf of its
1588     * children and should therefore not cancel invalidate requests, even if they
1589     * lie outside of this view's bounds.
1590     *
1591     * {@hide}
1592     */
1593    static final int DRAW_ANIMATION                 = 0x00000040;
1594    /** {@hide} */
1595    static final int SKIP_DRAW                      = 0x00000080;
1596    /** {@hide} */
1597    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1598    /** {@hide} */
1599    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1600    /** {@hide} */
1601    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1602    /** {@hide} */
1603    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1604    /** {@hide} */
1605    static final int FORCE_LAYOUT                   = 0x00001000;
1606    /** {@hide} */
1607    static final int LAYOUT_REQUIRED                = 0x00002000;
1608
1609    private static final int PRESSED                = 0x00004000;
1610
1611    /** {@hide} */
1612    static final int DRAWING_CACHE_VALID            = 0x00008000;
1613    /**
1614     * Flag used to indicate that this view should be drawn once more (and only once
1615     * more) after its animation has completed.
1616     * {@hide}
1617     */
1618    static final int ANIMATION_STARTED              = 0x00010000;
1619
1620    private static final int SAVE_STATE_CALLED      = 0x00020000;
1621
1622    /**
1623     * Indicates that the View returned true when onSetAlpha() was called and that
1624     * the alpha must be restored.
1625     * {@hide}
1626     */
1627    static final int ALPHA_SET                      = 0x00040000;
1628
1629    /**
1630     * Set by {@link #setScrollContainer(boolean)}.
1631     */
1632    static final int SCROLL_CONTAINER               = 0x00080000;
1633
1634    /**
1635     * Set by {@link #setScrollContainer(boolean)}.
1636     */
1637    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1638
1639    /**
1640     * View flag indicating whether this view was invalidated (fully or partially.)
1641     *
1642     * @hide
1643     */
1644    static final int DIRTY                          = 0x00200000;
1645
1646    /**
1647     * View flag indicating whether this view was invalidated by an opaque
1648     * invalidate request.
1649     *
1650     * @hide
1651     */
1652    static final int DIRTY_OPAQUE                   = 0x00400000;
1653
1654    /**
1655     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1656     *
1657     * @hide
1658     */
1659    static final int DIRTY_MASK                     = 0x00600000;
1660
1661    /**
1662     * Indicates whether the background is opaque.
1663     *
1664     * @hide
1665     */
1666    static final int OPAQUE_BACKGROUND              = 0x00800000;
1667
1668    /**
1669     * Indicates whether the scrollbars are opaque.
1670     *
1671     * @hide
1672     */
1673    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1674
1675    /**
1676     * Indicates whether the view is opaque.
1677     *
1678     * @hide
1679     */
1680    static final int OPAQUE_MASK                    = 0x01800000;
1681
1682    /**
1683     * Indicates a prepressed state;
1684     * the short time between ACTION_DOWN and recognizing
1685     * a 'real' press. Prepressed is used to recognize quick taps
1686     * even when they are shorter than ViewConfiguration.getTapTimeout().
1687     *
1688     * @hide
1689     */
1690    private static final int PREPRESSED             = 0x02000000;
1691
1692    /**
1693     * Indicates whether the view is temporarily detached.
1694     *
1695     * @hide
1696     */
1697    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1698
1699    /**
1700     * Indicates that we should awaken scroll bars once attached
1701     *
1702     * @hide
1703     */
1704    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1705
1706    /**
1707     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1708     * @hide
1709     */
1710    private static final int HOVERED              = 0x10000000;
1711
1712    /**
1713     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1714     * for transform operations
1715     *
1716     * @hide
1717     */
1718    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1719
1720    /** {@hide} */
1721    static final int ACTIVATED                    = 0x40000000;
1722
1723    /**
1724     * Indicates that this view was specifically invalidated, not just dirtied because some
1725     * child view was invalidated. The flag is used to determine when we need to recreate
1726     * a view's display list (as opposed to just returning a reference to its existing
1727     * display list).
1728     *
1729     * @hide
1730     */
1731    static final int INVALIDATED                  = 0x80000000;
1732
1733    /* Masks for mPrivateFlags2 */
1734
1735    /**
1736     * Indicates that this view has reported that it can accept the current drag's content.
1737     * Cleared when the drag operation concludes.
1738     * @hide
1739     */
1740    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1741
1742    /**
1743     * Indicates that this view is currently directly under the drag location in a
1744     * drag-and-drop operation involving content that it can accept.  Cleared when
1745     * the drag exits the view, or when the drag operation concludes.
1746     * @hide
1747     */
1748    static final int DRAG_HOVERED                 = 0x00000002;
1749
1750    /**
1751     * Indicates whether the view layout direction has been resolved and drawn to the
1752     * right-to-left direction.
1753     *
1754     * @hide
1755     */
1756    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1757
1758    /**
1759     * Indicates whether the view layout direction has been resolved.
1760     *
1761     * @hide
1762     */
1763    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1764
1765
1766    /* End of masks for mPrivateFlags2 */
1767
1768    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1769
1770    /**
1771     * Always allow a user to over-scroll this view, provided it is a
1772     * view that can scroll.
1773     *
1774     * @see #getOverScrollMode()
1775     * @see #setOverScrollMode(int)
1776     */
1777    public static final int OVER_SCROLL_ALWAYS = 0;
1778
1779    /**
1780     * Allow a user to over-scroll this view only if the content is large
1781     * enough to meaningfully scroll, provided it is a view that can scroll.
1782     *
1783     * @see #getOverScrollMode()
1784     * @see #setOverScrollMode(int)
1785     */
1786    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1787
1788    /**
1789     * Never allow a user to over-scroll this view.
1790     *
1791     * @see #getOverScrollMode()
1792     * @see #setOverScrollMode(int)
1793     */
1794    public static final int OVER_SCROLL_NEVER = 2;
1795
1796    /**
1797     * View has requested the system UI (status bar) to be visible (the default).
1798     *
1799     * @see #setSystemUiVisibility(int)
1800     */
1801    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1802
1803    /**
1804     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1805     *
1806     * This is for use in games, book readers, video players, or any other "immersive" application
1807     * where the usual system chrome is deemed too distracting.
1808     *
1809     * In low profile mode, the status bar and/or navigation icons may dim.
1810     *
1811     * @see #setSystemUiVisibility(int)
1812     */
1813    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1814
1815    /**
1816     * View has requested that the system navigation be temporarily hidden.
1817     *
1818     * This is an even less obtrusive state than that called for by
1819     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1820     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1821     * those to disappear. This is useful (in conjunction with the
1822     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1823     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1824     * window flags) for displaying content using every last pixel on the display.
1825     *
1826     * There is a limitation: because navigation controls are so important, the least user
1827     * interaction will cause them to reappear immediately.
1828     *
1829     * @see #setSystemUiVisibility(int)
1830     */
1831    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1832
1833    /**
1834     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1835     */
1836    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1837
1838    /**
1839     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1840     */
1841    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1842
1843    /**
1844     * @hide
1845     *
1846     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1847     * out of the public fields to keep the undefined bits out of the developer's way.
1848     *
1849     * Flag to make the status bar not expandable.  Unless you also
1850     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1851     */
1852    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
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 hide notification icons and scrolling ticker text.
1861     */
1862    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1863
1864    /**
1865     * @hide
1866     *
1867     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1868     * out of the public fields to keep the undefined bits out of the developer's way.
1869     *
1870     * Flag to disable incoming notification alerts.  This will not block
1871     * icons, but it will block sound, vibrating and other visual or aural notifications.
1872     */
1873    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1874
1875    /**
1876     * @hide
1877     *
1878     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1879     * out of the public fields to keep the undefined bits out of the developer's way.
1880     *
1881     * Flag to hide only the scrolling ticker.  Note that
1882     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1883     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1884     */
1885    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
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 the center system info area.
1894     */
1895    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1896
1897    /**
1898     * @hide
1899     *
1900     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1901     * out of the public fields to keep the undefined bits out of the developer's way.
1902     *
1903     * Flag to hide only the navigation buttons.  Don't use this
1904     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1905     *
1906     * THIS DOES NOT DISABLE THE BACK BUTTON
1907     */
1908    public static final int STATUS_BAR_DISABLE_NAVIGATION = 0x00200000;
1909
1910    /**
1911     * @hide
1912     *
1913     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1914     * out of the public fields to keep the undefined bits out of the developer's way.
1915     *
1916     * Flag to hide only the back button.  Don't use this
1917     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1918     */
1919    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1920
1921    /**
1922     * @hide
1923     *
1924     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1925     * out of the public fields to keep the undefined bits out of the developer's way.
1926     *
1927     * Flag to hide only the clock.  You might use this if your activity has
1928     * its own clock making the status bar's clock redundant.
1929     */
1930    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1931
1932    /**
1933     * @hide
1934     */
1935    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1936
1937    /**
1938     * Find views that render the specified text.
1939     *
1940     * @see #findViewsWithText(ArrayList, CharSequence, int)
1941     */
1942    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1943
1944    /**
1945     * Find find views that contain the specified content description.
1946     *
1947     * @see #findViewsWithText(ArrayList, CharSequence, int)
1948     */
1949    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1950
1951    /**
1952     * Controls the over-scroll mode for this view.
1953     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1954     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1955     * and {@link #OVER_SCROLL_NEVER}.
1956     */
1957    private int mOverScrollMode;
1958
1959    /**
1960     * The parent this view is attached to.
1961     * {@hide}
1962     *
1963     * @see #getParent()
1964     */
1965    protected ViewParent mParent;
1966
1967    /**
1968     * {@hide}
1969     */
1970    AttachInfo mAttachInfo;
1971
1972    /**
1973     * {@hide}
1974     */
1975    @ViewDebug.ExportedProperty(flagMapping = {
1976        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
1977                name = "FORCE_LAYOUT"),
1978        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
1979                name = "LAYOUT_REQUIRED"),
1980        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
1981            name = "DRAWING_CACHE_INVALID", outputIf = false),
1982        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
1983        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
1984        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
1985        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
1986    })
1987    int mPrivateFlags;
1988    int mPrivateFlags2;
1989
1990    /**
1991     * This view's request for the visibility of the status bar.
1992     * @hide
1993     */
1994    @ViewDebug.ExportedProperty(flagMapping = {
1995        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
1996                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
1997                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
1998        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
1999                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2000                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2001        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2002                                equals = SYSTEM_UI_FLAG_VISIBLE,
2003                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2004    })
2005    int mSystemUiVisibility;
2006
2007    /**
2008     * Count of how many windows this view has been attached to.
2009     */
2010    int mWindowAttachCount;
2011
2012    /**
2013     * The layout parameters associated with this view and used by the parent
2014     * {@link android.view.ViewGroup} to determine how this view should be
2015     * laid out.
2016     * {@hide}
2017     */
2018    protected ViewGroup.LayoutParams mLayoutParams;
2019
2020    /**
2021     * The view flags hold various views states.
2022     * {@hide}
2023     */
2024    @ViewDebug.ExportedProperty
2025    int mViewFlags;
2026
2027    static class TransformationInfo {
2028        /**
2029         * The transform matrix for the View. This transform is calculated internally
2030         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2031         * is used by default. Do *not* use this variable directly; instead call
2032         * getMatrix(), which will automatically recalculate the matrix if necessary
2033         * to get the correct matrix based on the latest rotation and scale properties.
2034         */
2035        private final Matrix mMatrix = new Matrix();
2036
2037        /**
2038         * The transform matrix for the View. This transform is calculated internally
2039         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2040         * is used by default. Do *not* use this variable directly; instead call
2041         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2042         * to get the correct matrix based on the latest rotation and scale properties.
2043         */
2044        private Matrix mInverseMatrix;
2045
2046        /**
2047         * An internal variable that tracks whether we need to recalculate the
2048         * transform matrix, based on whether the rotation or scaleX/Y properties
2049         * have changed since the matrix was last calculated.
2050         */
2051        boolean mMatrixDirty = false;
2052
2053        /**
2054         * An internal variable that tracks whether we need to recalculate the
2055         * transform matrix, based on whether the rotation or scaleX/Y properties
2056         * have changed since the matrix was last calculated.
2057         */
2058        private boolean mInverseMatrixDirty = true;
2059
2060        /**
2061         * A variable that tracks whether we need to recalculate the
2062         * transform matrix, based on whether the rotation or scaleX/Y properties
2063         * have changed since the matrix was last calculated. This variable
2064         * is only valid after a call to updateMatrix() or to a function that
2065         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2066         */
2067        private boolean mMatrixIsIdentity = true;
2068
2069        /**
2070         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2071         */
2072        private Camera mCamera = null;
2073
2074        /**
2075         * This matrix is used when computing the matrix for 3D rotations.
2076         */
2077        private Matrix matrix3D = null;
2078
2079        /**
2080         * These prev values are used to recalculate a centered pivot point when necessary. The
2081         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2082         * set), so thes values are only used then as well.
2083         */
2084        private int mPrevWidth = -1;
2085        private int mPrevHeight = -1;
2086
2087        /**
2088         * The degrees rotation around the vertical axis through the pivot point.
2089         */
2090        @ViewDebug.ExportedProperty
2091        float mRotationY = 0f;
2092
2093        /**
2094         * The degrees rotation around the horizontal axis through the pivot point.
2095         */
2096        @ViewDebug.ExportedProperty
2097        float mRotationX = 0f;
2098
2099        /**
2100         * The degrees rotation around the pivot point.
2101         */
2102        @ViewDebug.ExportedProperty
2103        float mRotation = 0f;
2104
2105        /**
2106         * The amount of translation of the object away from its left property (post-layout).
2107         */
2108        @ViewDebug.ExportedProperty
2109        float mTranslationX = 0f;
2110
2111        /**
2112         * The amount of translation of the object away from its top property (post-layout).
2113         */
2114        @ViewDebug.ExportedProperty
2115        float mTranslationY = 0f;
2116
2117        /**
2118         * The amount of scale in the x direction around the pivot point. A
2119         * value of 1 means no scaling is applied.
2120         */
2121        @ViewDebug.ExportedProperty
2122        float mScaleX = 1f;
2123
2124        /**
2125         * The amount of scale in the y direction around the pivot point. A
2126         * value of 1 means no scaling is applied.
2127         */
2128        @ViewDebug.ExportedProperty
2129        float mScaleY = 1f;
2130
2131        /**
2132         * The amount of scale in the x direction around the pivot point. A
2133         * value of 1 means no scaling is applied.
2134         */
2135        @ViewDebug.ExportedProperty
2136        float mPivotX = 0f;
2137
2138        /**
2139         * The amount of scale in the y direction around the pivot point. A
2140         * value of 1 means no scaling is applied.
2141         */
2142        @ViewDebug.ExportedProperty
2143        float mPivotY = 0f;
2144
2145        /**
2146         * The opacity of the View. This is a value from 0 to 1, where 0 means
2147         * completely transparent and 1 means completely opaque.
2148         */
2149        @ViewDebug.ExportedProperty
2150        float mAlpha = 1f;
2151    }
2152
2153    TransformationInfo mTransformationInfo;
2154
2155    private boolean mLastIsOpaque;
2156
2157    /**
2158     * Convenience value to check for float values that are close enough to zero to be considered
2159     * zero.
2160     */
2161    private static final float NONZERO_EPSILON = .001f;
2162
2163    /**
2164     * The distance in pixels from the left edge of this view's parent
2165     * to the left edge of this view.
2166     * {@hide}
2167     */
2168    @ViewDebug.ExportedProperty(category = "layout")
2169    protected int mLeft;
2170    /**
2171     * The distance in pixels from the left edge of this view's parent
2172     * to the right edge of this view.
2173     * {@hide}
2174     */
2175    @ViewDebug.ExportedProperty(category = "layout")
2176    protected int mRight;
2177    /**
2178     * The distance in pixels from the top edge of this view's parent
2179     * to the top edge of this view.
2180     * {@hide}
2181     */
2182    @ViewDebug.ExportedProperty(category = "layout")
2183    protected int mTop;
2184    /**
2185     * The distance in pixels from the top edge of this view's parent
2186     * to the bottom edge of this view.
2187     * {@hide}
2188     */
2189    @ViewDebug.ExportedProperty(category = "layout")
2190    protected int mBottom;
2191
2192    /**
2193     * The offset, in pixels, by which the content of this view is scrolled
2194     * horizontally.
2195     * {@hide}
2196     */
2197    @ViewDebug.ExportedProperty(category = "scrolling")
2198    protected int mScrollX;
2199    /**
2200     * The offset, in pixels, by which the content of this view is scrolled
2201     * vertically.
2202     * {@hide}
2203     */
2204    @ViewDebug.ExportedProperty(category = "scrolling")
2205    protected int mScrollY;
2206
2207    /**
2208     * The left padding in pixels, that is the distance in pixels between the
2209     * left edge of this view and the left edge of its content.
2210     * {@hide}
2211     */
2212    @ViewDebug.ExportedProperty(category = "padding")
2213    protected int mPaddingLeft;
2214    /**
2215     * The right padding in pixels, that is the distance in pixels between the
2216     * right edge of this view and the right edge of its content.
2217     * {@hide}
2218     */
2219    @ViewDebug.ExportedProperty(category = "padding")
2220    protected int mPaddingRight;
2221    /**
2222     * The top padding in pixels, that is the distance in pixels between the
2223     * top edge of this view and the top edge of its content.
2224     * {@hide}
2225     */
2226    @ViewDebug.ExportedProperty(category = "padding")
2227    protected int mPaddingTop;
2228    /**
2229     * The bottom padding in pixels, that is the distance in pixels between the
2230     * bottom edge of this view and the bottom edge of its content.
2231     * {@hide}
2232     */
2233    @ViewDebug.ExportedProperty(category = "padding")
2234    protected int mPaddingBottom;
2235
2236    /**
2237     * Briefly describes the view and is primarily used for accessibility support.
2238     */
2239    private CharSequence mContentDescription;
2240
2241    /**
2242     * Cache the paddingRight set by the user to append to the scrollbar's size.
2243     *
2244     * @hide
2245     */
2246    @ViewDebug.ExportedProperty(category = "padding")
2247    protected int mUserPaddingRight;
2248
2249    /**
2250     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2251     *
2252     * @hide
2253     */
2254    @ViewDebug.ExportedProperty(category = "padding")
2255    protected int mUserPaddingBottom;
2256
2257    /**
2258     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2259     *
2260     * @hide
2261     */
2262    @ViewDebug.ExportedProperty(category = "padding")
2263    protected int mUserPaddingLeft;
2264
2265    /**
2266     * Cache if the user padding is relative.
2267     *
2268     */
2269    @ViewDebug.ExportedProperty(category = "padding")
2270    boolean mUserPaddingRelative;
2271
2272    /**
2273     * Cache the paddingStart set by the user to append to the scrollbar's size.
2274     *
2275     */
2276    @ViewDebug.ExportedProperty(category = "padding")
2277    int mUserPaddingStart;
2278
2279    /**
2280     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2281     *
2282     */
2283    @ViewDebug.ExportedProperty(category = "padding")
2284    int mUserPaddingEnd;
2285
2286    /**
2287     * @hide
2288     */
2289    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2290    /**
2291     * @hide
2292     */
2293    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2294
2295    private Drawable mBGDrawable;
2296
2297    private int mBackgroundResource;
2298    private boolean mBackgroundSizeChanged;
2299
2300    /**
2301     * Listener used to dispatch focus change events.
2302     * This field should be made private, so it is hidden from the SDK.
2303     * {@hide}
2304     */
2305    protected OnFocusChangeListener mOnFocusChangeListener;
2306
2307    /**
2308     * Listeners for layout change events.
2309     */
2310    private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2311
2312    /**
2313     * Listeners for attach events.
2314     */
2315    private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2316
2317    /**
2318     * Listener used to dispatch click events.
2319     * This field should be made private, so it is hidden from the SDK.
2320     * {@hide}
2321     */
2322    protected OnClickListener mOnClickListener;
2323
2324    /**
2325     * Listener used to dispatch long click events.
2326     * This field should be made private, so it is hidden from the SDK.
2327     * {@hide}
2328     */
2329    protected OnLongClickListener mOnLongClickListener;
2330
2331    /**
2332     * Listener used to build the context menu.
2333     * This field should be made private, so it is hidden from the SDK.
2334     * {@hide}
2335     */
2336    protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2337
2338    private OnKeyListener mOnKeyListener;
2339
2340    private OnTouchListener mOnTouchListener;
2341
2342    private OnHoverListener mOnHoverListener;
2343
2344    private OnGenericMotionListener mOnGenericMotionListener;
2345
2346    private OnDragListener mOnDragListener;
2347
2348    private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2349
2350    /**
2351     * The application environment this view lives in.
2352     * This field should be made private, so it is hidden from the SDK.
2353     * {@hide}
2354     */
2355    protected Context mContext;
2356
2357    private final Resources mResources;
2358
2359    private ScrollabilityCache mScrollCache;
2360
2361    private int[] mDrawableState = null;
2362
2363    /**
2364     * Set to true when drawing cache is enabled and cannot be created.
2365     *
2366     * @hide
2367     */
2368    public boolean mCachingFailed;
2369
2370    private Bitmap mDrawingCache;
2371    private Bitmap mUnscaledDrawingCache;
2372    private HardwareLayer mHardwareLayer;
2373    DisplayList mDisplayList;
2374
2375    /**
2376     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2377     * the user may specify which view to go to next.
2378     */
2379    private int mNextFocusLeftId = View.NO_ID;
2380
2381    /**
2382     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2383     * the user may specify which view to go to next.
2384     */
2385    private int mNextFocusRightId = View.NO_ID;
2386
2387    /**
2388     * When this view has focus and the next focus is {@link #FOCUS_UP},
2389     * the user may specify which view to go to next.
2390     */
2391    private int mNextFocusUpId = View.NO_ID;
2392
2393    /**
2394     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2395     * the user may specify which view to go to next.
2396     */
2397    private int mNextFocusDownId = View.NO_ID;
2398
2399    /**
2400     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2401     * the user may specify which view to go to next.
2402     */
2403    int mNextFocusForwardId = View.NO_ID;
2404
2405    private CheckForLongPress mPendingCheckForLongPress;
2406    private CheckForTap mPendingCheckForTap = null;
2407    private PerformClick mPerformClick;
2408    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2409
2410    private UnsetPressedState mUnsetPressedState;
2411
2412    /**
2413     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2414     * up event while a long press is invoked as soon as the long press duration is reached, so
2415     * a long press could be performed before the tap is checked, in which case the tap's action
2416     * should not be invoked.
2417     */
2418    private boolean mHasPerformedLongPress;
2419
2420    /**
2421     * The minimum height of the view. We'll try our best to have the height
2422     * of this view to at least this amount.
2423     */
2424    @ViewDebug.ExportedProperty(category = "measurement")
2425    private int mMinHeight;
2426
2427    /**
2428     * The minimum width of the view. We'll try our best to have the width
2429     * of this view to at least this amount.
2430     */
2431    @ViewDebug.ExportedProperty(category = "measurement")
2432    private int mMinWidth;
2433
2434    /**
2435     * The delegate to handle touch events that are physically in this view
2436     * but should be handled by another view.
2437     */
2438    private TouchDelegate mTouchDelegate = null;
2439
2440    /**
2441     * Solid color to use as a background when creating the drawing cache. Enables
2442     * the cache to use 16 bit bitmaps instead of 32 bit.
2443     */
2444    private int mDrawingCacheBackgroundColor = 0;
2445
2446    /**
2447     * Special tree observer used when mAttachInfo is null.
2448     */
2449    private ViewTreeObserver mFloatingTreeObserver;
2450
2451    /**
2452     * Cache the touch slop from the context that created the view.
2453     */
2454    private int mTouchSlop;
2455
2456    /**
2457     * Object that handles automatic animation of view properties.
2458     */
2459    private ViewPropertyAnimator mAnimator = null;
2460
2461    /**
2462     * Flag indicating that a drag can cross window boundaries.  When
2463     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2464     * with this flag set, all visible applications will be able to participate
2465     * in the drag operation and receive the dragged content.
2466     *
2467     * @hide
2468     */
2469    public static final int DRAG_FLAG_GLOBAL = 1;
2470
2471    /**
2472     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2473     */
2474    private float mVerticalScrollFactor;
2475
2476    /**
2477     * Position of the vertical scroll bar.
2478     */
2479    private int mVerticalScrollbarPosition;
2480
2481    /**
2482     * Position the scroll bar at the default position as determined by the system.
2483     */
2484    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2485
2486    /**
2487     * Position the scroll bar along the left edge.
2488     */
2489    public static final int SCROLLBAR_POSITION_LEFT = 1;
2490
2491    /**
2492     * Position the scroll bar along the right edge.
2493     */
2494    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2495
2496    /**
2497     * Indicates that the view does not have a layer.
2498     *
2499     * @see #getLayerType()
2500     * @see #setLayerType(int, android.graphics.Paint)
2501     * @see #LAYER_TYPE_SOFTWARE
2502     * @see #LAYER_TYPE_HARDWARE
2503     */
2504    public static final int LAYER_TYPE_NONE = 0;
2505
2506    /**
2507     * <p>Indicates that the view has a software layer. A software layer is backed
2508     * by a bitmap and causes the view to be rendered using Android's software
2509     * rendering pipeline, even if hardware acceleration is enabled.</p>
2510     *
2511     * <p>Software layers have various usages:</p>
2512     * <p>When the application is not using hardware acceleration, a software layer
2513     * is useful to apply a specific color filter and/or blending mode and/or
2514     * translucency to a view and all its children.</p>
2515     * <p>When the application is using hardware acceleration, a software layer
2516     * is useful to render drawing primitives not supported by the hardware
2517     * accelerated pipeline. It can also be used to cache a complex view tree
2518     * into a texture and reduce the complexity of drawing operations. For instance,
2519     * when animating a complex view tree with a translation, a software layer can
2520     * be used to render the view tree only once.</p>
2521     * <p>Software layers should be avoided when the affected view tree updates
2522     * often. Every update will require to re-render the software layer, which can
2523     * potentially be slow (particularly when hardware acceleration is turned on
2524     * since the layer will have to be uploaded into a hardware texture after every
2525     * update.)</p>
2526     *
2527     * @see #getLayerType()
2528     * @see #setLayerType(int, android.graphics.Paint)
2529     * @see #LAYER_TYPE_NONE
2530     * @see #LAYER_TYPE_HARDWARE
2531     */
2532    public static final int LAYER_TYPE_SOFTWARE = 1;
2533
2534    /**
2535     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2536     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2537     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2538     * rendering pipeline, but only if hardware acceleration is turned on for the
2539     * view hierarchy. When hardware acceleration is turned off, hardware layers
2540     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2541     *
2542     * <p>A hardware layer is useful to apply a specific color filter and/or
2543     * blending mode and/or translucency to a view and all its children.</p>
2544     * <p>A hardware layer can be used to cache a complex view tree into a
2545     * texture and reduce the complexity of drawing operations. For instance,
2546     * when animating a complex view tree with a translation, a hardware layer can
2547     * be used to render the view tree only once.</p>
2548     * <p>A hardware layer can also be used to increase the rendering quality when
2549     * rotation transformations are applied on a view. It can also be used to
2550     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2551     *
2552     * @see #getLayerType()
2553     * @see #setLayerType(int, android.graphics.Paint)
2554     * @see #LAYER_TYPE_NONE
2555     * @see #LAYER_TYPE_SOFTWARE
2556     */
2557    public static final int LAYER_TYPE_HARDWARE = 2;
2558
2559    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2560            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2561            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2562            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2563    })
2564    int mLayerType = LAYER_TYPE_NONE;
2565    Paint mLayerPaint;
2566    Rect mLocalDirtyRect;
2567
2568    /**
2569     * Set to true when the view is sending hover accessibility events because it
2570     * is the innermost hovered view.
2571     */
2572    private boolean mSendingHoverAccessibilityEvents;
2573
2574    /**
2575     * Delegate for injecting accessiblity functionality.
2576     */
2577    AccessibilityDelegate mAccessibilityDelegate;
2578
2579    /**
2580     * Text direction is inherited thru {@link ViewGroup}
2581     * @hide
2582     */
2583    public static final int TEXT_DIRECTION_INHERIT = 0;
2584
2585    /**
2586     * Text direction is using "first strong algorithm". The first strong directional character
2587     * determines the paragraph direction. If there is no strong directional character, the
2588     * paragraph direction is the view's resolved ayout direction.
2589     *
2590     * @hide
2591     */
2592    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2593
2594    /**
2595     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2596     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2597     * If there are neither, the paragraph direction is the view's resolved layout direction.
2598     *
2599     * @hide
2600     */
2601    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2602
2603    /**
2604     * Text direction is forced to LTR.
2605     *
2606     * @hide
2607     */
2608    public static final int TEXT_DIRECTION_LTR = 3;
2609
2610    /**
2611     * Text direction is forced to RTL.
2612     *
2613     * @hide
2614     */
2615    public static final int TEXT_DIRECTION_RTL = 4;
2616
2617    /**
2618     * Default text direction is inherited
2619     *
2620     * @hide
2621     */
2622    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2623
2624    /**
2625     * The text direction that has been defined by {@link #setTextDirection(int)}.
2626     *
2627     * {@hide}
2628     */
2629    @ViewDebug.ExportedProperty(category = "text", mapping = {
2630            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2631            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2632            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2633            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2634            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2635    })
2636    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2637
2638    /**
2639     * The resolved text direction.  This needs resolution if the value is
2640     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if that is
2641     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2642     * chain of the view.
2643     *
2644     * {@hide}
2645     */
2646    @ViewDebug.ExportedProperty(category = "text", mapping = {
2647            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2648            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2649            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2650            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2651            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL")
2652    })
2653    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2654
2655    /**
2656     * Consistency verifier for debugging purposes.
2657     * @hide
2658     */
2659    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2660            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2661                    new InputEventConsistencyVerifier(this, 0) : null;
2662
2663    /**
2664     * Simple constructor to use when creating a view from code.
2665     *
2666     * @param context The Context the view is running in, through which it can
2667     *        access the current theme, resources, etc.
2668     */
2669    public View(Context context) {
2670        mContext = context;
2671        mResources = context != null ? context.getResources() : null;
2672        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2673        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2674        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2675        mUserPaddingStart = -1;
2676        mUserPaddingEnd = -1;
2677        mUserPaddingRelative = false;
2678    }
2679
2680    /**
2681     * Constructor that is called when inflating a view from XML. This is called
2682     * when a view is being constructed from an XML file, supplying attributes
2683     * that were specified in the XML file. This version uses a default style of
2684     * 0, so the only attribute values applied are those in the Context's Theme
2685     * and the given AttributeSet.
2686     *
2687     * <p>
2688     * The method onFinishInflate() will be called after all children have been
2689     * added.
2690     *
2691     * @param context The Context the view is running in, through which it can
2692     *        access the current theme, resources, etc.
2693     * @param attrs The attributes of the XML tag that is inflating the view.
2694     * @see #View(Context, AttributeSet, int)
2695     */
2696    public View(Context context, AttributeSet attrs) {
2697        this(context, attrs, 0);
2698    }
2699
2700    /**
2701     * Perform inflation from XML and apply a class-specific base style. This
2702     * constructor of View allows subclasses to use their own base style when
2703     * they are inflating. For example, a Button class's constructor would call
2704     * this version of the super class constructor and supply
2705     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2706     * the theme's button style to modify all of the base view attributes (in
2707     * particular its background) as well as the Button class's attributes.
2708     *
2709     * @param context The Context the view is running in, through which it can
2710     *        access the current theme, resources, etc.
2711     * @param attrs The attributes of the XML tag that is inflating the view.
2712     * @param defStyle The default style to apply to this view. If 0, no style
2713     *        will be applied (beyond what is included in the theme). This may
2714     *        either be an attribute resource, whose value will be retrieved
2715     *        from the current theme, or an explicit style resource.
2716     * @see #View(Context, AttributeSet)
2717     */
2718    public View(Context context, AttributeSet attrs, int defStyle) {
2719        this(context);
2720
2721        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2722                defStyle, 0);
2723
2724        Drawable background = null;
2725
2726        int leftPadding = -1;
2727        int topPadding = -1;
2728        int rightPadding = -1;
2729        int bottomPadding = -1;
2730        int startPadding = -1;
2731        int endPadding = -1;
2732
2733        int padding = -1;
2734
2735        int viewFlagValues = 0;
2736        int viewFlagMasks = 0;
2737
2738        boolean setScrollContainer = false;
2739
2740        int x = 0;
2741        int y = 0;
2742
2743        float tx = 0;
2744        float ty = 0;
2745        float rotation = 0;
2746        float rotationX = 0;
2747        float rotationY = 0;
2748        float sx = 1f;
2749        float sy = 1f;
2750        boolean transformSet = false;
2751
2752        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2753
2754        int overScrollMode = mOverScrollMode;
2755        final int N = a.getIndexCount();
2756        for (int i = 0; i < N; i++) {
2757            int attr = a.getIndex(i);
2758            switch (attr) {
2759                case com.android.internal.R.styleable.View_background:
2760                    background = a.getDrawable(attr);
2761                    break;
2762                case com.android.internal.R.styleable.View_padding:
2763                    padding = a.getDimensionPixelSize(attr, -1);
2764                    break;
2765                 case com.android.internal.R.styleable.View_paddingLeft:
2766                    leftPadding = a.getDimensionPixelSize(attr, -1);
2767                    break;
2768                case com.android.internal.R.styleable.View_paddingTop:
2769                    topPadding = a.getDimensionPixelSize(attr, -1);
2770                    break;
2771                case com.android.internal.R.styleable.View_paddingRight:
2772                    rightPadding = a.getDimensionPixelSize(attr, -1);
2773                    break;
2774                case com.android.internal.R.styleable.View_paddingBottom:
2775                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2776                    break;
2777                case com.android.internal.R.styleable.View_paddingStart:
2778                    startPadding = a.getDimensionPixelSize(attr, -1);
2779                    break;
2780                case com.android.internal.R.styleable.View_paddingEnd:
2781                    endPadding = a.getDimensionPixelSize(attr, -1);
2782                    break;
2783                case com.android.internal.R.styleable.View_scrollX:
2784                    x = a.getDimensionPixelOffset(attr, 0);
2785                    break;
2786                case com.android.internal.R.styleable.View_scrollY:
2787                    y = a.getDimensionPixelOffset(attr, 0);
2788                    break;
2789                case com.android.internal.R.styleable.View_alpha:
2790                    setAlpha(a.getFloat(attr, 1f));
2791                    break;
2792                case com.android.internal.R.styleable.View_transformPivotX:
2793                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2794                    break;
2795                case com.android.internal.R.styleable.View_transformPivotY:
2796                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2797                    break;
2798                case com.android.internal.R.styleable.View_translationX:
2799                    tx = a.getDimensionPixelOffset(attr, 0);
2800                    transformSet = true;
2801                    break;
2802                case com.android.internal.R.styleable.View_translationY:
2803                    ty = a.getDimensionPixelOffset(attr, 0);
2804                    transformSet = true;
2805                    break;
2806                case com.android.internal.R.styleable.View_rotation:
2807                    rotation = a.getFloat(attr, 0);
2808                    transformSet = true;
2809                    break;
2810                case com.android.internal.R.styleable.View_rotationX:
2811                    rotationX = a.getFloat(attr, 0);
2812                    transformSet = true;
2813                    break;
2814                case com.android.internal.R.styleable.View_rotationY:
2815                    rotationY = a.getFloat(attr, 0);
2816                    transformSet = true;
2817                    break;
2818                case com.android.internal.R.styleable.View_scaleX:
2819                    sx = a.getFloat(attr, 1f);
2820                    transformSet = true;
2821                    break;
2822                case com.android.internal.R.styleable.View_scaleY:
2823                    sy = a.getFloat(attr, 1f);
2824                    transformSet = true;
2825                    break;
2826                case com.android.internal.R.styleable.View_id:
2827                    mID = a.getResourceId(attr, NO_ID);
2828                    break;
2829                case com.android.internal.R.styleable.View_tag:
2830                    mTag = a.getText(attr);
2831                    break;
2832                case com.android.internal.R.styleable.View_fitsSystemWindows:
2833                    if (a.getBoolean(attr, false)) {
2834                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2835                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2836                    }
2837                    break;
2838                case com.android.internal.R.styleable.View_focusable:
2839                    if (a.getBoolean(attr, false)) {
2840                        viewFlagValues |= FOCUSABLE;
2841                        viewFlagMasks |= FOCUSABLE_MASK;
2842                    }
2843                    break;
2844                case com.android.internal.R.styleable.View_focusableInTouchMode:
2845                    if (a.getBoolean(attr, false)) {
2846                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2847                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2848                    }
2849                    break;
2850                case com.android.internal.R.styleable.View_clickable:
2851                    if (a.getBoolean(attr, false)) {
2852                        viewFlagValues |= CLICKABLE;
2853                        viewFlagMasks |= CLICKABLE;
2854                    }
2855                    break;
2856                case com.android.internal.R.styleable.View_longClickable:
2857                    if (a.getBoolean(attr, false)) {
2858                        viewFlagValues |= LONG_CLICKABLE;
2859                        viewFlagMasks |= LONG_CLICKABLE;
2860                    }
2861                    break;
2862                case com.android.internal.R.styleable.View_saveEnabled:
2863                    if (!a.getBoolean(attr, true)) {
2864                        viewFlagValues |= SAVE_DISABLED;
2865                        viewFlagMasks |= SAVE_DISABLED_MASK;
2866                    }
2867                    break;
2868                case com.android.internal.R.styleable.View_duplicateParentState:
2869                    if (a.getBoolean(attr, false)) {
2870                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2871                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2872                    }
2873                    break;
2874                case com.android.internal.R.styleable.View_visibility:
2875                    final int visibility = a.getInt(attr, 0);
2876                    if (visibility != 0) {
2877                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2878                        viewFlagMasks |= VISIBILITY_MASK;
2879                    }
2880                    break;
2881                case com.android.internal.R.styleable.View_layoutDirection:
2882                    // Clear any HORIZONTAL_DIRECTION flag already set
2883                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2884                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2885                    final int layoutDirection = a.getInt(attr, -1);
2886                    if (layoutDirection != -1) {
2887                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2888                    } else {
2889                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2890                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2891                    }
2892                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2893                    break;
2894                case com.android.internal.R.styleable.View_drawingCacheQuality:
2895                    final int cacheQuality = a.getInt(attr, 0);
2896                    if (cacheQuality != 0) {
2897                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2898                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2899                    }
2900                    break;
2901                case com.android.internal.R.styleable.View_contentDescription:
2902                    mContentDescription = a.getString(attr);
2903                    break;
2904                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2905                    if (!a.getBoolean(attr, true)) {
2906                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2907                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2908                    }
2909                    break;
2910                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2911                    if (!a.getBoolean(attr, true)) {
2912                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2913                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2914                    }
2915                    break;
2916                case R.styleable.View_scrollbars:
2917                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2918                    if (scrollbars != SCROLLBARS_NONE) {
2919                        viewFlagValues |= scrollbars;
2920                        viewFlagMasks |= SCROLLBARS_MASK;
2921                        initializeScrollbars(a);
2922                    }
2923                    break;
2924                //noinspection deprecation
2925                case R.styleable.View_fadingEdge:
2926                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2927                        // Ignore the attribute starting with ICS
2928                        break;
2929                    }
2930                    // With builds < ICS, fall through and apply fading edges
2931                case R.styleable.View_requiresFadingEdge:
2932                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2933                    if (fadingEdge != FADING_EDGE_NONE) {
2934                        viewFlagValues |= fadingEdge;
2935                        viewFlagMasks |= FADING_EDGE_MASK;
2936                        initializeFadingEdge(a);
2937                    }
2938                    break;
2939                case R.styleable.View_scrollbarStyle:
2940                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2941                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2942                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2943                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2944                    }
2945                    break;
2946                case R.styleable.View_isScrollContainer:
2947                    setScrollContainer = true;
2948                    if (a.getBoolean(attr, false)) {
2949                        setScrollContainer(true);
2950                    }
2951                    break;
2952                case com.android.internal.R.styleable.View_keepScreenOn:
2953                    if (a.getBoolean(attr, false)) {
2954                        viewFlagValues |= KEEP_SCREEN_ON;
2955                        viewFlagMasks |= KEEP_SCREEN_ON;
2956                    }
2957                    break;
2958                case R.styleable.View_filterTouchesWhenObscured:
2959                    if (a.getBoolean(attr, false)) {
2960                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
2961                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
2962                    }
2963                    break;
2964                case R.styleable.View_nextFocusLeft:
2965                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
2966                    break;
2967                case R.styleable.View_nextFocusRight:
2968                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
2969                    break;
2970                case R.styleable.View_nextFocusUp:
2971                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
2972                    break;
2973                case R.styleable.View_nextFocusDown:
2974                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
2975                    break;
2976                case R.styleable.View_nextFocusForward:
2977                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
2978                    break;
2979                case R.styleable.View_minWidth:
2980                    mMinWidth = a.getDimensionPixelSize(attr, 0);
2981                    break;
2982                case R.styleable.View_minHeight:
2983                    mMinHeight = a.getDimensionPixelSize(attr, 0);
2984                    break;
2985                case R.styleable.View_onClick:
2986                    if (context.isRestricted()) {
2987                        throw new IllegalStateException("The android:onClick attribute cannot "
2988                                + "be used within a restricted context");
2989                    }
2990
2991                    final String handlerName = a.getString(attr);
2992                    if (handlerName != null) {
2993                        setOnClickListener(new OnClickListener() {
2994                            private Method mHandler;
2995
2996                            public void onClick(View v) {
2997                                if (mHandler == null) {
2998                                    try {
2999                                        mHandler = getContext().getClass().getMethod(handlerName,
3000                                                View.class);
3001                                    } catch (NoSuchMethodException e) {
3002                                        int id = getId();
3003                                        String idText = id == NO_ID ? "" : " with id '"
3004                                                + getContext().getResources().getResourceEntryName(
3005                                                    id) + "'";
3006                                        throw new IllegalStateException("Could not find a method " +
3007                                                handlerName + "(View) in the activity "
3008                                                + getContext().getClass() + " for onClick handler"
3009                                                + " on view " + View.this.getClass() + idText, e);
3010                                    }
3011                                }
3012
3013                                try {
3014                                    mHandler.invoke(getContext(), View.this);
3015                                } catch (IllegalAccessException e) {
3016                                    throw new IllegalStateException("Could not execute non "
3017                                            + "public method of the activity", e);
3018                                } catch (InvocationTargetException e) {
3019                                    throw new IllegalStateException("Could not execute "
3020                                            + "method of the activity", e);
3021                                }
3022                            }
3023                        });
3024                    }
3025                    break;
3026                case R.styleable.View_overScrollMode:
3027                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3028                    break;
3029                case R.styleable.View_verticalScrollbarPosition:
3030                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3031                    break;
3032                case R.styleable.View_layerType:
3033                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3034                    break;
3035                case R.styleable.View_textDirection:
3036                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3037                    break;
3038            }
3039        }
3040
3041        a.recycle();
3042
3043        setOverScrollMode(overScrollMode);
3044
3045        if (background != null) {
3046            setBackgroundDrawable(background);
3047        }
3048
3049        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3050
3051        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3052        // layout direction). Those cached values will be used later during padding resolution.
3053        mUserPaddingStart = startPadding;
3054        mUserPaddingEnd = endPadding;
3055
3056        if (padding >= 0) {
3057            leftPadding = padding;
3058            topPadding = padding;
3059            rightPadding = padding;
3060            bottomPadding = padding;
3061        }
3062
3063        // If the user specified the padding (either with android:padding or
3064        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3065        // use the default padding or the padding from the background drawable
3066        // (stored at this point in mPadding*)
3067        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3068                topPadding >= 0 ? topPadding : mPaddingTop,
3069                rightPadding >= 0 ? rightPadding : mPaddingRight,
3070                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3071
3072        if (viewFlagMasks != 0) {
3073            setFlags(viewFlagValues, viewFlagMasks);
3074        }
3075
3076        // Needs to be called after mViewFlags is set
3077        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3078            recomputePadding();
3079        }
3080
3081        if (x != 0 || y != 0) {
3082            scrollTo(x, y);
3083        }
3084
3085        if (transformSet) {
3086            setTranslationX(tx);
3087            setTranslationY(ty);
3088            setRotation(rotation);
3089            setRotationX(rotationX);
3090            setRotationY(rotationY);
3091            setScaleX(sx);
3092            setScaleY(sy);
3093        }
3094
3095        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3096            setScrollContainer(true);
3097        }
3098
3099        computeOpaqueFlags();
3100    }
3101
3102    /**
3103     * Non-public constructor for use in testing
3104     */
3105    View() {
3106        mResources = null;
3107    }
3108
3109    /**
3110     * <p>
3111     * Initializes the fading edges from a given set of styled attributes. This
3112     * method should be called by subclasses that need fading edges and when an
3113     * instance of these subclasses is created programmatically rather than
3114     * being inflated from XML. This method is automatically called when the XML
3115     * is inflated.
3116     * </p>
3117     *
3118     * @param a the styled attributes set to initialize the fading edges from
3119     */
3120    protected void initializeFadingEdge(TypedArray a) {
3121        initScrollCache();
3122
3123        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3124                R.styleable.View_fadingEdgeLength,
3125                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3126    }
3127
3128    /**
3129     * Returns the size of the vertical faded edges used to indicate that more
3130     * content in this view is visible.
3131     *
3132     * @return The size in pixels of the vertical faded edge or 0 if vertical
3133     *         faded edges are not enabled for this view.
3134     * @attr ref android.R.styleable#View_fadingEdgeLength
3135     */
3136    public int getVerticalFadingEdgeLength() {
3137        if (isVerticalFadingEdgeEnabled()) {
3138            ScrollabilityCache cache = mScrollCache;
3139            if (cache != null) {
3140                return cache.fadingEdgeLength;
3141            }
3142        }
3143        return 0;
3144    }
3145
3146    /**
3147     * Set the size of the faded edge used to indicate that more content in this
3148     * view is available.  Will not change whether the fading edge is enabled; use
3149     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3150     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3151     * for the vertical or horizontal fading edges.
3152     *
3153     * @param length The size in pixels of the faded edge used to indicate that more
3154     *        content in this view is visible.
3155     */
3156    public void setFadingEdgeLength(int length) {
3157        initScrollCache();
3158        mScrollCache.fadingEdgeLength = length;
3159    }
3160
3161    /**
3162     * Returns the size of the horizontal faded edges used to indicate that more
3163     * content in this view is visible.
3164     *
3165     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3166     *         faded edges are not enabled for this view.
3167     * @attr ref android.R.styleable#View_fadingEdgeLength
3168     */
3169    public int getHorizontalFadingEdgeLength() {
3170        if (isHorizontalFadingEdgeEnabled()) {
3171            ScrollabilityCache cache = mScrollCache;
3172            if (cache != null) {
3173                return cache.fadingEdgeLength;
3174            }
3175        }
3176        return 0;
3177    }
3178
3179    /**
3180     * Returns the width of the vertical scrollbar.
3181     *
3182     * @return The width in pixels of the vertical scrollbar or 0 if there
3183     *         is no vertical scrollbar.
3184     */
3185    public int getVerticalScrollbarWidth() {
3186        ScrollabilityCache cache = mScrollCache;
3187        if (cache != null) {
3188            ScrollBarDrawable scrollBar = cache.scrollBar;
3189            if (scrollBar != null) {
3190                int size = scrollBar.getSize(true);
3191                if (size <= 0) {
3192                    size = cache.scrollBarSize;
3193                }
3194                return size;
3195            }
3196            return 0;
3197        }
3198        return 0;
3199    }
3200
3201    /**
3202     * Returns the height of the horizontal scrollbar.
3203     *
3204     * @return The height in pixels of the horizontal scrollbar or 0 if
3205     *         there is no horizontal scrollbar.
3206     */
3207    protected int getHorizontalScrollbarHeight() {
3208        ScrollabilityCache cache = mScrollCache;
3209        if (cache != null) {
3210            ScrollBarDrawable scrollBar = cache.scrollBar;
3211            if (scrollBar != null) {
3212                int size = scrollBar.getSize(false);
3213                if (size <= 0) {
3214                    size = cache.scrollBarSize;
3215                }
3216                return size;
3217            }
3218            return 0;
3219        }
3220        return 0;
3221    }
3222
3223    /**
3224     * <p>
3225     * Initializes the scrollbars from a given set of styled attributes. This
3226     * method should be called by subclasses that need scrollbars and when an
3227     * instance of these subclasses is created programmatically rather than
3228     * being inflated from XML. This method is automatically called when the XML
3229     * is inflated.
3230     * </p>
3231     *
3232     * @param a the styled attributes set to initialize the scrollbars from
3233     */
3234    protected void initializeScrollbars(TypedArray a) {
3235        initScrollCache();
3236
3237        final ScrollabilityCache scrollabilityCache = mScrollCache;
3238
3239        if (scrollabilityCache.scrollBar == null) {
3240            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3241        }
3242
3243        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3244
3245        if (!fadeScrollbars) {
3246            scrollabilityCache.state = ScrollabilityCache.ON;
3247        }
3248        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3249
3250
3251        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3252                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3253                        .getScrollBarFadeDuration());
3254        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3255                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3256                ViewConfiguration.getScrollDefaultDelay());
3257
3258
3259        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3260                com.android.internal.R.styleable.View_scrollbarSize,
3261                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3262
3263        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3264        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3265
3266        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3267        if (thumb != null) {
3268            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3269        }
3270
3271        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3272                false);
3273        if (alwaysDraw) {
3274            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3275        }
3276
3277        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3278        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3279
3280        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3281        if (thumb != null) {
3282            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3283        }
3284
3285        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3286                false);
3287        if (alwaysDraw) {
3288            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3289        }
3290
3291        // Re-apply user/background padding so that scrollbar(s) get added
3292        resolvePadding();
3293    }
3294
3295    /**
3296     * <p>
3297     * Initalizes the scrollability cache if necessary.
3298     * </p>
3299     */
3300    private void initScrollCache() {
3301        if (mScrollCache == null) {
3302            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3303        }
3304    }
3305
3306    /**
3307     * Set the position of the vertical scroll bar. Should be one of
3308     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3309     * {@link #SCROLLBAR_POSITION_RIGHT}.
3310     *
3311     * @param position Where the vertical scroll bar should be positioned.
3312     */
3313    public void setVerticalScrollbarPosition(int position) {
3314        if (mVerticalScrollbarPosition != position) {
3315            mVerticalScrollbarPosition = position;
3316            computeOpaqueFlags();
3317            resolvePadding();
3318        }
3319    }
3320
3321    /**
3322     * @return The position where the vertical scroll bar will show, if applicable.
3323     * @see #setVerticalScrollbarPosition(int)
3324     */
3325    public int getVerticalScrollbarPosition() {
3326        return mVerticalScrollbarPosition;
3327    }
3328
3329    /**
3330     * Register a callback to be invoked when focus of this view changed.
3331     *
3332     * @param l The callback that will run.
3333     */
3334    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3335        mOnFocusChangeListener = l;
3336    }
3337
3338    /**
3339     * Add a listener that will be called when the bounds of the view change due to
3340     * layout processing.
3341     *
3342     * @param listener The listener that will be called when layout bounds change.
3343     */
3344    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3345        if (mOnLayoutChangeListeners == null) {
3346            mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3347        }
3348        mOnLayoutChangeListeners.add(listener);
3349    }
3350
3351    /**
3352     * Remove a listener for layout changes.
3353     *
3354     * @param listener The listener for layout bounds change.
3355     */
3356    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3357        if (mOnLayoutChangeListeners == null) {
3358            return;
3359        }
3360        mOnLayoutChangeListeners.remove(listener);
3361    }
3362
3363    /**
3364     * Add a listener for attach state changes.
3365     *
3366     * This listener will be called whenever this view is attached or detached
3367     * from a window. Remove the listener using
3368     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3369     *
3370     * @param listener Listener to attach
3371     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3372     */
3373    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3374        if (mOnAttachStateChangeListeners == null) {
3375            mOnAttachStateChangeListeners = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3376        }
3377        mOnAttachStateChangeListeners.add(listener);
3378    }
3379
3380    /**
3381     * Remove a listener for attach state changes. The listener will receive no further
3382     * notification of window attach/detach events.
3383     *
3384     * @param listener Listener to remove
3385     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3386     */
3387    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3388        if (mOnAttachStateChangeListeners == null) {
3389            return;
3390        }
3391        mOnAttachStateChangeListeners.remove(listener);
3392    }
3393
3394    /**
3395     * Returns the focus-change callback registered for this view.
3396     *
3397     * @return The callback, or null if one is not registered.
3398     */
3399    public OnFocusChangeListener getOnFocusChangeListener() {
3400        return mOnFocusChangeListener;
3401    }
3402
3403    /**
3404     * Register a callback to be invoked when this view is clicked. If this view is not
3405     * clickable, it becomes clickable.
3406     *
3407     * @param l The callback that will run
3408     *
3409     * @see #setClickable(boolean)
3410     */
3411    public void setOnClickListener(OnClickListener l) {
3412        if (!isClickable()) {
3413            setClickable(true);
3414        }
3415        mOnClickListener = l;
3416    }
3417
3418    /**
3419     * Register a callback to be invoked when this view is clicked and held. If this view is not
3420     * long clickable, it becomes long clickable.
3421     *
3422     * @param l The callback that will run
3423     *
3424     * @see #setLongClickable(boolean)
3425     */
3426    public void setOnLongClickListener(OnLongClickListener l) {
3427        if (!isLongClickable()) {
3428            setLongClickable(true);
3429        }
3430        mOnLongClickListener = l;
3431    }
3432
3433    /**
3434     * Register a callback to be invoked when the context menu for this view is
3435     * being built. If this view is not long clickable, it becomes long clickable.
3436     *
3437     * @param l The callback that will run
3438     *
3439     */
3440    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3441        if (!isLongClickable()) {
3442            setLongClickable(true);
3443        }
3444        mOnCreateContextMenuListener = l;
3445    }
3446
3447    /**
3448     * Call this view's OnClickListener, if it is defined.
3449     *
3450     * @return True there was an assigned OnClickListener that was called, false
3451     *         otherwise is returned.
3452     */
3453    public boolean performClick() {
3454        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3455
3456        if (mOnClickListener != null) {
3457            playSoundEffect(SoundEffectConstants.CLICK);
3458            mOnClickListener.onClick(this);
3459            return true;
3460        }
3461
3462        return false;
3463    }
3464
3465    /**
3466     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3467     * OnLongClickListener did not consume the event.
3468     *
3469     * @return True if one of the above receivers consumed the event, false otherwise.
3470     */
3471    public boolean performLongClick() {
3472        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3473
3474        boolean handled = false;
3475        if (mOnLongClickListener != null) {
3476            handled = mOnLongClickListener.onLongClick(View.this);
3477        }
3478        if (!handled) {
3479            handled = showContextMenu();
3480        }
3481        if (handled) {
3482            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3483        }
3484        return handled;
3485    }
3486
3487    /**
3488     * Performs button-related actions during a touch down event.
3489     *
3490     * @param event The event.
3491     * @return True if the down was consumed.
3492     *
3493     * @hide
3494     */
3495    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3496        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3497            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3498                return true;
3499            }
3500        }
3501        return false;
3502    }
3503
3504    /**
3505     * Bring up the context menu for this view.
3506     *
3507     * @return Whether a context menu was displayed.
3508     */
3509    public boolean showContextMenu() {
3510        return getParent().showContextMenuForChild(this);
3511    }
3512
3513    /**
3514     * Bring up the context menu for this view, referring to the item under the specified point.
3515     *
3516     * @param x The referenced x coordinate.
3517     * @param y The referenced y coordinate.
3518     * @param metaState The keyboard modifiers that were pressed.
3519     * @return Whether a context menu was displayed.
3520     *
3521     * @hide
3522     */
3523    public boolean showContextMenu(float x, float y, int metaState) {
3524        return showContextMenu();
3525    }
3526
3527    /**
3528     * Start an action mode.
3529     *
3530     * @param callback Callback that will control the lifecycle of the action mode
3531     * @return The new action mode if it is started, null otherwise
3532     *
3533     * @see ActionMode
3534     */
3535    public ActionMode startActionMode(ActionMode.Callback callback) {
3536        return getParent().startActionModeForChild(this, callback);
3537    }
3538
3539    /**
3540     * Register a callback to be invoked when a key is pressed in this view.
3541     * @param l the key listener to attach to this view
3542     */
3543    public void setOnKeyListener(OnKeyListener l) {
3544        mOnKeyListener = l;
3545    }
3546
3547    /**
3548     * Register a callback to be invoked when a touch event is sent to this view.
3549     * @param l the touch listener to attach to this view
3550     */
3551    public void setOnTouchListener(OnTouchListener l) {
3552        mOnTouchListener = l;
3553    }
3554
3555    /**
3556     * Register a callback to be invoked when a generic motion event is sent to this view.
3557     * @param l the generic motion listener to attach to this view
3558     */
3559    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3560        mOnGenericMotionListener = l;
3561    }
3562
3563    /**
3564     * Register a callback to be invoked when a hover event is sent to this view.
3565     * @param l the hover listener to attach to this view
3566     */
3567    public void setOnHoverListener(OnHoverListener l) {
3568        mOnHoverListener = l;
3569    }
3570
3571    /**
3572     * Register a drag event listener callback object for this View. The parameter is
3573     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3574     * View, the system calls the
3575     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3576     * @param l An implementation of {@link android.view.View.OnDragListener}.
3577     */
3578    public void setOnDragListener(OnDragListener l) {
3579        mOnDragListener = l;
3580    }
3581
3582    /**
3583     * Give this view focus. This will cause
3584     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3585     *
3586     * Note: this does not check whether this {@link View} should get focus, it just
3587     * gives it focus no matter what.  It should only be called internally by framework
3588     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3589     *
3590     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3591     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3592     *        focus moved when requestFocus() is called. It may not always
3593     *        apply, in which case use the default View.FOCUS_DOWN.
3594     * @param previouslyFocusedRect The rectangle of the view that had focus
3595     *        prior in this View's coordinate system.
3596     */
3597    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3598        if (DBG) {
3599            System.out.println(this + " requestFocus()");
3600        }
3601
3602        if ((mPrivateFlags & FOCUSED) == 0) {
3603            mPrivateFlags |= FOCUSED;
3604
3605            if (mParent != null) {
3606                mParent.requestChildFocus(this, this);
3607            }
3608
3609            onFocusChanged(true, direction, previouslyFocusedRect);
3610            refreshDrawableState();
3611        }
3612    }
3613
3614    /**
3615     * Request that a rectangle of this view be visible on the screen,
3616     * scrolling if necessary just enough.
3617     *
3618     * <p>A View should call this if it maintains some notion of which part
3619     * of its content is interesting.  For example, a text editing view
3620     * should call this when its cursor moves.
3621     *
3622     * @param rectangle The rectangle.
3623     * @return Whether any parent scrolled.
3624     */
3625    public boolean requestRectangleOnScreen(Rect rectangle) {
3626        return requestRectangleOnScreen(rectangle, false);
3627    }
3628
3629    /**
3630     * Request that a rectangle of this view be visible on the screen,
3631     * scrolling if necessary just enough.
3632     *
3633     * <p>A View should call this if it maintains some notion of which part
3634     * of its content is interesting.  For example, a text editing view
3635     * should call this when its cursor moves.
3636     *
3637     * <p>When <code>immediate</code> is set to true, scrolling will not be
3638     * animated.
3639     *
3640     * @param rectangle The rectangle.
3641     * @param immediate True to forbid animated scrolling, false otherwise
3642     * @return Whether any parent scrolled.
3643     */
3644    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3645        View child = this;
3646        ViewParent parent = mParent;
3647        boolean scrolled = false;
3648        while (parent != null) {
3649            scrolled |= parent.requestChildRectangleOnScreen(child,
3650                    rectangle, immediate);
3651
3652            // offset rect so next call has the rectangle in the
3653            // coordinate system of its direct child.
3654            rectangle.offset(child.getLeft(), child.getTop());
3655            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3656
3657            if (!(parent instanceof View)) {
3658                break;
3659            }
3660
3661            child = (View) parent;
3662            parent = child.getParent();
3663        }
3664        return scrolled;
3665    }
3666
3667    /**
3668     * Called when this view wants to give up focus. This will cause
3669     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3670     */
3671    public void clearFocus() {
3672        if (DBG) {
3673            System.out.println(this + " clearFocus()");
3674        }
3675
3676        if ((mPrivateFlags & FOCUSED) != 0) {
3677            mPrivateFlags &= ~FOCUSED;
3678
3679            if (mParent != null) {
3680                mParent.clearChildFocus(this);
3681            }
3682
3683            onFocusChanged(false, 0, null);
3684            refreshDrawableState();
3685        }
3686    }
3687
3688    /**
3689     * Called to clear the focus of a view that is about to be removed.
3690     * Doesn't call clearChildFocus, which prevents this view from taking
3691     * focus again before it has been removed from the parent
3692     */
3693    void clearFocusForRemoval() {
3694        if ((mPrivateFlags & FOCUSED) != 0) {
3695            mPrivateFlags &= ~FOCUSED;
3696
3697            onFocusChanged(false, 0, null);
3698            refreshDrawableState();
3699        }
3700    }
3701
3702    /**
3703     * Called internally by the view system when a new view is getting focus.
3704     * This is what clears the old focus.
3705     */
3706    void unFocus() {
3707        if (DBG) {
3708            System.out.println(this + " unFocus()");
3709        }
3710
3711        if ((mPrivateFlags & FOCUSED) != 0) {
3712            mPrivateFlags &= ~FOCUSED;
3713
3714            onFocusChanged(false, 0, null);
3715            refreshDrawableState();
3716        }
3717    }
3718
3719    /**
3720     * Returns true if this view has focus iteself, or is the ancestor of the
3721     * view that has focus.
3722     *
3723     * @return True if this view has or contains focus, false otherwise.
3724     */
3725    @ViewDebug.ExportedProperty(category = "focus")
3726    public boolean hasFocus() {
3727        return (mPrivateFlags & FOCUSED) != 0;
3728    }
3729
3730    /**
3731     * Returns true if this view is focusable or if it contains a reachable View
3732     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3733     * is a View whose parents do not block descendants focus.
3734     *
3735     * Only {@link #VISIBLE} views are considered focusable.
3736     *
3737     * @return True if the view is focusable or if the view contains a focusable
3738     *         View, false otherwise.
3739     *
3740     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3741     */
3742    public boolean hasFocusable() {
3743        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3744    }
3745
3746    /**
3747     * Called by the view system when the focus state of this view changes.
3748     * When the focus change event is caused by directional navigation, direction
3749     * and previouslyFocusedRect provide insight into where the focus is coming from.
3750     * When overriding, be sure to call up through to the super class so that
3751     * the standard focus handling will occur.
3752     *
3753     * @param gainFocus True if the View has focus; false otherwise.
3754     * @param direction The direction focus has moved when requestFocus()
3755     *                  is called to give this view focus. Values are
3756     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3757     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3758     *                  It may not always apply, in which case use the default.
3759     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3760     *        system, of the previously focused view.  If applicable, this will be
3761     *        passed in as finer grained information about where the focus is coming
3762     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3763     */
3764    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3765        if (gainFocus) {
3766            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3767        }
3768
3769        InputMethodManager imm = InputMethodManager.peekInstance();
3770        if (!gainFocus) {
3771            if (isPressed()) {
3772                setPressed(false);
3773            }
3774            if (imm != null && mAttachInfo != null
3775                    && mAttachInfo.mHasWindowFocus) {
3776                imm.focusOut(this);
3777            }
3778            onFocusLost();
3779        } else if (imm != null && mAttachInfo != null
3780                && mAttachInfo.mHasWindowFocus) {
3781            imm.focusIn(this);
3782        }
3783
3784        invalidate(true);
3785        if (mOnFocusChangeListener != null) {
3786            mOnFocusChangeListener.onFocusChange(this, gainFocus);
3787        }
3788
3789        if (mAttachInfo != null) {
3790            mAttachInfo.mKeyDispatchState.reset(this);
3791        }
3792    }
3793
3794    /**
3795     * Sends an accessibility event of the given type. If accessiiblity is
3796     * not enabled this method has no effect. The default implementation calls
3797     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3798     * to populate information about the event source (this View), then calls
3799     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3800     * populate the text content of the event source including its descendants,
3801     * and last calls
3802     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3803     * on its parent to resuest sending of the event to interested parties.
3804     * <p>
3805     * If an {@link AccessibilityDelegate} has been specified via calling
3806     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3807     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3808     * responsible for handling this call.
3809     * </p>
3810     *
3811     * @param eventType The type of the event to send.
3812     *
3813     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3814     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3815     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3816     * @see AccessibilityDelegate
3817     */
3818    public void sendAccessibilityEvent(int eventType) {
3819        if (mAccessibilityDelegate != null) {
3820            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3821        } else {
3822            sendAccessibilityEventInternal(eventType);
3823        }
3824    }
3825
3826    /**
3827     * @see #sendAccessibilityEvent(int)
3828     *
3829     * Note: Called from the default {@link AccessibilityDelegate}.
3830     */
3831    void sendAccessibilityEventInternal(int eventType) {
3832        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3833            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3834        }
3835    }
3836
3837    /**
3838     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3839     * takes as an argument an empty {@link AccessibilityEvent} and does not
3840     * perform a check whether accessibility is enabled.
3841     * <p>
3842     * If an {@link AccessibilityDelegate} has been specified via calling
3843     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3844     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
3845     * is responsible for handling this call.
3846     * </p>
3847     *
3848     * @param event The event to send.
3849     *
3850     * @see #sendAccessibilityEvent(int)
3851     */
3852    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3853        if (mAccessibilityDelegate != null) {
3854           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
3855        } else {
3856            sendAccessibilityEventUncheckedInternal(event);
3857        }
3858    }
3859
3860    /**
3861     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
3862     *
3863     * Note: Called from the default {@link AccessibilityDelegate}.
3864     */
3865    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
3866        if (!isShown()) {
3867            return;
3868        }
3869        onInitializeAccessibilityEvent(event);
3870        // Only a subset of accessibility events populates text content.
3871        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
3872            dispatchPopulateAccessibilityEvent(event);
3873        }
3874        // In the beginning we called #isShown(), so we know that getParent() is not null.
3875        getParent().requestSendAccessibilityEvent(this, event);
3876    }
3877
3878    /**
3879     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3880     * to its children for adding their text content to the event. Note that the
3881     * event text is populated in a separate dispatch path since we add to the
3882     * event not only the text of the source but also the text of all its descendants.
3883     * A typical implementation will call
3884     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3885     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3886     * on each child. Override this method if custom population of the event text
3887     * content is required.
3888     * <p>
3889     * If an {@link AccessibilityDelegate} has been specified via calling
3890     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3891     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
3892     * is responsible for handling this call.
3893     * </p>
3894     * <p>
3895     * <em>Note:</em> Accessibility events of certain types are not dispatched for
3896     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
3897     * </p>
3898     *
3899     * @param event The event.
3900     *
3901     * @return True if the event population was completed.
3902     */
3903    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3904        if (mAccessibilityDelegate != null) {
3905            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
3906        } else {
3907            return dispatchPopulateAccessibilityEventInternal(event);
3908        }
3909    }
3910
3911    /**
3912     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3913     *
3914     * Note: Called from the default {@link AccessibilityDelegate}.
3915     */
3916    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
3917        onPopulateAccessibilityEvent(event);
3918        return false;
3919    }
3920
3921    /**
3922     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3923     * giving a chance to this View to populate the accessibility event with its
3924     * text content. While the implementation is free to modify other event
3925     * attributes this should be performed in
3926     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
3927     * <p>
3928     * Example: Adding formatted date string to an accessibility event in addition
3929     *          to the text added by the super implementation.
3930     * </p><p><pre><code>
3931     * public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3932     *     super.onPopulateAccessibilityEvent(event);
3933     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
3934     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
3935     *         mCurrentDate.getTimeInMillis(), flags);
3936     *     event.getText().add(selectedDateUtterance);
3937     * }
3938     * </code></pre></p>
3939     * <p>
3940     * If an {@link AccessibilityDelegate} has been specified via calling
3941     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3942     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
3943     * is responsible for handling this call.
3944     * </p>
3945     *
3946     * @param event The accessibility event which to populate.
3947     *
3948     * @see #sendAccessibilityEvent(int)
3949     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3950     */
3951    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
3952        if (mAccessibilityDelegate != null) {
3953            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
3954        } else {
3955            onPopulateAccessibilityEventInternal(event);
3956        }
3957    }
3958
3959    /**
3960     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
3961     *
3962     * Note: Called from the default {@link AccessibilityDelegate}.
3963     */
3964    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
3965
3966    }
3967
3968    /**
3969     * Initializes an {@link AccessibilityEvent} with information about
3970     * this View which is the event source. In other words, the source of
3971     * an accessibility event is the view whose state change triggered firing
3972     * the event.
3973     * <p>
3974     * Example: Setting the password property of an event in addition
3975     *          to properties set by the super implementation.
3976     * </p><p><pre><code>
3977     * public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3978     *    super.onInitializeAccessibilityEvent(event);
3979     *    event.setPassword(true);
3980     * }
3981     * </code></pre></p>
3982     * <p>
3983     * If an {@link AccessibilityDelegate} has been specified via calling
3984     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3985     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
3986     * is responsible for handling this call.
3987     * </p>
3988     *
3989     * @param event The event to initialize.
3990     *
3991     * @see #sendAccessibilityEvent(int)
3992     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3993     */
3994    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
3995        if (mAccessibilityDelegate != null) {
3996            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
3997        } else {
3998            onInitializeAccessibilityEventInternal(event);
3999        }
4000    }
4001
4002    /**
4003     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4004     *
4005     * Note: Called from the default {@link AccessibilityDelegate}.
4006     */
4007    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4008        event.setSource(this);
4009        event.setClassName(getClass().getName());
4010        event.setPackageName(getContext().getPackageName());
4011        event.setEnabled(isEnabled());
4012        event.setContentDescription(mContentDescription);
4013
4014        final int eventType = event.getEventType();
4015        switch (eventType) {
4016            case AccessibilityEvent.TYPE_VIEW_FOCUSED: {
4017                if (mAttachInfo != null) {
4018                    ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4019                    getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4020                            FOCUSABLES_ALL);
4021                    event.setItemCount(focusablesTempList.size());
4022                    event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4023                    focusablesTempList.clear();
4024                }
4025            } break;
4026            case AccessibilityEvent.TYPE_VIEW_SCROLLED: {
4027                event.setScrollX(mScrollX);
4028                event.setScrollY(mScrollY);
4029                event.setItemCount(getHeight());
4030            } break;
4031        }
4032    }
4033
4034    /**
4035     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4036     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4037     * This method is responsible for obtaining an accessibility node info from a
4038     * pool of reusable instances and calling
4039     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4040     * initialize the former.
4041     * <p>
4042     * Note: The client is responsible for recycling the obtained instance by calling
4043     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4044     * </p>
4045     * @return A populated {@link AccessibilityNodeInfo}.
4046     *
4047     * @see AccessibilityNodeInfo
4048     */
4049    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4050        AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4051        onInitializeAccessibilityNodeInfo(info);
4052        return info;
4053    }
4054
4055    /**
4056     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4057     * The base implementation sets:
4058     * <ul>
4059     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4060     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4061     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4062     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4063     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4064     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4065     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4066     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4067     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4068     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4069     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4070     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4071     * </ul>
4072     * <p>
4073     * Subclasses should override this method, call the super implementation,
4074     * and set additional attributes.
4075     * </p>
4076     * <p>
4077     * If an {@link AccessibilityDelegate} has been specified via calling
4078     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4079     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4080     * is responsible for handling this call.
4081     * </p>
4082     *
4083     * @param info The instance to initialize.
4084     */
4085    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4086        if (mAccessibilityDelegate != null) {
4087            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4088        } else {
4089            onInitializeAccessibilityNodeInfoInternal(info);
4090        }
4091    }
4092
4093    /**
4094     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4095     *
4096     * Note: Called from the default {@link AccessibilityDelegate}.
4097     */
4098    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4099        Rect bounds = mAttachInfo.mTmpInvalRect;
4100        getDrawingRect(bounds);
4101        info.setBoundsInParent(bounds);
4102
4103        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4104        getLocationOnScreen(locationOnScreen);
4105        bounds.offsetTo(0, 0);
4106        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4107        info.setBoundsInScreen(bounds);
4108
4109        ViewParent parent = getParent();
4110        if (parent instanceof View) {
4111            View parentView = (View) parent;
4112            info.setParent(parentView);
4113        }
4114
4115        info.setPackageName(mContext.getPackageName());
4116        info.setClassName(getClass().getName());
4117        info.setContentDescription(getContentDescription());
4118
4119        info.setEnabled(isEnabled());
4120        info.setClickable(isClickable());
4121        info.setFocusable(isFocusable());
4122        info.setFocused(isFocused());
4123        info.setSelected(isSelected());
4124        info.setLongClickable(isLongClickable());
4125
4126        // TODO: These make sense only if we are in an AdapterView but all
4127        // views can be selected. Maybe from accessiiblity perspective
4128        // we should report as selectable view in an AdapterView.
4129        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4130        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4131
4132        if (isFocusable()) {
4133            if (isFocused()) {
4134                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4135            } else {
4136                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4137            }
4138        }
4139    }
4140
4141    /**
4142     * Sets a delegate for implementing accessibility support via compositon as
4143     * opposed to inheritance. The delegate's primary use is for implementing
4144     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4145     *
4146     * @param delegate The delegate instance.
4147     *
4148     * @see AccessibilityDelegate
4149     */
4150    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4151        mAccessibilityDelegate = delegate;
4152    }
4153
4154    /**
4155     * Gets the unique identifier of this view on the screen for accessibility purposes.
4156     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4157     *
4158     * @return The view accessibility id.
4159     *
4160     * @hide
4161     */
4162    public int getAccessibilityViewId() {
4163        if (mAccessibilityViewId == NO_ID) {
4164            mAccessibilityViewId = sNextAccessibilityViewId++;
4165        }
4166        return mAccessibilityViewId;
4167    }
4168
4169    /**
4170     * Gets the unique identifier of the window in which this View reseides.
4171     *
4172     * @return The window accessibility id.
4173     *
4174     * @hide
4175     */
4176    public int getAccessibilityWindowId() {
4177        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4178    }
4179
4180    /**
4181     * Gets the {@link View} description. It briefly describes the view and is
4182     * primarily used for accessibility support. Set this property to enable
4183     * better accessibility support for your application. This is especially
4184     * true for views that do not have textual representation (For example,
4185     * ImageButton).
4186     *
4187     * @return The content descriptiopn.
4188     *
4189     * @attr ref android.R.styleable#View_contentDescription
4190     */
4191    public CharSequence getContentDescription() {
4192        return mContentDescription;
4193    }
4194
4195    /**
4196     * Sets the {@link View} description. It briefly describes the view and is
4197     * primarily used for accessibility support. Set this property to enable
4198     * better accessibility support for your application. This is especially
4199     * true for views that do not have textual representation (For example,
4200     * ImageButton).
4201     *
4202     * @param contentDescription The content description.
4203     *
4204     * @attr ref android.R.styleable#View_contentDescription
4205     */
4206    public void setContentDescription(CharSequence contentDescription) {
4207        mContentDescription = contentDescription;
4208    }
4209
4210    /**
4211     * Invoked whenever this view loses focus, either by losing window focus or by losing
4212     * focus within its window. This method can be used to clear any state tied to the
4213     * focus. For instance, if a button is held pressed with the trackball and the window
4214     * loses focus, this method can be used to cancel the press.
4215     *
4216     * Subclasses of View overriding this method should always call super.onFocusLost().
4217     *
4218     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4219     * @see #onWindowFocusChanged(boolean)
4220     *
4221     * @hide pending API council approval
4222     */
4223    protected void onFocusLost() {
4224        resetPressedState();
4225    }
4226
4227    private void resetPressedState() {
4228        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4229            return;
4230        }
4231
4232        if (isPressed()) {
4233            setPressed(false);
4234
4235            if (!mHasPerformedLongPress) {
4236                removeLongPressCallback();
4237            }
4238        }
4239    }
4240
4241    /**
4242     * Returns true if this view has focus
4243     *
4244     * @return True if this view has focus, false otherwise.
4245     */
4246    @ViewDebug.ExportedProperty(category = "focus")
4247    public boolean isFocused() {
4248        return (mPrivateFlags & FOCUSED) != 0;
4249    }
4250
4251    /**
4252     * Find the view in the hierarchy rooted at this view that currently has
4253     * focus.
4254     *
4255     * @return The view that currently has focus, or null if no focused view can
4256     *         be found.
4257     */
4258    public View findFocus() {
4259        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4260    }
4261
4262    /**
4263     * Change whether this view is one of the set of scrollable containers in
4264     * its window.  This will be used to determine whether the window can
4265     * resize or must pan when a soft input area is open -- scrollable
4266     * containers allow the window to use resize mode since the container
4267     * will appropriately shrink.
4268     */
4269    public void setScrollContainer(boolean isScrollContainer) {
4270        if (isScrollContainer) {
4271            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4272                mAttachInfo.mScrollContainers.add(this);
4273                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4274            }
4275            mPrivateFlags |= SCROLL_CONTAINER;
4276        } else {
4277            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4278                mAttachInfo.mScrollContainers.remove(this);
4279            }
4280            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4281        }
4282    }
4283
4284    /**
4285     * Returns the quality of the drawing cache.
4286     *
4287     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4288     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4289     *
4290     * @see #setDrawingCacheQuality(int)
4291     * @see #setDrawingCacheEnabled(boolean)
4292     * @see #isDrawingCacheEnabled()
4293     *
4294     * @attr ref android.R.styleable#View_drawingCacheQuality
4295     */
4296    public int getDrawingCacheQuality() {
4297        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4298    }
4299
4300    /**
4301     * Set the drawing cache quality of this view. This value is used only when the
4302     * drawing cache is enabled
4303     *
4304     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4305     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4306     *
4307     * @see #getDrawingCacheQuality()
4308     * @see #setDrawingCacheEnabled(boolean)
4309     * @see #isDrawingCacheEnabled()
4310     *
4311     * @attr ref android.R.styleable#View_drawingCacheQuality
4312     */
4313    public void setDrawingCacheQuality(int quality) {
4314        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4315    }
4316
4317    /**
4318     * Returns whether the screen should remain on, corresponding to the current
4319     * value of {@link #KEEP_SCREEN_ON}.
4320     *
4321     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4322     *
4323     * @see #setKeepScreenOn(boolean)
4324     *
4325     * @attr ref android.R.styleable#View_keepScreenOn
4326     */
4327    public boolean getKeepScreenOn() {
4328        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4329    }
4330
4331    /**
4332     * Controls whether the screen should remain on, modifying the
4333     * value of {@link #KEEP_SCREEN_ON}.
4334     *
4335     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4336     *
4337     * @see #getKeepScreenOn()
4338     *
4339     * @attr ref android.R.styleable#View_keepScreenOn
4340     */
4341    public void setKeepScreenOn(boolean keepScreenOn) {
4342        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4343    }
4344
4345    /**
4346     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4347     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4348     *
4349     * @attr ref android.R.styleable#View_nextFocusLeft
4350     */
4351    public int getNextFocusLeftId() {
4352        return mNextFocusLeftId;
4353    }
4354
4355    /**
4356     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4357     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4358     * decide automatically.
4359     *
4360     * @attr ref android.R.styleable#View_nextFocusLeft
4361     */
4362    public void setNextFocusLeftId(int nextFocusLeftId) {
4363        mNextFocusLeftId = nextFocusLeftId;
4364    }
4365
4366    /**
4367     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4368     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4369     *
4370     * @attr ref android.R.styleable#View_nextFocusRight
4371     */
4372    public int getNextFocusRightId() {
4373        return mNextFocusRightId;
4374    }
4375
4376    /**
4377     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4378     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4379     * decide automatically.
4380     *
4381     * @attr ref android.R.styleable#View_nextFocusRight
4382     */
4383    public void setNextFocusRightId(int nextFocusRightId) {
4384        mNextFocusRightId = nextFocusRightId;
4385    }
4386
4387    /**
4388     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4389     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4390     *
4391     * @attr ref android.R.styleable#View_nextFocusUp
4392     */
4393    public int getNextFocusUpId() {
4394        return mNextFocusUpId;
4395    }
4396
4397    /**
4398     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4399     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4400     * decide automatically.
4401     *
4402     * @attr ref android.R.styleable#View_nextFocusUp
4403     */
4404    public void setNextFocusUpId(int nextFocusUpId) {
4405        mNextFocusUpId = nextFocusUpId;
4406    }
4407
4408    /**
4409     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4410     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4411     *
4412     * @attr ref android.R.styleable#View_nextFocusDown
4413     */
4414    public int getNextFocusDownId() {
4415        return mNextFocusDownId;
4416    }
4417
4418    /**
4419     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4420     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4421     * decide automatically.
4422     *
4423     * @attr ref android.R.styleable#View_nextFocusDown
4424     */
4425    public void setNextFocusDownId(int nextFocusDownId) {
4426        mNextFocusDownId = nextFocusDownId;
4427    }
4428
4429    /**
4430     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4431     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4432     *
4433     * @attr ref android.R.styleable#View_nextFocusForward
4434     */
4435    public int getNextFocusForwardId() {
4436        return mNextFocusForwardId;
4437    }
4438
4439    /**
4440     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4441     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4442     * decide automatically.
4443     *
4444     * @attr ref android.R.styleable#View_nextFocusForward
4445     */
4446    public void setNextFocusForwardId(int nextFocusForwardId) {
4447        mNextFocusForwardId = nextFocusForwardId;
4448    }
4449
4450    /**
4451     * Returns the visibility of this view and all of its ancestors
4452     *
4453     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4454     */
4455    public boolean isShown() {
4456        View current = this;
4457        //noinspection ConstantConditions
4458        do {
4459            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4460                return false;
4461            }
4462            ViewParent parent = current.mParent;
4463            if (parent == null) {
4464                return false; // We are not attached to the view root
4465            }
4466            if (!(parent instanceof View)) {
4467                return true;
4468            }
4469            current = (View) parent;
4470        } while (current != null);
4471
4472        return false;
4473    }
4474
4475    /**
4476     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4477     * is set
4478     *
4479     * @param insets Insets for system windows
4480     *
4481     * @return True if this view applied the insets, false otherwise
4482     */
4483    protected boolean fitSystemWindows(Rect insets) {
4484        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4485            mPaddingLeft = insets.left;
4486            mPaddingTop = insets.top;
4487            mPaddingRight = insets.right;
4488            mPaddingBottom = insets.bottom;
4489            requestLayout();
4490            return true;
4491        }
4492        return false;
4493    }
4494
4495    /**
4496     * Set whether or not this view should account for system screen decorations
4497     * such as the status bar and inset its content. This allows this view to be
4498     * positioned in absolute screen coordinates and remain visible to the user.
4499     *
4500     * <p>This should only be used by top-level window decor views.
4501     *
4502     * @param fitSystemWindows true to inset content for system screen decorations, false for
4503     *                         default behavior.
4504     *
4505     * @attr ref android.R.styleable#View_fitsSystemWindows
4506     */
4507    public void setFitsSystemWindows(boolean fitSystemWindows) {
4508        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4509    }
4510
4511    /**
4512     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4513     * will account for system screen decorations such as the status bar and inset its
4514     * content. This allows the view to be positioned in absolute screen coordinates
4515     * and remain visible to the user.
4516     *
4517     * @return true if this view will adjust its content bounds for system screen decorations.
4518     *
4519     * @attr ref android.R.styleable#View_fitsSystemWindows
4520     */
4521    public boolean fitsSystemWindows() {
4522        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4523    }
4524
4525    /**
4526     * Returns the visibility status for this view.
4527     *
4528     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4529     * @attr ref android.R.styleable#View_visibility
4530     */
4531    @ViewDebug.ExportedProperty(mapping = {
4532        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4533        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4534        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4535    })
4536    public int getVisibility() {
4537        return mViewFlags & VISIBILITY_MASK;
4538    }
4539
4540    /**
4541     * Set the enabled state of this view.
4542     *
4543     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4544     * @attr ref android.R.styleable#View_visibility
4545     */
4546    @RemotableViewMethod
4547    public void setVisibility(int visibility) {
4548        setFlags(visibility, VISIBILITY_MASK);
4549        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4550    }
4551
4552    /**
4553     * Returns the enabled status for this view. The interpretation of the
4554     * enabled state varies by subclass.
4555     *
4556     * @return True if this view is enabled, false otherwise.
4557     */
4558    @ViewDebug.ExportedProperty
4559    public boolean isEnabled() {
4560        return (mViewFlags & ENABLED_MASK) == ENABLED;
4561    }
4562
4563    /**
4564     * Set the enabled state of this view. The interpretation of the enabled
4565     * state varies by subclass.
4566     *
4567     * @param enabled True if this view is enabled, false otherwise.
4568     */
4569    @RemotableViewMethod
4570    public void setEnabled(boolean enabled) {
4571        if (enabled == isEnabled()) return;
4572
4573        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4574
4575        /*
4576         * The View most likely has to change its appearance, so refresh
4577         * the drawable state.
4578         */
4579        refreshDrawableState();
4580
4581        // Invalidate too, since the default behavior for views is to be
4582        // be drawn at 50% alpha rather than to change the drawable.
4583        invalidate(true);
4584    }
4585
4586    /**
4587     * Set whether this view can receive the focus.
4588     *
4589     * Setting this to false will also ensure that this view is not focusable
4590     * in touch mode.
4591     *
4592     * @param focusable If true, this view can receive the focus.
4593     *
4594     * @see #setFocusableInTouchMode(boolean)
4595     * @attr ref android.R.styleable#View_focusable
4596     */
4597    public void setFocusable(boolean focusable) {
4598        if (!focusable) {
4599            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4600        }
4601        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4602    }
4603
4604    /**
4605     * Set whether this view can receive focus while in touch mode.
4606     *
4607     * Setting this to true will also ensure that this view is focusable.
4608     *
4609     * @param focusableInTouchMode If true, this view can receive the focus while
4610     *   in touch mode.
4611     *
4612     * @see #setFocusable(boolean)
4613     * @attr ref android.R.styleable#View_focusableInTouchMode
4614     */
4615    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4616        // Focusable in touch mode should always be set before the focusable flag
4617        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4618        // which, in touch mode, will not successfully request focus on this view
4619        // because the focusable in touch mode flag is not set
4620        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4621        if (focusableInTouchMode) {
4622            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4623        }
4624    }
4625
4626    /**
4627     * Set whether this view should have sound effects enabled for events such as
4628     * clicking and touching.
4629     *
4630     * <p>You may wish to disable sound effects for a view if you already play sounds,
4631     * for instance, a dial key that plays dtmf tones.
4632     *
4633     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4634     * @see #isSoundEffectsEnabled()
4635     * @see #playSoundEffect(int)
4636     * @attr ref android.R.styleable#View_soundEffectsEnabled
4637     */
4638    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4639        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4640    }
4641
4642    /**
4643     * @return whether this view should have sound effects enabled for events such as
4644     *     clicking and touching.
4645     *
4646     * @see #setSoundEffectsEnabled(boolean)
4647     * @see #playSoundEffect(int)
4648     * @attr ref android.R.styleable#View_soundEffectsEnabled
4649     */
4650    @ViewDebug.ExportedProperty
4651    public boolean isSoundEffectsEnabled() {
4652        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4653    }
4654
4655    /**
4656     * Set whether this view should have haptic feedback for events such as
4657     * long presses.
4658     *
4659     * <p>You may wish to disable haptic feedback if your view already controls
4660     * its own haptic feedback.
4661     *
4662     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4663     * @see #isHapticFeedbackEnabled()
4664     * @see #performHapticFeedback(int)
4665     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4666     */
4667    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4668        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4669    }
4670
4671    /**
4672     * @return whether this view should have haptic feedback enabled for events
4673     * long presses.
4674     *
4675     * @see #setHapticFeedbackEnabled(boolean)
4676     * @see #performHapticFeedback(int)
4677     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4678     */
4679    @ViewDebug.ExportedProperty
4680    public boolean isHapticFeedbackEnabled() {
4681        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4682    }
4683
4684    /**
4685     * Returns the layout direction for this view.
4686     *
4687     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4688     *   {@link #LAYOUT_DIRECTION_RTL},
4689     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4690     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4691     * @attr ref android.R.styleable#View_layoutDirection
4692     *
4693     * @hide
4694     */
4695    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4696        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4697        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4698        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4699        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4700    })
4701    public int getLayoutDirection() {
4702        return mViewFlags & LAYOUT_DIRECTION_MASK;
4703    }
4704
4705    /**
4706     * Set the layout direction for this view. This will propagate a reset of layout direction
4707     * resolution to the view's children and resolve layout direction for this view.
4708     *
4709     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4710     *   {@link #LAYOUT_DIRECTION_RTL},
4711     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4712     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4713     *
4714     * @attr ref android.R.styleable#View_layoutDirection
4715     *
4716     * @hide
4717     */
4718    @RemotableViewMethod
4719    public void setLayoutDirection(int layoutDirection) {
4720        if (getLayoutDirection() != layoutDirection) {
4721            resetResolvedLayoutDirection();
4722            // Setting the flag will also request a layout.
4723            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4724        }
4725    }
4726
4727    /**
4728     * Returns the resolved layout direction for this view.
4729     *
4730     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4731     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4732     *
4733     * @hide
4734     */
4735    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4736        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4737        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4738    })
4739    public int getResolvedLayoutDirection() {
4740        resolveLayoutDirectionIfNeeded();
4741        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4742                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4743    }
4744
4745    /**
4746     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4747     * layout attribute and/or the inherited value from the parent.</p>
4748     *
4749     * @return true if the layout is right-to-left.
4750     *
4751     * @hide
4752     */
4753    @ViewDebug.ExportedProperty(category = "layout")
4754    public boolean isLayoutRtl() {
4755        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4756    }
4757
4758    /**
4759     * If this view doesn't do any drawing on its own, set this flag to
4760     * allow further optimizations. By default, this flag is not set on
4761     * View, but could be set on some View subclasses such as ViewGroup.
4762     *
4763     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4764     * you should clear this flag.
4765     *
4766     * @param willNotDraw whether or not this View draw on its own
4767     */
4768    public void setWillNotDraw(boolean willNotDraw) {
4769        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4770    }
4771
4772    /**
4773     * Returns whether or not this View draws on its own.
4774     *
4775     * @return true if this view has nothing to draw, false otherwise
4776     */
4777    @ViewDebug.ExportedProperty(category = "drawing")
4778    public boolean willNotDraw() {
4779        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4780    }
4781
4782    /**
4783     * When a View's drawing cache is enabled, drawing is redirected to an
4784     * offscreen bitmap. Some views, like an ImageView, must be able to
4785     * bypass this mechanism if they already draw a single bitmap, to avoid
4786     * unnecessary usage of the memory.
4787     *
4788     * @param willNotCacheDrawing true if this view does not cache its
4789     *        drawing, false otherwise
4790     */
4791    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4792        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4793    }
4794
4795    /**
4796     * Returns whether or not this View can cache its drawing or not.
4797     *
4798     * @return true if this view does not cache its drawing, false otherwise
4799     */
4800    @ViewDebug.ExportedProperty(category = "drawing")
4801    public boolean willNotCacheDrawing() {
4802        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4803    }
4804
4805    /**
4806     * Indicates whether this view reacts to click events or not.
4807     *
4808     * @return true if the view is clickable, false otherwise
4809     *
4810     * @see #setClickable(boolean)
4811     * @attr ref android.R.styleable#View_clickable
4812     */
4813    @ViewDebug.ExportedProperty
4814    public boolean isClickable() {
4815        return (mViewFlags & CLICKABLE) == CLICKABLE;
4816    }
4817
4818    /**
4819     * Enables or disables click events for this view. When a view
4820     * is clickable it will change its state to "pressed" on every click.
4821     * Subclasses should set the view clickable to visually react to
4822     * user's clicks.
4823     *
4824     * @param clickable true to make the view clickable, false otherwise
4825     *
4826     * @see #isClickable()
4827     * @attr ref android.R.styleable#View_clickable
4828     */
4829    public void setClickable(boolean clickable) {
4830        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4831    }
4832
4833    /**
4834     * Indicates whether this view reacts to long click events or not.
4835     *
4836     * @return true if the view is long clickable, false otherwise
4837     *
4838     * @see #setLongClickable(boolean)
4839     * @attr ref android.R.styleable#View_longClickable
4840     */
4841    public boolean isLongClickable() {
4842        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4843    }
4844
4845    /**
4846     * Enables or disables long click events for this view. When a view is long
4847     * clickable it reacts to the user holding down the button for a longer
4848     * duration than a tap. This event can either launch the listener or a
4849     * context menu.
4850     *
4851     * @param longClickable true to make the view long clickable, false otherwise
4852     * @see #isLongClickable()
4853     * @attr ref android.R.styleable#View_longClickable
4854     */
4855    public void setLongClickable(boolean longClickable) {
4856        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4857    }
4858
4859    /**
4860     * Sets the pressed state for this view.
4861     *
4862     * @see #isClickable()
4863     * @see #setClickable(boolean)
4864     *
4865     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4866     *        the View's internal state from a previously set "pressed" state.
4867     */
4868    public void setPressed(boolean pressed) {
4869        if (pressed) {
4870            mPrivateFlags |= PRESSED;
4871        } else {
4872            mPrivateFlags &= ~PRESSED;
4873        }
4874        refreshDrawableState();
4875        dispatchSetPressed(pressed);
4876    }
4877
4878    /**
4879     * Dispatch setPressed to all of this View's children.
4880     *
4881     * @see #setPressed(boolean)
4882     *
4883     * @param pressed The new pressed state
4884     */
4885    protected void dispatchSetPressed(boolean pressed) {
4886    }
4887
4888    /**
4889     * Indicates whether the view is currently in pressed state. Unless
4890     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
4891     * the pressed state.
4892     *
4893     * @see #setPressed(boolean)
4894     * @see #isClickable()
4895     * @see #setClickable(boolean)
4896     *
4897     * @return true if the view is currently pressed, false otherwise
4898     */
4899    public boolean isPressed() {
4900        return (mPrivateFlags & PRESSED) == PRESSED;
4901    }
4902
4903    /**
4904     * Indicates whether this view will save its state (that is,
4905     * whether its {@link #onSaveInstanceState} method will be called).
4906     *
4907     * @return Returns true if the view state saving is enabled, else false.
4908     *
4909     * @see #setSaveEnabled(boolean)
4910     * @attr ref android.R.styleable#View_saveEnabled
4911     */
4912    public boolean isSaveEnabled() {
4913        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
4914    }
4915
4916    /**
4917     * Controls whether the saving of this view's state is
4918     * enabled (that is, whether its {@link #onSaveInstanceState} method
4919     * will be called).  Note that even if freezing is enabled, the
4920     * view still must have an id assigned to it (via {@link #setId(int)})
4921     * for its state to be saved.  This flag can only disable the
4922     * saving of this view; any child views may still have their state saved.
4923     *
4924     * @param enabled Set to false to <em>disable</em> state saving, or true
4925     * (the default) to allow it.
4926     *
4927     * @see #isSaveEnabled()
4928     * @see #setId(int)
4929     * @see #onSaveInstanceState()
4930     * @attr ref android.R.styleable#View_saveEnabled
4931     */
4932    public void setSaveEnabled(boolean enabled) {
4933        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
4934    }
4935
4936    /**
4937     * Gets whether the framework should discard touches when the view's
4938     * window is obscured by another visible window.
4939     * Refer to the {@link View} security documentation for more details.
4940     *
4941     * @return True if touch filtering is enabled.
4942     *
4943     * @see #setFilterTouchesWhenObscured(boolean)
4944     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4945     */
4946    @ViewDebug.ExportedProperty
4947    public boolean getFilterTouchesWhenObscured() {
4948        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
4949    }
4950
4951    /**
4952     * Sets whether the framework should discard touches when the view's
4953     * window is obscured by another visible window.
4954     * Refer to the {@link View} security documentation for more details.
4955     *
4956     * @param enabled True if touch filtering should be enabled.
4957     *
4958     * @see #getFilterTouchesWhenObscured
4959     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
4960     */
4961    public void setFilterTouchesWhenObscured(boolean enabled) {
4962        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
4963                FILTER_TOUCHES_WHEN_OBSCURED);
4964    }
4965
4966    /**
4967     * Indicates whether the entire hierarchy under this view will save its
4968     * state when a state saving traversal occurs from its parent.  The default
4969     * is true; if false, these views will not be saved unless
4970     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4971     *
4972     * @return Returns true if the view state saving from parent is enabled, else false.
4973     *
4974     * @see #setSaveFromParentEnabled(boolean)
4975     */
4976    public boolean isSaveFromParentEnabled() {
4977        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
4978    }
4979
4980    /**
4981     * Controls whether the entire hierarchy under this view will save its
4982     * state when a state saving traversal occurs from its parent.  The default
4983     * is true; if false, these views will not be saved unless
4984     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
4985     *
4986     * @param enabled Set to false to <em>disable</em> state saving, or true
4987     * (the default) to allow it.
4988     *
4989     * @see #isSaveFromParentEnabled()
4990     * @see #setId(int)
4991     * @see #onSaveInstanceState()
4992     */
4993    public void setSaveFromParentEnabled(boolean enabled) {
4994        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
4995    }
4996
4997
4998    /**
4999     * Returns whether this View is able to take focus.
5000     *
5001     * @return True if this view can take focus, or false otherwise.
5002     * @attr ref android.R.styleable#View_focusable
5003     */
5004    @ViewDebug.ExportedProperty(category = "focus")
5005    public final boolean isFocusable() {
5006        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5007    }
5008
5009    /**
5010     * When a view is focusable, it may not want to take focus when in touch mode.
5011     * For example, a button would like focus when the user is navigating via a D-pad
5012     * so that the user can click on it, but once the user starts touching the screen,
5013     * the button shouldn't take focus
5014     * @return Whether the view is focusable in touch mode.
5015     * @attr ref android.R.styleable#View_focusableInTouchMode
5016     */
5017    @ViewDebug.ExportedProperty
5018    public final boolean isFocusableInTouchMode() {
5019        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5020    }
5021
5022    /**
5023     * Find the nearest view in the specified direction that can take focus.
5024     * This does not actually give focus to that view.
5025     *
5026     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5027     *
5028     * @return The nearest focusable in the specified direction, or null if none
5029     *         can be found.
5030     */
5031    public View focusSearch(int direction) {
5032        if (mParent != null) {
5033            return mParent.focusSearch(this, direction);
5034        } else {
5035            return null;
5036        }
5037    }
5038
5039    /**
5040     * This method is the last chance for the focused view and its ancestors to
5041     * respond to an arrow key. This is called when the focused view did not
5042     * consume the key internally, nor could the view system find a new view in
5043     * the requested direction to give focus to.
5044     *
5045     * @param focused The currently focused view.
5046     * @param direction The direction focus wants to move. One of FOCUS_UP,
5047     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5048     * @return True if the this view consumed this unhandled move.
5049     */
5050    public boolean dispatchUnhandledMove(View focused, int direction) {
5051        return false;
5052    }
5053
5054    /**
5055     * If a user manually specified the next view id for a particular direction,
5056     * use the root to look up the view.
5057     * @param root The root view of the hierarchy containing this view.
5058     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5059     * or FOCUS_BACKWARD.
5060     * @return The user specified next view, or null if there is none.
5061     */
5062    View findUserSetNextFocus(View root, int direction) {
5063        switch (direction) {
5064            case FOCUS_LEFT:
5065                if (mNextFocusLeftId == View.NO_ID) return null;
5066                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5067            case FOCUS_RIGHT:
5068                if (mNextFocusRightId == View.NO_ID) return null;
5069                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5070            case FOCUS_UP:
5071                if (mNextFocusUpId == View.NO_ID) return null;
5072                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5073            case FOCUS_DOWN:
5074                if (mNextFocusDownId == View.NO_ID) return null;
5075                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5076            case FOCUS_FORWARD:
5077                if (mNextFocusForwardId == View.NO_ID) return null;
5078                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5079            case FOCUS_BACKWARD: {
5080                final int id = mID;
5081                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5082                    @Override
5083                    public boolean apply(View t) {
5084                        return t.mNextFocusForwardId == id;
5085                    }
5086                });
5087            }
5088        }
5089        return null;
5090    }
5091
5092    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5093        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5094            @Override
5095            public boolean apply(View t) {
5096                return t.mID == childViewId;
5097            }
5098        });
5099
5100        if (result == null) {
5101            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5102                    + "by user for id " + childViewId);
5103        }
5104        return result;
5105    }
5106
5107    /**
5108     * Find and return all focusable views that are descendants of this view,
5109     * possibly including this view if it is focusable itself.
5110     *
5111     * @param direction The direction of the focus
5112     * @return A list of focusable views
5113     */
5114    public ArrayList<View> getFocusables(int direction) {
5115        ArrayList<View> result = new ArrayList<View>(24);
5116        addFocusables(result, direction);
5117        return result;
5118    }
5119
5120    /**
5121     * Add any focusable views that are descendants of this view (possibly
5122     * including this view if it is focusable itself) to views.  If we are in touch mode,
5123     * only add views that are also focusable in touch mode.
5124     *
5125     * @param views Focusable views found so far
5126     * @param direction The direction of the focus
5127     */
5128    public void addFocusables(ArrayList<View> views, int direction) {
5129        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5130    }
5131
5132    /**
5133     * Adds any focusable views that are descendants of this view (possibly
5134     * including this view if it is focusable itself) to views. This method
5135     * adds all focusable views regardless if we are in touch mode or
5136     * only views focusable in touch mode if we are in touch mode depending on
5137     * the focusable mode paramater.
5138     *
5139     * @param views Focusable views found so far or null if all we are interested is
5140     *        the number of focusables.
5141     * @param direction The direction of the focus.
5142     * @param focusableMode The type of focusables to be added.
5143     *
5144     * @see #FOCUSABLES_ALL
5145     * @see #FOCUSABLES_TOUCH_MODE
5146     */
5147    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5148        if (!isFocusable()) {
5149            return;
5150        }
5151
5152        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5153                isInTouchMode() && !isFocusableInTouchMode()) {
5154            return;
5155        }
5156
5157        if (views != null) {
5158            views.add(this);
5159        }
5160    }
5161
5162    /**
5163     * Finds the Views that contain given text. The containment is case insensitive.
5164     * The search is performed by either the text that the View renders or the content
5165     * description that describes the view for accessibility purposes and the view does
5166     * not render or both. Clients can specify how the search is to be performed via
5167     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5168     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5169     *
5170     * @param outViews The output list of matching Views.
5171     * @param searched The text to match against.
5172     *
5173     * @see #FIND_VIEWS_WITH_TEXT
5174     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5175     * @see #setContentDescription(CharSequence)
5176     */
5177    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5178        if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 && !TextUtils.isEmpty(searched)
5179                && !TextUtils.isEmpty(mContentDescription)) {
5180            String searchedLowerCase = searched.toString().toLowerCase();
5181            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5182            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5183                outViews.add(this);
5184            }
5185        }
5186    }
5187
5188    /**
5189     * Find and return all touchable views that are descendants of this view,
5190     * possibly including this view if it is touchable itself.
5191     *
5192     * @return A list of touchable views
5193     */
5194    public ArrayList<View> getTouchables() {
5195        ArrayList<View> result = new ArrayList<View>();
5196        addTouchables(result);
5197        return result;
5198    }
5199
5200    /**
5201     * Add any touchable views that are descendants of this view (possibly
5202     * including this view if it is touchable itself) to views.
5203     *
5204     * @param views Touchable views found so far
5205     */
5206    public void addTouchables(ArrayList<View> views) {
5207        final int viewFlags = mViewFlags;
5208
5209        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5210                && (viewFlags & ENABLED_MASK) == ENABLED) {
5211            views.add(this);
5212        }
5213    }
5214
5215    /**
5216     * Call this to try to give focus to a specific view or to one of its
5217     * descendants.
5218     *
5219     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5220     * false), or if it is focusable and it is not focusable in touch mode
5221     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5222     *
5223     * See also {@link #focusSearch(int)}, which is what you call to say that you
5224     * have focus, and you want your parent to look for the next one.
5225     *
5226     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5227     * {@link #FOCUS_DOWN} and <code>null</code>.
5228     *
5229     * @return Whether this view or one of its descendants actually took focus.
5230     */
5231    public final boolean requestFocus() {
5232        return requestFocus(View.FOCUS_DOWN);
5233    }
5234
5235
5236    /**
5237     * Call this to try to give focus to a specific view or to one of its
5238     * descendants and give it a hint about what direction focus is heading.
5239     *
5240     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5241     * false), or if it is focusable and it is not focusable in touch mode
5242     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5243     *
5244     * See also {@link #focusSearch(int)}, which is what you call to say that you
5245     * have focus, and you want your parent to look for the next one.
5246     *
5247     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5248     * <code>null</code> set for the previously focused rectangle.
5249     *
5250     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5251     * @return Whether this view or one of its descendants actually took focus.
5252     */
5253    public final boolean requestFocus(int direction) {
5254        return requestFocus(direction, null);
5255    }
5256
5257    /**
5258     * Call this to try to give focus to a specific view or to one of its descendants
5259     * and give it hints about the direction and a specific rectangle that the focus
5260     * is coming from.  The rectangle can help give larger views a finer grained hint
5261     * about where focus is coming from, and therefore, where to show selection, or
5262     * forward focus change internally.
5263     *
5264     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5265     * false), or if it is focusable and it is not focusable in touch mode
5266     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5267     *
5268     * A View will not take focus if it is not visible.
5269     *
5270     * A View will not take focus if one of its parents has
5271     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5272     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5273     *
5274     * See also {@link #focusSearch(int)}, which is what you call to say that you
5275     * have focus, and you want your parent to look for the next one.
5276     *
5277     * You may wish to override this method if your custom {@link View} has an internal
5278     * {@link View} that it wishes to forward the request to.
5279     *
5280     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5281     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5282     *        to give a finer grained hint about where focus is coming from.  May be null
5283     *        if there is no hint.
5284     * @return Whether this view or one of its descendants actually took focus.
5285     */
5286    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5287        // need to be focusable
5288        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5289                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5290            return false;
5291        }
5292
5293        // need to be focusable in touch mode if in touch mode
5294        if (isInTouchMode() &&
5295            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5296               return false;
5297        }
5298
5299        // need to not have any parents blocking us
5300        if (hasAncestorThatBlocksDescendantFocus()) {
5301            return false;
5302        }
5303
5304        handleFocusGainInternal(direction, previouslyFocusedRect);
5305        return true;
5306    }
5307
5308    /** Gets the ViewAncestor, or null if not attached. */
5309    /*package*/ ViewRootImpl getViewRootImpl() {
5310        View root = getRootView();
5311        return root != null ? (ViewRootImpl)root.getParent() : null;
5312    }
5313
5314    /**
5315     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5316     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5317     * touch mode to request focus when they are touched.
5318     *
5319     * @return Whether this view or one of its descendants actually took focus.
5320     *
5321     * @see #isInTouchMode()
5322     *
5323     */
5324    public final boolean requestFocusFromTouch() {
5325        // Leave touch mode if we need to
5326        if (isInTouchMode()) {
5327            ViewRootImpl viewRoot = getViewRootImpl();
5328            if (viewRoot != null) {
5329                viewRoot.ensureTouchMode(false);
5330            }
5331        }
5332        return requestFocus(View.FOCUS_DOWN);
5333    }
5334
5335    /**
5336     * @return Whether any ancestor of this view blocks descendant focus.
5337     */
5338    private boolean hasAncestorThatBlocksDescendantFocus() {
5339        ViewParent ancestor = mParent;
5340        while (ancestor instanceof ViewGroup) {
5341            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5342            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5343                return true;
5344            } else {
5345                ancestor = vgAncestor.getParent();
5346            }
5347        }
5348        return false;
5349    }
5350
5351    /**
5352     * @hide
5353     */
5354    public void dispatchStartTemporaryDetach() {
5355        onStartTemporaryDetach();
5356    }
5357
5358    /**
5359     * This is called when a container is going to temporarily detach a child, with
5360     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5361     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5362     * {@link #onDetachedFromWindow()} when the container is done.
5363     */
5364    public void onStartTemporaryDetach() {
5365        removeUnsetPressCallback();
5366        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5367    }
5368
5369    /**
5370     * @hide
5371     */
5372    public void dispatchFinishTemporaryDetach() {
5373        onFinishTemporaryDetach();
5374    }
5375
5376    /**
5377     * Called after {@link #onStartTemporaryDetach} when the container is done
5378     * changing the view.
5379     */
5380    public void onFinishTemporaryDetach() {
5381    }
5382
5383    /**
5384     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5385     * for this view's window.  Returns null if the view is not currently attached
5386     * to the window.  Normally you will not need to use this directly, but
5387     * just use the standard high-level event callbacks like
5388     * {@link #onKeyDown(int, KeyEvent)}.
5389     */
5390    public KeyEvent.DispatcherState getKeyDispatcherState() {
5391        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5392    }
5393
5394    /**
5395     * Dispatch a key event before it is processed by any input method
5396     * associated with the view hierarchy.  This can be used to intercept
5397     * key events in special situations before the IME consumes them; a
5398     * typical example would be handling the BACK key to update the application's
5399     * UI instead of allowing the IME to see it and close itself.
5400     *
5401     * @param event The key event to be dispatched.
5402     * @return True if the event was handled, false otherwise.
5403     */
5404    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5405        return onKeyPreIme(event.getKeyCode(), event);
5406    }
5407
5408    /**
5409     * Dispatch a key event to the next view on the focus path. This path runs
5410     * from the top of the view tree down to the currently focused view. If this
5411     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5412     * the next node down the focus path. This method also fires any key
5413     * listeners.
5414     *
5415     * @param event The key event to be dispatched.
5416     * @return True if the event was handled, false otherwise.
5417     */
5418    public boolean dispatchKeyEvent(KeyEvent event) {
5419        if (mInputEventConsistencyVerifier != null) {
5420            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5421        }
5422
5423        // Give any attached key listener a first crack at the event.
5424        //noinspection SimplifiableIfStatement
5425        if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5426                && mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5427            return true;
5428        }
5429
5430        if (event.dispatch(this, mAttachInfo != null
5431                ? mAttachInfo.mKeyDispatchState : null, this)) {
5432            return true;
5433        }
5434
5435        if (mInputEventConsistencyVerifier != null) {
5436            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5437        }
5438        return false;
5439    }
5440
5441    /**
5442     * Dispatches a key shortcut event.
5443     *
5444     * @param event The key event to be dispatched.
5445     * @return True if the event was handled by the view, false otherwise.
5446     */
5447    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5448        return onKeyShortcut(event.getKeyCode(), event);
5449    }
5450
5451    /**
5452     * Pass the touch screen motion event down to the target view, or this
5453     * view if it is the target.
5454     *
5455     * @param event The motion event to be dispatched.
5456     * @return True if the event was handled by the view, false otherwise.
5457     */
5458    public boolean dispatchTouchEvent(MotionEvent event) {
5459        if (mInputEventConsistencyVerifier != null) {
5460            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5461        }
5462
5463        if (onFilterTouchEventForSecurity(event)) {
5464            //noinspection SimplifiableIfStatement
5465            if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
5466                    mOnTouchListener.onTouch(this, event)) {
5467                return true;
5468            }
5469
5470            if (onTouchEvent(event)) {
5471                return true;
5472            }
5473        }
5474
5475        if (mInputEventConsistencyVerifier != null) {
5476            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5477        }
5478        return false;
5479    }
5480
5481    /**
5482     * Filter the touch event to apply security policies.
5483     *
5484     * @param event The motion event to be filtered.
5485     * @return True if the event should be dispatched, false if the event should be dropped.
5486     *
5487     * @see #getFilterTouchesWhenObscured
5488     */
5489    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5490        //noinspection RedundantIfStatement
5491        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5492                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5493            // Window is obscured, drop this touch.
5494            return false;
5495        }
5496        return true;
5497    }
5498
5499    /**
5500     * Pass a trackball motion event down to the focused view.
5501     *
5502     * @param event The motion event to be dispatched.
5503     * @return True if the event was handled by the view, false otherwise.
5504     */
5505    public boolean dispatchTrackballEvent(MotionEvent event) {
5506        if (mInputEventConsistencyVerifier != null) {
5507            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5508        }
5509
5510        return onTrackballEvent(event);
5511    }
5512
5513    /**
5514     * Dispatch a generic motion event.
5515     * <p>
5516     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5517     * are delivered to the view under the pointer.  All other generic motion events are
5518     * delivered to the focused view.  Hover events are handled specially and are delivered
5519     * to {@link #onHoverEvent(MotionEvent)}.
5520     * </p>
5521     *
5522     * @param event The motion event to be dispatched.
5523     * @return True if the event was handled by the view, false otherwise.
5524     */
5525    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5526        if (mInputEventConsistencyVerifier != null) {
5527            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5528        }
5529
5530        final int source = event.getSource();
5531        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5532            final int action = event.getAction();
5533            if (action == MotionEvent.ACTION_HOVER_ENTER
5534                    || action == MotionEvent.ACTION_HOVER_MOVE
5535                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5536                if (dispatchHoverEvent(event)) {
5537                    return true;
5538                }
5539            } else if (dispatchGenericPointerEvent(event)) {
5540                return true;
5541            }
5542        } else if (dispatchGenericFocusedEvent(event)) {
5543            return true;
5544        }
5545
5546        if (dispatchGenericMotionEventInternal(event)) {
5547            return true;
5548        }
5549
5550        if (mInputEventConsistencyVerifier != null) {
5551            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5552        }
5553        return false;
5554    }
5555
5556    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5557        //noinspection SimplifiableIfStatement
5558        if (mOnGenericMotionListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5559                && mOnGenericMotionListener.onGenericMotion(this, event)) {
5560            return true;
5561        }
5562
5563        if (onGenericMotionEvent(event)) {
5564            return true;
5565        }
5566
5567        if (mInputEventConsistencyVerifier != null) {
5568            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5569        }
5570        return false;
5571    }
5572
5573    /**
5574     * Dispatch a hover event.
5575     * <p>
5576     * Do not call this method directly.
5577     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5578     * </p>
5579     *
5580     * @param event The motion event to be dispatched.
5581     * @return True if the event was handled by the view, false otherwise.
5582     */
5583    protected boolean dispatchHoverEvent(MotionEvent event) {
5584        //noinspection SimplifiableIfStatement
5585        if (mOnHoverListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5586                && mOnHoverListener.onHover(this, event)) {
5587            return true;
5588        }
5589
5590        return onHoverEvent(event);
5591    }
5592
5593    /**
5594     * Returns true if the view has a child to which it has recently sent
5595     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5596     * it does not have a hovered child, then it must be the innermost hovered view.
5597     * @hide
5598     */
5599    protected boolean hasHoveredChild() {
5600        return false;
5601    }
5602
5603    /**
5604     * Dispatch a generic motion event to the view under the first pointer.
5605     * <p>
5606     * Do not call this method directly.
5607     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5608     * </p>
5609     *
5610     * @param event The motion event to be dispatched.
5611     * @return True if the event was handled by the view, false otherwise.
5612     */
5613    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5614        return false;
5615    }
5616
5617    /**
5618     * Dispatch a generic motion event to the currently focused view.
5619     * <p>
5620     * Do not call this method directly.
5621     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5622     * </p>
5623     *
5624     * @param event The motion event to be dispatched.
5625     * @return True if the event was handled by the view, false otherwise.
5626     */
5627    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5628        return false;
5629    }
5630
5631    /**
5632     * Dispatch a pointer event.
5633     * <p>
5634     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5635     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5636     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5637     * and should not be expected to handle other pointing device features.
5638     * </p>
5639     *
5640     * @param event The motion event to be dispatched.
5641     * @return True if the event was handled by the view, false otherwise.
5642     * @hide
5643     */
5644    public final boolean dispatchPointerEvent(MotionEvent event) {
5645        if (event.isTouchEvent()) {
5646            return dispatchTouchEvent(event);
5647        } else {
5648            return dispatchGenericMotionEvent(event);
5649        }
5650    }
5651
5652    /**
5653     * Called when the window containing this view gains or loses window focus.
5654     * ViewGroups should override to route to their children.
5655     *
5656     * @param hasFocus True if the window containing this view now has focus,
5657     *        false otherwise.
5658     */
5659    public void dispatchWindowFocusChanged(boolean hasFocus) {
5660        onWindowFocusChanged(hasFocus);
5661    }
5662
5663    /**
5664     * Called when the window containing this view gains or loses focus.  Note
5665     * that this is separate from view focus: to receive key events, both
5666     * your view and its window must have focus.  If a window is displayed
5667     * on top of yours that takes input focus, then your own window will lose
5668     * focus but the view focus will remain unchanged.
5669     *
5670     * @param hasWindowFocus True if the window containing this view now has
5671     *        focus, false otherwise.
5672     */
5673    public void onWindowFocusChanged(boolean hasWindowFocus) {
5674        InputMethodManager imm = InputMethodManager.peekInstance();
5675        if (!hasWindowFocus) {
5676            if (isPressed()) {
5677                setPressed(false);
5678            }
5679            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5680                imm.focusOut(this);
5681            }
5682            removeLongPressCallback();
5683            removeTapCallback();
5684            onFocusLost();
5685        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5686            imm.focusIn(this);
5687        }
5688        refreshDrawableState();
5689    }
5690
5691    /**
5692     * Returns true if this view is in a window that currently has window focus.
5693     * Note that this is not the same as the view itself having focus.
5694     *
5695     * @return True if this view is in a window that currently has window focus.
5696     */
5697    public boolean hasWindowFocus() {
5698        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5699    }
5700
5701    /**
5702     * Dispatch a view visibility change down the view hierarchy.
5703     * ViewGroups should override to route to their children.
5704     * @param changedView The view whose visibility changed. Could be 'this' or
5705     * an ancestor view.
5706     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5707     * {@link #INVISIBLE} or {@link #GONE}.
5708     */
5709    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5710        onVisibilityChanged(changedView, visibility);
5711    }
5712
5713    /**
5714     * Called when the visibility of the view or an ancestor of the view is changed.
5715     * @param changedView The view whose visibility changed. Could be 'this' or
5716     * an ancestor view.
5717     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5718     * {@link #INVISIBLE} or {@link #GONE}.
5719     */
5720    protected void onVisibilityChanged(View changedView, int visibility) {
5721        if (visibility == VISIBLE) {
5722            if (mAttachInfo != null) {
5723                initialAwakenScrollBars();
5724            } else {
5725                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5726            }
5727        }
5728    }
5729
5730    /**
5731     * Dispatch a hint about whether this view is displayed. For instance, when
5732     * a View moves out of the screen, it might receives a display hint indicating
5733     * the view is not displayed. Applications should not <em>rely</em> on this hint
5734     * as there is no guarantee that they will receive one.
5735     *
5736     * @param hint A hint about whether or not this view is displayed:
5737     * {@link #VISIBLE} or {@link #INVISIBLE}.
5738     */
5739    public void dispatchDisplayHint(int hint) {
5740        onDisplayHint(hint);
5741    }
5742
5743    /**
5744     * Gives this view a hint about whether is displayed or not. For instance, when
5745     * a View moves out of the screen, it might receives a display hint indicating
5746     * the view is not displayed. Applications should not <em>rely</em> on this hint
5747     * as there is no guarantee that they will receive one.
5748     *
5749     * @param hint A hint about whether or not this view is displayed:
5750     * {@link #VISIBLE} or {@link #INVISIBLE}.
5751     */
5752    protected void onDisplayHint(int hint) {
5753    }
5754
5755    /**
5756     * Dispatch a window visibility change down the view hierarchy.
5757     * ViewGroups should override to route to their children.
5758     *
5759     * @param visibility The new visibility of the window.
5760     *
5761     * @see #onWindowVisibilityChanged(int)
5762     */
5763    public void dispatchWindowVisibilityChanged(int visibility) {
5764        onWindowVisibilityChanged(visibility);
5765    }
5766
5767    /**
5768     * Called when the window containing has change its visibility
5769     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5770     * that this tells you whether or not your window is being made visible
5771     * to the window manager; this does <em>not</em> tell you whether or not
5772     * your window is obscured by other windows on the screen, even if it
5773     * is itself visible.
5774     *
5775     * @param visibility The new visibility of the window.
5776     */
5777    protected void onWindowVisibilityChanged(int visibility) {
5778        if (visibility == VISIBLE) {
5779            initialAwakenScrollBars();
5780        }
5781    }
5782
5783    /**
5784     * Returns the current visibility of the window this view is attached to
5785     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5786     *
5787     * @return Returns the current visibility of the view's window.
5788     */
5789    public int getWindowVisibility() {
5790        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5791    }
5792
5793    /**
5794     * Retrieve the overall visible display size in which the window this view is
5795     * attached to has been positioned in.  This takes into account screen
5796     * decorations above the window, for both cases where the window itself
5797     * is being position inside of them or the window is being placed under
5798     * then and covered insets are used for the window to position its content
5799     * inside.  In effect, this tells you the available area where content can
5800     * be placed and remain visible to users.
5801     *
5802     * <p>This function requires an IPC back to the window manager to retrieve
5803     * the requested information, so should not be used in performance critical
5804     * code like drawing.
5805     *
5806     * @param outRect Filled in with the visible display frame.  If the view
5807     * is not attached to a window, this is simply the raw display size.
5808     */
5809    public void getWindowVisibleDisplayFrame(Rect outRect) {
5810        if (mAttachInfo != null) {
5811            try {
5812                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5813            } catch (RemoteException e) {
5814                return;
5815            }
5816            // XXX This is really broken, and probably all needs to be done
5817            // in the window manager, and we need to know more about whether
5818            // we want the area behind or in front of the IME.
5819            final Rect insets = mAttachInfo.mVisibleInsets;
5820            outRect.left += insets.left;
5821            outRect.top += insets.top;
5822            outRect.right -= insets.right;
5823            outRect.bottom -= insets.bottom;
5824            return;
5825        }
5826        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5827        d.getRectSize(outRect);
5828    }
5829
5830    /**
5831     * Dispatch a notification about a resource configuration change down
5832     * the view hierarchy.
5833     * ViewGroups should override to route to their children.
5834     *
5835     * @param newConfig The new resource configuration.
5836     *
5837     * @see #onConfigurationChanged(android.content.res.Configuration)
5838     */
5839    public void dispatchConfigurationChanged(Configuration newConfig) {
5840        onConfigurationChanged(newConfig);
5841    }
5842
5843    /**
5844     * Called when the current configuration of the resources being used
5845     * by the application have changed.  You can use this to decide when
5846     * to reload resources that can changed based on orientation and other
5847     * configuration characterstics.  You only need to use this if you are
5848     * not relying on the normal {@link android.app.Activity} mechanism of
5849     * recreating the activity instance upon a configuration change.
5850     *
5851     * @param newConfig The new resource configuration.
5852     */
5853    protected void onConfigurationChanged(Configuration newConfig) {
5854    }
5855
5856    /**
5857     * Private function to aggregate all per-view attributes in to the view
5858     * root.
5859     */
5860    void dispatchCollectViewAttributes(int visibility) {
5861        performCollectViewAttributes(visibility);
5862    }
5863
5864    void performCollectViewAttributes(int visibility) {
5865        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
5866            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
5867                mAttachInfo.mKeepScreenOn = true;
5868            }
5869            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
5870            if (mOnSystemUiVisibilityChangeListener != null) {
5871                mAttachInfo.mHasSystemUiListeners = true;
5872            }
5873        }
5874    }
5875
5876    void needGlobalAttributesUpdate(boolean force) {
5877        final AttachInfo ai = mAttachInfo;
5878        if (ai != null) {
5879            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
5880                    || ai.mHasSystemUiListeners) {
5881                ai.mRecomputeGlobalAttributes = true;
5882            }
5883        }
5884    }
5885
5886    /**
5887     * Returns whether the device is currently in touch mode.  Touch mode is entered
5888     * once the user begins interacting with the device by touch, and affects various
5889     * things like whether focus is always visible to the user.
5890     *
5891     * @return Whether the device is in touch mode.
5892     */
5893    @ViewDebug.ExportedProperty
5894    public boolean isInTouchMode() {
5895        if (mAttachInfo != null) {
5896            return mAttachInfo.mInTouchMode;
5897        } else {
5898            return ViewRootImpl.isInTouchMode();
5899        }
5900    }
5901
5902    /**
5903     * Returns the context the view is running in, through which it can
5904     * access the current theme, resources, etc.
5905     *
5906     * @return The view's Context.
5907     */
5908    @ViewDebug.CapturedViewProperty
5909    public final Context getContext() {
5910        return mContext;
5911    }
5912
5913    /**
5914     * Handle a key event before it is processed by any input method
5915     * associated with the view hierarchy.  This can be used to intercept
5916     * key events in special situations before the IME consumes them; a
5917     * typical example would be handling the BACK key to update the application's
5918     * UI instead of allowing the IME to see it and close itself.
5919     *
5920     * @param keyCode The value in event.getKeyCode().
5921     * @param event Description of the key event.
5922     * @return If you handled the event, return true. If you want to allow the
5923     *         event to be handled by the next receiver, return false.
5924     */
5925    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
5926        return false;
5927    }
5928
5929    /**
5930     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
5931     * KeyEvent.Callback.onKeyDown()}: perform press of the view
5932     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
5933     * is released, if the view is enabled and clickable.
5934     *
5935     * @param keyCode A key code that represents the button pressed, from
5936     *                {@link android.view.KeyEvent}.
5937     * @param event   The KeyEvent object that defines the button action.
5938     */
5939    public boolean onKeyDown(int keyCode, KeyEvent event) {
5940        boolean result = false;
5941
5942        switch (keyCode) {
5943            case KeyEvent.KEYCODE_DPAD_CENTER:
5944            case KeyEvent.KEYCODE_ENTER: {
5945                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5946                    return true;
5947                }
5948                // Long clickable items don't necessarily have to be clickable
5949                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
5950                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
5951                        (event.getRepeatCount() == 0)) {
5952                    setPressed(true);
5953                    checkForLongClick(0);
5954                    return true;
5955                }
5956                break;
5957            }
5958        }
5959        return result;
5960    }
5961
5962    /**
5963     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
5964     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
5965     * the event).
5966     */
5967    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
5968        return false;
5969    }
5970
5971    /**
5972     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
5973     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
5974     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
5975     * {@link KeyEvent#KEYCODE_ENTER} is released.
5976     *
5977     * @param keyCode A key code that represents the button pressed, from
5978     *                {@link android.view.KeyEvent}.
5979     * @param event   The KeyEvent object that defines the button action.
5980     */
5981    public boolean onKeyUp(int keyCode, KeyEvent event) {
5982        boolean result = false;
5983
5984        switch (keyCode) {
5985            case KeyEvent.KEYCODE_DPAD_CENTER:
5986            case KeyEvent.KEYCODE_ENTER: {
5987                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
5988                    return true;
5989                }
5990                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
5991                    setPressed(false);
5992
5993                    if (!mHasPerformedLongPress) {
5994                        // This is a tap, so remove the longpress check
5995                        removeLongPressCallback();
5996
5997                        result = performClick();
5998                    }
5999                }
6000                break;
6001            }
6002        }
6003        return result;
6004    }
6005
6006    /**
6007     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6008     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6009     * the event).
6010     *
6011     * @param keyCode     A key code that represents the button pressed, from
6012     *                    {@link android.view.KeyEvent}.
6013     * @param repeatCount The number of times the action was made.
6014     * @param event       The KeyEvent object that defines the button action.
6015     */
6016    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6017        return false;
6018    }
6019
6020    /**
6021     * Called on the focused view when a key shortcut event is not handled.
6022     * Override this method to implement local key shortcuts for the View.
6023     * Key shortcuts can also be implemented by setting the
6024     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6025     *
6026     * @param keyCode The value in event.getKeyCode().
6027     * @param event Description of the key event.
6028     * @return If you handled the event, return true. If you want to allow the
6029     *         event to be handled by the next receiver, return false.
6030     */
6031    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6032        return false;
6033    }
6034
6035    /**
6036     * Check whether the called view is a text editor, in which case it
6037     * would make sense to automatically display a soft input window for
6038     * it.  Subclasses should override this if they implement
6039     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6040     * a call on that method would return a non-null InputConnection, and
6041     * they are really a first-class editor that the user would normally
6042     * start typing on when the go into a window containing your view.
6043     *
6044     * <p>The default implementation always returns false.  This does
6045     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6046     * will not be called or the user can not otherwise perform edits on your
6047     * view; it is just a hint to the system that this is not the primary
6048     * purpose of this view.
6049     *
6050     * @return Returns true if this view is a text editor, else false.
6051     */
6052    public boolean onCheckIsTextEditor() {
6053        return false;
6054    }
6055
6056    /**
6057     * Create a new InputConnection for an InputMethod to interact
6058     * with the view.  The default implementation returns null, since it doesn't
6059     * support input methods.  You can override this to implement such support.
6060     * This is only needed for views that take focus and text input.
6061     *
6062     * <p>When implementing this, you probably also want to implement
6063     * {@link #onCheckIsTextEditor()} to indicate you will return a
6064     * non-null InputConnection.
6065     *
6066     * @param outAttrs Fill in with attribute information about the connection.
6067     */
6068    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6069        return null;
6070    }
6071
6072    /**
6073     * Called by the {@link android.view.inputmethod.InputMethodManager}
6074     * when a view who is not the current
6075     * input connection target is trying to make a call on the manager.  The
6076     * default implementation returns false; you can override this to return
6077     * true for certain views if you are performing InputConnection proxying
6078     * to them.
6079     * @param view The View that is making the InputMethodManager call.
6080     * @return Return true to allow the call, false to reject.
6081     */
6082    public boolean checkInputConnectionProxy(View view) {
6083        return false;
6084    }
6085
6086    /**
6087     * Show the context menu for this view. It is not safe to hold on to the
6088     * menu after returning from this method.
6089     *
6090     * You should normally not overload this method. Overload
6091     * {@link #onCreateContextMenu(ContextMenu)} or define an
6092     * {@link OnCreateContextMenuListener} to add items to the context menu.
6093     *
6094     * @param menu The context menu to populate
6095     */
6096    public void createContextMenu(ContextMenu menu) {
6097        ContextMenuInfo menuInfo = getContextMenuInfo();
6098
6099        // Sets the current menu info so all items added to menu will have
6100        // my extra info set.
6101        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6102
6103        onCreateContextMenu(menu);
6104        if (mOnCreateContextMenuListener != null) {
6105            mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6106        }
6107
6108        // Clear the extra information so subsequent items that aren't mine don't
6109        // have my extra info.
6110        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6111
6112        if (mParent != null) {
6113            mParent.createContextMenu(menu);
6114        }
6115    }
6116
6117    /**
6118     * Views should implement this if they have extra information to associate
6119     * with the context menu. The return result is supplied as a parameter to
6120     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6121     * callback.
6122     *
6123     * @return Extra information about the item for which the context menu
6124     *         should be shown. This information will vary across different
6125     *         subclasses of View.
6126     */
6127    protected ContextMenuInfo getContextMenuInfo() {
6128        return null;
6129    }
6130
6131    /**
6132     * Views should implement this if the view itself is going to add items to
6133     * the context menu.
6134     *
6135     * @param menu the context menu to populate
6136     */
6137    protected void onCreateContextMenu(ContextMenu menu) {
6138    }
6139
6140    /**
6141     * Implement this method to handle trackball motion events.  The
6142     * <em>relative</em> movement of the trackball since the last event
6143     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6144     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6145     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6146     * they will often be fractional values, representing the more fine-grained
6147     * movement information available from a trackball).
6148     *
6149     * @param event The motion event.
6150     * @return True if the event was handled, false otherwise.
6151     */
6152    public boolean onTrackballEvent(MotionEvent event) {
6153        return false;
6154    }
6155
6156    /**
6157     * Implement this method to handle generic motion events.
6158     * <p>
6159     * Generic motion events describe joystick movements, mouse hovers, track pad
6160     * touches, scroll wheel movements and other input events.  The
6161     * {@link MotionEvent#getSource() source} of the motion event specifies
6162     * the class of input that was received.  Implementations of this method
6163     * must examine the bits in the source before processing the event.
6164     * The following code example shows how this is done.
6165     * </p><p>
6166     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6167     * are delivered to the view under the pointer.  All other generic motion events are
6168     * delivered to the focused view.
6169     * </p>
6170     * <code>
6171     * public boolean onGenericMotionEvent(MotionEvent event) {
6172     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6173     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6174     *             // process the joystick movement...
6175     *             return true;
6176     *         }
6177     *     }
6178     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6179     *         switch (event.getAction()) {
6180     *             case MotionEvent.ACTION_HOVER_MOVE:
6181     *                 // process the mouse hover movement...
6182     *                 return true;
6183     *             case MotionEvent.ACTION_SCROLL:
6184     *                 // process the scroll wheel movement...
6185     *                 return true;
6186     *         }
6187     *     }
6188     *     return super.onGenericMotionEvent(event);
6189     * }
6190     * </code>
6191     *
6192     * @param event The generic motion event being processed.
6193     * @return True if the event was handled, false otherwise.
6194     */
6195    public boolean onGenericMotionEvent(MotionEvent event) {
6196        return false;
6197    }
6198
6199    /**
6200     * Implement this method to handle hover events.
6201     * <p>
6202     * This method is called whenever a pointer is hovering into, over, or out of the
6203     * bounds of a view and the view is not currently being touched.
6204     * Hover events are represented as pointer events with action
6205     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6206     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6207     * </p>
6208     * <ul>
6209     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6210     * when the pointer enters the bounds of the view.</li>
6211     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6212     * when the pointer has already entered the bounds of the view and has moved.</li>
6213     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6214     * when the pointer has exited the bounds of the view or when the pointer is
6215     * about to go down due to a button click, tap, or similar user action that
6216     * causes the view to be touched.</li>
6217     * </ul>
6218     * <p>
6219     * The view should implement this method to return true to indicate that it is
6220     * handling the hover event, such as by changing its drawable state.
6221     * </p><p>
6222     * The default implementation calls {@link #setHovered} to update the hovered state
6223     * of the view when a hover enter or hover exit event is received, if the view
6224     * is enabled and is clickable.  The default implementation also sends hover
6225     * accessibility events.
6226     * </p>
6227     *
6228     * @param event The motion event that describes the hover.
6229     * @return True if the view handled the hover event.
6230     *
6231     * @see #isHovered
6232     * @see #setHovered
6233     * @see #onHoverChanged
6234     */
6235    public boolean onHoverEvent(MotionEvent event) {
6236        // The root view may receive hover (or touch) events that are outside the bounds of
6237        // the window.  This code ensures that we only send accessibility events for
6238        // hovers that are actually within the bounds of the root view.
6239        final int action = event.getAction();
6240        if (!mSendingHoverAccessibilityEvents) {
6241            if ((action == MotionEvent.ACTION_HOVER_ENTER
6242                    || action == MotionEvent.ACTION_HOVER_MOVE)
6243                    && !hasHoveredChild()
6244                    && pointInView(event.getX(), event.getY())) {
6245                mSendingHoverAccessibilityEvents = true;
6246                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6247            }
6248        } else {
6249            if (action == MotionEvent.ACTION_HOVER_EXIT
6250                    || (action == MotionEvent.ACTION_HOVER_MOVE
6251                            && !pointInView(event.getX(), event.getY()))) {
6252                mSendingHoverAccessibilityEvents = false;
6253                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6254            }
6255        }
6256
6257        if (isHoverable()) {
6258            switch (action) {
6259                case MotionEvent.ACTION_HOVER_ENTER:
6260                    setHovered(true);
6261                    break;
6262                case MotionEvent.ACTION_HOVER_EXIT:
6263                    setHovered(false);
6264                    break;
6265            }
6266
6267            // Dispatch the event to onGenericMotionEvent before returning true.
6268            // This is to provide compatibility with existing applications that
6269            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6270            // break because of the new default handling for hoverable views
6271            // in onHoverEvent.
6272            // Note that onGenericMotionEvent will be called by default when
6273            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6274            dispatchGenericMotionEventInternal(event);
6275            return true;
6276        }
6277        return false;
6278    }
6279
6280    /**
6281     * Returns true if the view should handle {@link #onHoverEvent}
6282     * by calling {@link #setHovered} to change its hovered state.
6283     *
6284     * @return True if the view is hoverable.
6285     */
6286    private boolean isHoverable() {
6287        final int viewFlags = mViewFlags;
6288        //noinspection SimplifiableIfStatement
6289        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6290            return false;
6291        }
6292
6293        return (viewFlags & CLICKABLE) == CLICKABLE
6294                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6295    }
6296
6297    /**
6298     * Returns true if the view is currently hovered.
6299     *
6300     * @return True if the view is currently hovered.
6301     *
6302     * @see #setHovered
6303     * @see #onHoverChanged
6304     */
6305    @ViewDebug.ExportedProperty
6306    public boolean isHovered() {
6307        return (mPrivateFlags & HOVERED) != 0;
6308    }
6309
6310    /**
6311     * Sets whether the view is currently hovered.
6312     * <p>
6313     * Calling this method also changes the drawable state of the view.  This
6314     * enables the view to react to hover by using different drawable resources
6315     * to change its appearance.
6316     * </p><p>
6317     * The {@link #onHoverChanged} method is called when the hovered state changes.
6318     * </p>
6319     *
6320     * @param hovered True if the view is hovered.
6321     *
6322     * @see #isHovered
6323     * @see #onHoverChanged
6324     */
6325    public void setHovered(boolean hovered) {
6326        if (hovered) {
6327            if ((mPrivateFlags & HOVERED) == 0) {
6328                mPrivateFlags |= HOVERED;
6329                refreshDrawableState();
6330                onHoverChanged(true);
6331            }
6332        } else {
6333            if ((mPrivateFlags & HOVERED) != 0) {
6334                mPrivateFlags &= ~HOVERED;
6335                refreshDrawableState();
6336                onHoverChanged(false);
6337            }
6338        }
6339    }
6340
6341    /**
6342     * Implement this method to handle hover state changes.
6343     * <p>
6344     * This method is called whenever the hover state changes as a result of a
6345     * call to {@link #setHovered}.
6346     * </p>
6347     *
6348     * @param hovered The current hover state, as returned by {@link #isHovered}.
6349     *
6350     * @see #isHovered
6351     * @see #setHovered
6352     */
6353    public void onHoverChanged(boolean hovered) {
6354    }
6355
6356    /**
6357     * Implement this method to handle touch screen motion events.
6358     *
6359     * @param event The motion event.
6360     * @return True if the event was handled, false otherwise.
6361     */
6362    public boolean onTouchEvent(MotionEvent event) {
6363        final int viewFlags = mViewFlags;
6364
6365        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6366            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6367                mPrivateFlags &= ~PRESSED;
6368                refreshDrawableState();
6369            }
6370            // A disabled view that is clickable still consumes the touch
6371            // events, it just doesn't respond to them.
6372            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6373                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6374        }
6375
6376        if (mTouchDelegate != null) {
6377            if (mTouchDelegate.onTouchEvent(event)) {
6378                return true;
6379            }
6380        }
6381
6382        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6383                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6384            switch (event.getAction()) {
6385                case MotionEvent.ACTION_UP:
6386                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6387                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6388                        // take focus if we don't have it already and we should in
6389                        // touch mode.
6390                        boolean focusTaken = false;
6391                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6392                            focusTaken = requestFocus();
6393                        }
6394
6395                        if (prepressed) {
6396                            // The button is being released before we actually
6397                            // showed it as pressed.  Make it show the pressed
6398                            // state now (before scheduling the click) to ensure
6399                            // the user sees it.
6400                            mPrivateFlags |= PRESSED;
6401                            refreshDrawableState();
6402                       }
6403
6404                        if (!mHasPerformedLongPress) {
6405                            // This is a tap, so remove the longpress check
6406                            removeLongPressCallback();
6407
6408                            // Only perform take click actions if we were in the pressed state
6409                            if (!focusTaken) {
6410                                // Use a Runnable and post this rather than calling
6411                                // performClick directly. This lets other visual state
6412                                // of the view update before click actions start.
6413                                if (mPerformClick == null) {
6414                                    mPerformClick = new PerformClick();
6415                                }
6416                                if (!post(mPerformClick)) {
6417                                    performClick();
6418                                }
6419                            }
6420                        }
6421
6422                        if (mUnsetPressedState == null) {
6423                            mUnsetPressedState = new UnsetPressedState();
6424                        }
6425
6426                        if (prepressed) {
6427                            postDelayed(mUnsetPressedState,
6428                                    ViewConfiguration.getPressedStateDuration());
6429                        } else if (!post(mUnsetPressedState)) {
6430                            // If the post failed, unpress right now
6431                            mUnsetPressedState.run();
6432                        }
6433                        removeTapCallback();
6434                    }
6435                    break;
6436
6437                case MotionEvent.ACTION_DOWN:
6438                    mHasPerformedLongPress = false;
6439
6440                    if (performButtonActionOnTouchDown(event)) {
6441                        break;
6442                    }
6443
6444                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6445                    boolean isInScrollingContainer = isInScrollingContainer();
6446
6447                    // For views inside a scrolling container, delay the pressed feedback for
6448                    // a short period in case this is a scroll.
6449                    if (isInScrollingContainer) {
6450                        mPrivateFlags |= PREPRESSED;
6451                        if (mPendingCheckForTap == null) {
6452                            mPendingCheckForTap = new CheckForTap();
6453                        }
6454                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6455                    } else {
6456                        // Not inside a scrolling container, so show the feedback right away
6457                        mPrivateFlags |= PRESSED;
6458                        refreshDrawableState();
6459                        checkForLongClick(0);
6460                    }
6461                    break;
6462
6463                case MotionEvent.ACTION_CANCEL:
6464                    mPrivateFlags &= ~PRESSED;
6465                    refreshDrawableState();
6466                    removeTapCallback();
6467                    break;
6468
6469                case MotionEvent.ACTION_MOVE:
6470                    final int x = (int) event.getX();
6471                    final int y = (int) event.getY();
6472
6473                    // Be lenient about moving outside of buttons
6474                    if (!pointInView(x, y, mTouchSlop)) {
6475                        // Outside button
6476                        removeTapCallback();
6477                        if ((mPrivateFlags & PRESSED) != 0) {
6478                            // Remove any future long press/tap checks
6479                            removeLongPressCallback();
6480
6481                            // Need to switch from pressed to not pressed
6482                            mPrivateFlags &= ~PRESSED;
6483                            refreshDrawableState();
6484                        }
6485                    }
6486                    break;
6487            }
6488            return true;
6489        }
6490
6491        return false;
6492    }
6493
6494    /**
6495     * @hide
6496     */
6497    public boolean isInScrollingContainer() {
6498        ViewParent p = getParent();
6499        while (p != null && p instanceof ViewGroup) {
6500            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6501                return true;
6502            }
6503            p = p.getParent();
6504        }
6505        return false;
6506    }
6507
6508    /**
6509     * Remove the longpress detection timer.
6510     */
6511    private void removeLongPressCallback() {
6512        if (mPendingCheckForLongPress != null) {
6513          removeCallbacks(mPendingCheckForLongPress);
6514        }
6515    }
6516
6517    /**
6518     * Remove the pending click action
6519     */
6520    private void removePerformClickCallback() {
6521        if (mPerformClick != null) {
6522            removeCallbacks(mPerformClick);
6523        }
6524    }
6525
6526    /**
6527     * Remove the prepress detection timer.
6528     */
6529    private void removeUnsetPressCallback() {
6530        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6531            setPressed(false);
6532            removeCallbacks(mUnsetPressedState);
6533        }
6534    }
6535
6536    /**
6537     * Remove the tap detection timer.
6538     */
6539    private void removeTapCallback() {
6540        if (mPendingCheckForTap != null) {
6541            mPrivateFlags &= ~PREPRESSED;
6542            removeCallbacks(mPendingCheckForTap);
6543        }
6544    }
6545
6546    /**
6547     * Cancels a pending long press.  Your subclass can use this if you
6548     * want the context menu to come up if the user presses and holds
6549     * at the same place, but you don't want it to come up if they press
6550     * and then move around enough to cause scrolling.
6551     */
6552    public void cancelLongPress() {
6553        removeLongPressCallback();
6554
6555        /*
6556         * The prepressed state handled by the tap callback is a display
6557         * construct, but the tap callback will post a long press callback
6558         * less its own timeout. Remove it here.
6559         */
6560        removeTapCallback();
6561    }
6562
6563    /**
6564     * Remove the pending callback for sending a
6565     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6566     */
6567    private void removeSendViewScrolledAccessibilityEventCallback() {
6568        if (mSendViewScrolledAccessibilityEvent != null) {
6569            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6570        }
6571    }
6572
6573    /**
6574     * Sets the TouchDelegate for this View.
6575     */
6576    public void setTouchDelegate(TouchDelegate delegate) {
6577        mTouchDelegate = delegate;
6578    }
6579
6580    /**
6581     * Gets the TouchDelegate for this View.
6582     */
6583    public TouchDelegate getTouchDelegate() {
6584        return mTouchDelegate;
6585    }
6586
6587    /**
6588     * Set flags controlling behavior of this view.
6589     *
6590     * @param flags Constant indicating the value which should be set
6591     * @param mask Constant indicating the bit range that should be changed
6592     */
6593    void setFlags(int flags, int mask) {
6594        int old = mViewFlags;
6595        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6596
6597        int changed = mViewFlags ^ old;
6598        if (changed == 0) {
6599            return;
6600        }
6601        int privateFlags = mPrivateFlags;
6602
6603        /* Check if the FOCUSABLE bit has changed */
6604        if (((changed & FOCUSABLE_MASK) != 0) &&
6605                ((privateFlags & HAS_BOUNDS) !=0)) {
6606            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6607                    && ((privateFlags & FOCUSED) != 0)) {
6608                /* Give up focus if we are no longer focusable */
6609                clearFocus();
6610            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6611                    && ((privateFlags & FOCUSED) == 0)) {
6612                /*
6613                 * Tell the view system that we are now available to take focus
6614                 * if no one else already has it.
6615                 */
6616                if (mParent != null) mParent.focusableViewAvailable(this);
6617            }
6618        }
6619
6620        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6621            if ((changed & VISIBILITY_MASK) != 0) {
6622                /*
6623                 * If this view is becoming visible, invalidate it in case it changed while
6624                 * it was not visible. Marking it drawn ensures that the invalidation will
6625                 * go through.
6626                 */
6627                mPrivateFlags |= DRAWN;
6628                invalidate(true);
6629
6630                needGlobalAttributesUpdate(true);
6631
6632                // a view becoming visible is worth notifying the parent
6633                // about in case nothing has focus.  even if this specific view
6634                // isn't focusable, it may contain something that is, so let
6635                // the root view try to give this focus if nothing else does.
6636                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6637                    mParent.focusableViewAvailable(this);
6638                }
6639            }
6640        }
6641
6642        /* Check if the GONE bit has changed */
6643        if ((changed & GONE) != 0) {
6644            needGlobalAttributesUpdate(false);
6645            requestLayout();
6646
6647            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6648                if (hasFocus()) clearFocus();
6649                destroyDrawingCache();
6650                if (mParent instanceof View) {
6651                    // GONE views noop invalidation, so invalidate the parent
6652                    ((View) mParent).invalidate(true);
6653                }
6654                // Mark the view drawn to ensure that it gets invalidated properly the next
6655                // time it is visible and gets invalidated
6656                mPrivateFlags |= DRAWN;
6657            }
6658            if (mAttachInfo != null) {
6659                mAttachInfo.mViewVisibilityChanged = true;
6660            }
6661        }
6662
6663        /* Check if the VISIBLE bit has changed */
6664        if ((changed & INVISIBLE) != 0) {
6665            needGlobalAttributesUpdate(false);
6666            /*
6667             * If this view is becoming invisible, set the DRAWN flag so that
6668             * the next invalidate() will not be skipped.
6669             */
6670            mPrivateFlags |= DRAWN;
6671
6672            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6673                // root view becoming invisible shouldn't clear focus
6674                if (getRootView() != this) {
6675                    clearFocus();
6676                }
6677            }
6678            if (mAttachInfo != null) {
6679                mAttachInfo.mViewVisibilityChanged = true;
6680            }
6681        }
6682
6683        if ((changed & VISIBILITY_MASK) != 0) {
6684            if (mParent instanceof ViewGroup) {
6685                ((ViewGroup) mParent).onChildVisibilityChanged(this, (flags & VISIBILITY_MASK));
6686                ((View) mParent).invalidate(true);
6687            } else if (mParent != null) {
6688                mParent.invalidateChild(this, null);
6689            }
6690            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6691        }
6692
6693        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6694            destroyDrawingCache();
6695        }
6696
6697        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6698            destroyDrawingCache();
6699            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6700            invalidateParentCaches();
6701        }
6702
6703        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6704            destroyDrawingCache();
6705            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6706        }
6707
6708        if ((changed & DRAW_MASK) != 0) {
6709            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6710                if (mBGDrawable != null) {
6711                    mPrivateFlags &= ~SKIP_DRAW;
6712                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6713                } else {
6714                    mPrivateFlags |= SKIP_DRAW;
6715                }
6716            } else {
6717                mPrivateFlags &= ~SKIP_DRAW;
6718            }
6719            requestLayout();
6720            invalidate(true);
6721        }
6722
6723        if ((changed & KEEP_SCREEN_ON) != 0) {
6724            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6725                mParent.recomputeViewAttributes(this);
6726            }
6727        }
6728
6729        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6730            requestLayout();
6731        }
6732    }
6733
6734    /**
6735     * Change the view's z order in the tree, so it's on top of other sibling
6736     * views
6737     */
6738    public void bringToFront() {
6739        if (mParent != null) {
6740            mParent.bringChildToFront(this);
6741        }
6742    }
6743
6744    /**
6745     * This is called in response to an internal scroll in this view (i.e., the
6746     * view scrolled its own contents). This is typically as a result of
6747     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6748     * called.
6749     *
6750     * @param l Current horizontal scroll origin.
6751     * @param t Current vertical scroll origin.
6752     * @param oldl Previous horizontal scroll origin.
6753     * @param oldt Previous vertical scroll origin.
6754     */
6755    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6756        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6757            postSendViewScrolledAccessibilityEventCallback();
6758        }
6759
6760        mBackgroundSizeChanged = true;
6761
6762        final AttachInfo ai = mAttachInfo;
6763        if (ai != null) {
6764            ai.mViewScrollChanged = true;
6765        }
6766    }
6767
6768    /**
6769     * Interface definition for a callback to be invoked when the layout bounds of a view
6770     * changes due to layout processing.
6771     */
6772    public interface OnLayoutChangeListener {
6773        /**
6774         * Called when the focus state of a view has changed.
6775         *
6776         * @param v The view whose state has changed.
6777         * @param left The new value of the view's left property.
6778         * @param top The new value of the view's top property.
6779         * @param right The new value of the view's right property.
6780         * @param bottom The new value of the view's bottom property.
6781         * @param oldLeft The previous value of the view's left property.
6782         * @param oldTop The previous value of the view's top property.
6783         * @param oldRight The previous value of the view's right property.
6784         * @param oldBottom The previous value of the view's bottom property.
6785         */
6786        void onLayoutChange(View v, int left, int top, int right, int bottom,
6787            int oldLeft, int oldTop, int oldRight, int oldBottom);
6788    }
6789
6790    /**
6791     * This is called during layout when the size of this view has changed. If
6792     * you were just added to the view hierarchy, you're called with the old
6793     * values of 0.
6794     *
6795     * @param w Current width of this view.
6796     * @param h Current height of this view.
6797     * @param oldw Old width of this view.
6798     * @param oldh Old height of this view.
6799     */
6800    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6801    }
6802
6803    /**
6804     * Called by draw to draw the child views. This may be overridden
6805     * by derived classes to gain control just before its children are drawn
6806     * (but after its own view has been drawn).
6807     * @param canvas the canvas on which to draw the view
6808     */
6809    protected void dispatchDraw(Canvas canvas) {
6810    }
6811
6812    /**
6813     * Gets the parent of this view. Note that the parent is a
6814     * ViewParent and not necessarily a View.
6815     *
6816     * @return Parent of this view.
6817     */
6818    public final ViewParent getParent() {
6819        return mParent;
6820    }
6821
6822    /**
6823     * Set the horizontal scrolled position of your view. This will cause a call to
6824     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6825     * invalidated.
6826     * @param value the x position to scroll to
6827     */
6828    public void setScrollX(int value) {
6829        scrollTo(value, mScrollY);
6830    }
6831
6832    /**
6833     * Set the vertical scrolled position of your view. This will cause a call to
6834     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6835     * invalidated.
6836     * @param value the y position to scroll to
6837     */
6838    public void setScrollY(int value) {
6839        scrollTo(mScrollX, value);
6840    }
6841
6842    /**
6843     * Return the scrolled left position of this view. This is the left edge of
6844     * the displayed part of your view. You do not need to draw any pixels
6845     * farther left, since those are outside of the frame of your view on
6846     * screen.
6847     *
6848     * @return The left edge of the displayed part of your view, in pixels.
6849     */
6850    public final int getScrollX() {
6851        return mScrollX;
6852    }
6853
6854    /**
6855     * Return the scrolled top position of this view. This is the top edge of
6856     * the displayed part of your view. You do not need to draw any pixels above
6857     * it, since those are outside of the frame of your view on screen.
6858     *
6859     * @return The top edge of the displayed part of your view, in pixels.
6860     */
6861    public final int getScrollY() {
6862        return mScrollY;
6863    }
6864
6865    /**
6866     * Return the width of the your view.
6867     *
6868     * @return The width of your view, in pixels.
6869     */
6870    @ViewDebug.ExportedProperty(category = "layout")
6871    public final int getWidth() {
6872        return mRight - mLeft;
6873    }
6874
6875    /**
6876     * Return the height of your view.
6877     *
6878     * @return The height of your view, in pixels.
6879     */
6880    @ViewDebug.ExportedProperty(category = "layout")
6881    public final int getHeight() {
6882        return mBottom - mTop;
6883    }
6884
6885    /**
6886     * Return the visible drawing bounds of your view. Fills in the output
6887     * rectangle with the values from getScrollX(), getScrollY(),
6888     * getWidth(), and getHeight().
6889     *
6890     * @param outRect The (scrolled) drawing bounds of the view.
6891     */
6892    public void getDrawingRect(Rect outRect) {
6893        outRect.left = mScrollX;
6894        outRect.top = mScrollY;
6895        outRect.right = mScrollX + (mRight - mLeft);
6896        outRect.bottom = mScrollY + (mBottom - mTop);
6897    }
6898
6899    /**
6900     * Like {@link #getMeasuredWidthAndState()}, but only returns the
6901     * raw width component (that is the result is masked by
6902     * {@link #MEASURED_SIZE_MASK}).
6903     *
6904     * @return The raw measured width of this view.
6905     */
6906    public final int getMeasuredWidth() {
6907        return mMeasuredWidth & MEASURED_SIZE_MASK;
6908    }
6909
6910    /**
6911     * Return the full width measurement information for this view as computed
6912     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6913     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6914     * This should be used during measurement and layout calculations only. Use
6915     * {@link #getWidth()} to see how wide a view is after layout.
6916     *
6917     * @return The measured width of this view as a bit mask.
6918     */
6919    public final int getMeasuredWidthAndState() {
6920        return mMeasuredWidth;
6921    }
6922
6923    /**
6924     * Like {@link #getMeasuredHeightAndState()}, but only returns the
6925     * raw width component (that is the result is masked by
6926     * {@link #MEASURED_SIZE_MASK}).
6927     *
6928     * @return The raw measured height of this view.
6929     */
6930    public final int getMeasuredHeight() {
6931        return mMeasuredHeight & MEASURED_SIZE_MASK;
6932    }
6933
6934    /**
6935     * Return the full height measurement information for this view as computed
6936     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
6937     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
6938     * This should be used during measurement and layout calculations only. Use
6939     * {@link #getHeight()} to see how wide a view is after layout.
6940     *
6941     * @return The measured width of this view as a bit mask.
6942     */
6943    public final int getMeasuredHeightAndState() {
6944        return mMeasuredHeight;
6945    }
6946
6947    /**
6948     * Return only the state bits of {@link #getMeasuredWidthAndState()}
6949     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
6950     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
6951     * and the height component is at the shifted bits
6952     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
6953     */
6954    public final int getMeasuredState() {
6955        return (mMeasuredWidth&MEASURED_STATE_MASK)
6956                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
6957                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
6958    }
6959
6960    /**
6961     * The transform matrix of this view, which is calculated based on the current
6962     * roation, scale, and pivot properties.
6963     *
6964     * @see #getRotation()
6965     * @see #getScaleX()
6966     * @see #getScaleY()
6967     * @see #getPivotX()
6968     * @see #getPivotY()
6969     * @return The current transform matrix for the view
6970     */
6971    public Matrix getMatrix() {
6972        if (mTransformationInfo != null) {
6973            updateMatrix();
6974            return mTransformationInfo.mMatrix;
6975        }
6976        return Matrix.IDENTITY_MATRIX;
6977    }
6978
6979    /**
6980     * Utility function to determine if the value is far enough away from zero to be
6981     * considered non-zero.
6982     * @param value A floating point value to check for zero-ness
6983     * @return whether the passed-in value is far enough away from zero to be considered non-zero
6984     */
6985    private static boolean nonzero(float value) {
6986        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
6987    }
6988
6989    /**
6990     * Returns true if the transform matrix is the identity matrix.
6991     * Recomputes the matrix if necessary.
6992     *
6993     * @return True if the transform matrix is the identity matrix, false otherwise.
6994     */
6995    final boolean hasIdentityMatrix() {
6996        if (mTransformationInfo != null) {
6997            updateMatrix();
6998            return mTransformationInfo.mMatrixIsIdentity;
6999        }
7000        return true;
7001    }
7002
7003    void ensureTransformationInfo() {
7004        if (mTransformationInfo == null) {
7005            mTransformationInfo = new TransformationInfo();
7006        }
7007    }
7008
7009    /**
7010     * Recomputes the transform matrix if necessary.
7011     */
7012    private void updateMatrix() {
7013        final TransformationInfo info = mTransformationInfo;
7014        if (info == null) {
7015            return;
7016        }
7017        if (info.mMatrixDirty) {
7018            // transform-related properties have changed since the last time someone
7019            // asked for the matrix; recalculate it with the current values
7020
7021            // Figure out if we need to update the pivot point
7022            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7023                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7024                    info.mPrevWidth = mRight - mLeft;
7025                    info.mPrevHeight = mBottom - mTop;
7026                    info.mPivotX = info.mPrevWidth / 2f;
7027                    info.mPivotY = info.mPrevHeight / 2f;
7028                }
7029            }
7030            info.mMatrix.reset();
7031            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7032                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7033                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7034                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7035            } else {
7036                if (info.mCamera == null) {
7037                    info.mCamera = new Camera();
7038                    info.matrix3D = new Matrix();
7039                }
7040                info.mCamera.save();
7041                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7042                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7043                info.mCamera.getMatrix(info.matrix3D);
7044                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7045                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7046                        info.mPivotY + info.mTranslationY);
7047                info.mMatrix.postConcat(info.matrix3D);
7048                info.mCamera.restore();
7049            }
7050            info.mMatrixDirty = false;
7051            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7052            info.mInverseMatrixDirty = true;
7053        }
7054    }
7055
7056    /**
7057     * Utility method to retrieve the inverse of the current mMatrix property.
7058     * We cache the matrix to avoid recalculating it when transform properties
7059     * have not changed.
7060     *
7061     * @return The inverse of the current matrix of this view.
7062     */
7063    final Matrix getInverseMatrix() {
7064        final TransformationInfo info = mTransformationInfo;
7065        if (info != null) {
7066            updateMatrix();
7067            if (info.mInverseMatrixDirty) {
7068                if (info.mInverseMatrix == null) {
7069                    info.mInverseMatrix = new Matrix();
7070                }
7071                info.mMatrix.invert(info.mInverseMatrix);
7072                info.mInverseMatrixDirty = false;
7073            }
7074            return info.mInverseMatrix;
7075        }
7076        return Matrix.IDENTITY_MATRIX;
7077    }
7078
7079    /**
7080     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7081     * views are drawn) from the camera to this view. The camera's distance
7082     * affects 3D transformations, for instance rotations around the X and Y
7083     * axis. If the rotationX or rotationY properties are changed and this view is
7084     * large (more than half the size of the screen), it is recommended to always
7085     * use a camera distance that's greater than the height (X axis rotation) or
7086     * the width (Y axis rotation) of this view.</p>
7087     *
7088     * <p>The distance of the camera from the view plane can have an affect on the
7089     * perspective distortion of the view when it is rotated around the x or y axis.
7090     * For example, a large distance will result in a large viewing angle, and there
7091     * will not be much perspective distortion of the view as it rotates. A short
7092     * distance may cause much more perspective distortion upon rotation, and can
7093     * also result in some drawing artifacts if the rotated view ends up partially
7094     * behind the camera (which is why the recommendation is to use a distance at
7095     * least as far as the size of the view, if the view is to be rotated.)</p>
7096     *
7097     * <p>The distance is expressed in "depth pixels." The default distance depends
7098     * on the screen density. For instance, on a medium density display, the
7099     * default distance is 1280. On a high density display, the default distance
7100     * is 1920.</p>
7101     *
7102     * <p>If you want to specify a distance that leads to visually consistent
7103     * results across various densities, use the following formula:</p>
7104     * <pre>
7105     * float scale = context.getResources().getDisplayMetrics().density;
7106     * view.setCameraDistance(distance * scale);
7107     * </pre>
7108     *
7109     * <p>The density scale factor of a high density display is 1.5,
7110     * and 1920 = 1280 * 1.5.</p>
7111     *
7112     * @param distance The distance in "depth pixels", if negative the opposite
7113     *        value is used
7114     *
7115     * @see #setRotationX(float)
7116     * @see #setRotationY(float)
7117     */
7118    public void setCameraDistance(float distance) {
7119        invalidateParentCaches();
7120        invalidate(false);
7121
7122        ensureTransformationInfo();
7123        final float dpi = mResources.getDisplayMetrics().densityDpi;
7124        final TransformationInfo info = mTransformationInfo;
7125        if (info.mCamera == null) {
7126            info.mCamera = new Camera();
7127            info.matrix3D = new Matrix();
7128        }
7129
7130        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7131        info.mMatrixDirty = true;
7132
7133        invalidate(false);
7134    }
7135
7136    /**
7137     * The degrees that the view is rotated around the pivot point.
7138     *
7139     * @see #setRotation(float)
7140     * @see #getPivotX()
7141     * @see #getPivotY()
7142     *
7143     * @return The degrees of rotation.
7144     */
7145    public float getRotation() {
7146        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7147    }
7148
7149    /**
7150     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7151     * result in clockwise rotation.
7152     *
7153     * @param rotation The degrees of rotation.
7154     *
7155     * @see #getRotation()
7156     * @see #getPivotX()
7157     * @see #getPivotY()
7158     * @see #setRotationX(float)
7159     * @see #setRotationY(float)
7160     *
7161     * @attr ref android.R.styleable#View_rotation
7162     */
7163    public void setRotation(float rotation) {
7164        ensureTransformationInfo();
7165        final TransformationInfo info = mTransformationInfo;
7166        if (info.mRotation != rotation) {
7167            invalidateParentCaches();
7168            // Double-invalidation is necessary to capture view's old and new areas
7169            invalidate(false);
7170            info.mRotation = rotation;
7171            info.mMatrixDirty = true;
7172            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7173            invalidate(false);
7174        }
7175    }
7176
7177    /**
7178     * The degrees that the view is rotated around the vertical axis through the pivot point.
7179     *
7180     * @see #getPivotX()
7181     * @see #getPivotY()
7182     * @see #setRotationY(float)
7183     *
7184     * @return The degrees of Y rotation.
7185     */
7186    public float getRotationY() {
7187        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7188    }
7189
7190    /**
7191     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7192     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7193     * down the y axis.
7194     *
7195     * When rotating large views, it is recommended to adjust the camera distance
7196     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7197     *
7198     * @param rotationY The degrees of Y rotation.
7199     *
7200     * @see #getRotationY()
7201     * @see #getPivotX()
7202     * @see #getPivotY()
7203     * @see #setRotation(float)
7204     * @see #setRotationX(float)
7205     * @see #setCameraDistance(float)
7206     *
7207     * @attr ref android.R.styleable#View_rotationY
7208     */
7209    public void setRotationY(float rotationY) {
7210        ensureTransformationInfo();
7211        final TransformationInfo info = mTransformationInfo;
7212        if (info.mRotationY != rotationY) {
7213            invalidateParentCaches();
7214            // Double-invalidation is necessary to capture view's old and new areas
7215            invalidate(false);
7216            info.mRotationY = rotationY;
7217            info.mMatrixDirty = true;
7218            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7219            invalidate(false);
7220        }
7221    }
7222
7223    /**
7224     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7225     *
7226     * @see #getPivotX()
7227     * @see #getPivotY()
7228     * @see #setRotationX(float)
7229     *
7230     * @return The degrees of X rotation.
7231     */
7232    public float getRotationX() {
7233        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7234    }
7235
7236    /**
7237     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7238     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7239     * x axis.
7240     *
7241     * When rotating large views, it is recommended to adjust the camera distance
7242     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7243     *
7244     * @param rotationX The degrees of X rotation.
7245     *
7246     * @see #getRotationX()
7247     * @see #getPivotX()
7248     * @see #getPivotY()
7249     * @see #setRotation(float)
7250     * @see #setRotationY(float)
7251     * @see #setCameraDistance(float)
7252     *
7253     * @attr ref android.R.styleable#View_rotationX
7254     */
7255    public void setRotationX(float rotationX) {
7256        ensureTransformationInfo();
7257        final TransformationInfo info = mTransformationInfo;
7258        if (info.mRotationX != rotationX) {
7259            invalidateParentCaches();
7260            // Double-invalidation is necessary to capture view's old and new areas
7261            invalidate(false);
7262            info.mRotationX = rotationX;
7263            info.mMatrixDirty = true;
7264            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7265            invalidate(false);
7266        }
7267    }
7268
7269    /**
7270     * The amount that the view is scaled in x around the pivot point, as a proportion of
7271     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7272     *
7273     * <p>By default, this is 1.0f.
7274     *
7275     * @see #getPivotX()
7276     * @see #getPivotY()
7277     * @return The scaling factor.
7278     */
7279    public float getScaleX() {
7280        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7281    }
7282
7283    /**
7284     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7285     * the view's unscaled width. A value of 1 means that no scaling is applied.
7286     *
7287     * @param scaleX The scaling factor.
7288     * @see #getPivotX()
7289     * @see #getPivotY()
7290     *
7291     * @attr ref android.R.styleable#View_scaleX
7292     */
7293    public void setScaleX(float scaleX) {
7294        ensureTransformationInfo();
7295        final TransformationInfo info = mTransformationInfo;
7296        if (info.mScaleX != scaleX) {
7297            invalidateParentCaches();
7298            // Double-invalidation is necessary to capture view's old and new areas
7299            invalidate(false);
7300            info.mScaleX = scaleX;
7301            info.mMatrixDirty = true;
7302            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7303            invalidate(false);
7304        }
7305    }
7306
7307    /**
7308     * The amount that the view is scaled in y around the pivot point, as a proportion of
7309     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7310     *
7311     * <p>By default, this is 1.0f.
7312     *
7313     * @see #getPivotX()
7314     * @see #getPivotY()
7315     * @return The scaling factor.
7316     */
7317    public float getScaleY() {
7318        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7319    }
7320
7321    /**
7322     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7323     * the view's unscaled width. A value of 1 means that no scaling is applied.
7324     *
7325     * @param scaleY The scaling factor.
7326     * @see #getPivotX()
7327     * @see #getPivotY()
7328     *
7329     * @attr ref android.R.styleable#View_scaleY
7330     */
7331    public void setScaleY(float scaleY) {
7332        ensureTransformationInfo();
7333        final TransformationInfo info = mTransformationInfo;
7334        if (info.mScaleY != scaleY) {
7335            invalidateParentCaches();
7336            // Double-invalidation is necessary to capture view's old and new areas
7337            invalidate(false);
7338            info.mScaleY = scaleY;
7339            info.mMatrixDirty = true;
7340            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7341            invalidate(false);
7342        }
7343    }
7344
7345    /**
7346     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7347     * and {@link #setScaleX(float) scaled}.
7348     *
7349     * @see #getRotation()
7350     * @see #getScaleX()
7351     * @see #getScaleY()
7352     * @see #getPivotY()
7353     * @return The x location of the pivot point.
7354     */
7355    public float getPivotX() {
7356        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7357    }
7358
7359    /**
7360     * Sets the x location of the point around which the view is
7361     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7362     * By default, the pivot point is centered on the object.
7363     * Setting this property disables this behavior and causes the view to use only the
7364     * explicitly set pivotX and pivotY values.
7365     *
7366     * @param pivotX The x location of the pivot point.
7367     * @see #getRotation()
7368     * @see #getScaleX()
7369     * @see #getScaleY()
7370     * @see #getPivotY()
7371     *
7372     * @attr ref android.R.styleable#View_transformPivotX
7373     */
7374    public void setPivotX(float pivotX) {
7375        ensureTransformationInfo();
7376        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7377        final TransformationInfo info = mTransformationInfo;
7378        if (info.mPivotX != pivotX) {
7379            invalidateParentCaches();
7380            // Double-invalidation is necessary to capture view's old and new areas
7381            invalidate(false);
7382            info.mPivotX = pivotX;
7383            info.mMatrixDirty = true;
7384            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7385            invalidate(false);
7386        }
7387    }
7388
7389    /**
7390     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7391     * and {@link #setScaleY(float) scaled}.
7392     *
7393     * @see #getRotation()
7394     * @see #getScaleX()
7395     * @see #getScaleY()
7396     * @see #getPivotY()
7397     * @return The y location of the pivot point.
7398     */
7399    public float getPivotY() {
7400        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7401    }
7402
7403    /**
7404     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7405     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7406     * Setting this property disables this behavior and causes the view to use only the
7407     * explicitly set pivotX and pivotY values.
7408     *
7409     * @param pivotY The y location of the pivot point.
7410     * @see #getRotation()
7411     * @see #getScaleX()
7412     * @see #getScaleY()
7413     * @see #getPivotY()
7414     *
7415     * @attr ref android.R.styleable#View_transformPivotY
7416     */
7417    public void setPivotY(float pivotY) {
7418        ensureTransformationInfo();
7419        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7420        final TransformationInfo info = mTransformationInfo;
7421        if (info.mPivotY != pivotY) {
7422            invalidateParentCaches();
7423            // Double-invalidation is necessary to capture view's old and new areas
7424            invalidate(false);
7425            info.mPivotY = pivotY;
7426            info.mMatrixDirty = true;
7427            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7428            invalidate(false);
7429        }
7430    }
7431
7432    /**
7433     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7434     * completely transparent and 1 means the view is completely opaque.
7435     *
7436     * <p>By default this is 1.0f.
7437     * @return The opacity of the view.
7438     */
7439    public float getAlpha() {
7440        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7441    }
7442
7443    /**
7444     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7445     * completely transparent and 1 means the view is completely opaque.</p>
7446     *
7447     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7448     * responsible for applying the opacity itself. Otherwise, calling this method is
7449     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7450     * setting a hardware layer.</p>
7451     *
7452     * @param alpha The opacity of the view.
7453     *
7454     * @see #setLayerType(int, android.graphics.Paint)
7455     *
7456     * @attr ref android.R.styleable#View_alpha
7457     */
7458    public void setAlpha(float alpha) {
7459        ensureTransformationInfo();
7460        mTransformationInfo.mAlpha = alpha;
7461        invalidateParentCaches();
7462        if (onSetAlpha((int) (alpha * 255))) {
7463            mPrivateFlags |= ALPHA_SET;
7464            // subclass is handling alpha - don't optimize rendering cache invalidation
7465            invalidate(true);
7466        } else {
7467            mPrivateFlags &= ~ALPHA_SET;
7468            invalidate(false);
7469        }
7470    }
7471
7472    /**
7473     * Faster version of setAlpha() which performs the same steps except there are
7474     * no calls to invalidate(). The caller of this function should perform proper invalidation
7475     * on the parent and this object. The return value indicates whether the subclass handles
7476     * alpha (the return value for onSetAlpha()).
7477     *
7478     * @param alpha The new value for the alpha property
7479     * @return true if the View subclass handles alpha (the return value for onSetAlpha())
7480     */
7481    boolean setAlphaNoInvalidation(float alpha) {
7482        ensureTransformationInfo();
7483        mTransformationInfo.mAlpha = alpha;
7484        boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7485        if (subclassHandlesAlpha) {
7486            mPrivateFlags |= ALPHA_SET;
7487        } else {
7488            mPrivateFlags &= ~ALPHA_SET;
7489        }
7490        return subclassHandlesAlpha;
7491    }
7492
7493    /**
7494     * Top position of this view relative to its parent.
7495     *
7496     * @return The top of this view, in pixels.
7497     */
7498    @ViewDebug.CapturedViewProperty
7499    public final int getTop() {
7500        return mTop;
7501    }
7502
7503    /**
7504     * Sets the top position of this view relative to its parent. This method is meant to be called
7505     * by the layout system and should not generally be called otherwise, because the property
7506     * may be changed at any time by the layout.
7507     *
7508     * @param top The top of this view, in pixels.
7509     */
7510    public final void setTop(int top) {
7511        if (top != mTop) {
7512            updateMatrix();
7513            final boolean matrixIsIdentity = mTransformationInfo == null
7514                    || mTransformationInfo.mMatrixIsIdentity;
7515            if (matrixIsIdentity) {
7516                if (mAttachInfo != null) {
7517                    int minTop;
7518                    int yLoc;
7519                    if (top < mTop) {
7520                        minTop = top;
7521                        yLoc = top - mTop;
7522                    } else {
7523                        minTop = mTop;
7524                        yLoc = 0;
7525                    }
7526                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7527                }
7528            } else {
7529                // Double-invalidation is necessary to capture view's old and new areas
7530                invalidate(true);
7531            }
7532
7533            int width = mRight - mLeft;
7534            int oldHeight = mBottom - mTop;
7535
7536            mTop = top;
7537
7538            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7539
7540            if (!matrixIsIdentity) {
7541                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7542                    // A change in dimension means an auto-centered pivot point changes, too
7543                    mTransformationInfo.mMatrixDirty = true;
7544                }
7545                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7546                invalidate(true);
7547            }
7548            mBackgroundSizeChanged = true;
7549            invalidateParentIfNeeded();
7550        }
7551    }
7552
7553    /**
7554     * Bottom position of this view relative to its parent.
7555     *
7556     * @return The bottom of this view, in pixels.
7557     */
7558    @ViewDebug.CapturedViewProperty
7559    public final int getBottom() {
7560        return mBottom;
7561    }
7562
7563    /**
7564     * True if this view has changed since the last time being drawn.
7565     *
7566     * @return The dirty state of this view.
7567     */
7568    public boolean isDirty() {
7569        return (mPrivateFlags & DIRTY_MASK) != 0;
7570    }
7571
7572    /**
7573     * Sets the bottom position of this view relative to its parent. This method is meant to be
7574     * called by the layout system and should not generally be called otherwise, because the
7575     * property may be changed at any time by the layout.
7576     *
7577     * @param bottom The bottom of this view, in pixels.
7578     */
7579    public final void setBottom(int bottom) {
7580        if (bottom != mBottom) {
7581            updateMatrix();
7582            final boolean matrixIsIdentity = mTransformationInfo == null
7583                    || mTransformationInfo.mMatrixIsIdentity;
7584            if (matrixIsIdentity) {
7585                if (mAttachInfo != null) {
7586                    int maxBottom;
7587                    if (bottom < mBottom) {
7588                        maxBottom = mBottom;
7589                    } else {
7590                        maxBottom = bottom;
7591                    }
7592                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7593                }
7594            } else {
7595                // Double-invalidation is necessary to capture view's old and new areas
7596                invalidate(true);
7597            }
7598
7599            int width = mRight - mLeft;
7600            int oldHeight = mBottom - mTop;
7601
7602            mBottom = bottom;
7603
7604            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7605
7606            if (!matrixIsIdentity) {
7607                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7608                    // A change in dimension means an auto-centered pivot point changes, too
7609                    mTransformationInfo.mMatrixDirty = true;
7610                }
7611                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7612                invalidate(true);
7613            }
7614            mBackgroundSizeChanged = true;
7615            invalidateParentIfNeeded();
7616        }
7617    }
7618
7619    /**
7620     * Left position of this view relative to its parent.
7621     *
7622     * @return The left edge of this view, in pixels.
7623     */
7624    @ViewDebug.CapturedViewProperty
7625    public final int getLeft() {
7626        return mLeft;
7627    }
7628
7629    /**
7630     * Sets the left position of this view relative to its parent. This method is meant to be called
7631     * by the layout system and should not generally be called otherwise, because the property
7632     * may be changed at any time by the layout.
7633     *
7634     * @param left The bottom of this view, in pixels.
7635     */
7636    public final void setLeft(int left) {
7637        if (left != mLeft) {
7638            updateMatrix();
7639            final boolean matrixIsIdentity = mTransformationInfo == null
7640                    || mTransformationInfo.mMatrixIsIdentity;
7641            if (matrixIsIdentity) {
7642                if (mAttachInfo != null) {
7643                    int minLeft;
7644                    int xLoc;
7645                    if (left < mLeft) {
7646                        minLeft = left;
7647                        xLoc = left - mLeft;
7648                    } else {
7649                        minLeft = mLeft;
7650                        xLoc = 0;
7651                    }
7652                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7653                }
7654            } else {
7655                // Double-invalidation is necessary to capture view's old and new areas
7656                invalidate(true);
7657            }
7658
7659            int oldWidth = mRight - mLeft;
7660            int height = mBottom - mTop;
7661
7662            mLeft = left;
7663
7664            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7665
7666            if (!matrixIsIdentity) {
7667                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7668                    // A change in dimension means an auto-centered pivot point changes, too
7669                    mTransformationInfo.mMatrixDirty = true;
7670                }
7671                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7672                invalidate(true);
7673            }
7674            mBackgroundSizeChanged = true;
7675            invalidateParentIfNeeded();
7676        }
7677    }
7678
7679    /**
7680     * Right position of this view relative to its parent.
7681     *
7682     * @return The right edge of this view, in pixels.
7683     */
7684    @ViewDebug.CapturedViewProperty
7685    public final int getRight() {
7686        return mRight;
7687    }
7688
7689    /**
7690     * Sets the right position of this view relative to its parent. This method is meant to be called
7691     * by the layout system and should not generally be called otherwise, because the property
7692     * may be changed at any time by the layout.
7693     *
7694     * @param right The bottom of this view, in pixels.
7695     */
7696    public final void setRight(int right) {
7697        if (right != mRight) {
7698            updateMatrix();
7699            final boolean matrixIsIdentity = mTransformationInfo == null
7700                    || mTransformationInfo.mMatrixIsIdentity;
7701            if (matrixIsIdentity) {
7702                if (mAttachInfo != null) {
7703                    int maxRight;
7704                    if (right < mRight) {
7705                        maxRight = mRight;
7706                    } else {
7707                        maxRight = right;
7708                    }
7709                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7710                }
7711            } else {
7712                // Double-invalidation is necessary to capture view's old and new areas
7713                invalidate(true);
7714            }
7715
7716            int oldWidth = mRight - mLeft;
7717            int height = mBottom - mTop;
7718
7719            mRight = right;
7720
7721            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7722
7723            if (!matrixIsIdentity) {
7724                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7725                    // A change in dimension means an auto-centered pivot point changes, too
7726                    mTransformationInfo.mMatrixDirty = true;
7727                }
7728                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7729                invalidate(true);
7730            }
7731            mBackgroundSizeChanged = true;
7732            invalidateParentIfNeeded();
7733        }
7734    }
7735
7736    /**
7737     * The visual x position of this view, in pixels. This is equivalent to the
7738     * {@link #setTranslationX(float) translationX} property plus the current
7739     * {@link #getLeft() left} property.
7740     *
7741     * @return The visual x position of this view, in pixels.
7742     */
7743    public float getX() {
7744        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
7745    }
7746
7747    /**
7748     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7749     * {@link #setTranslationX(float) translationX} property to be the difference between
7750     * the x value passed in and the current {@link #getLeft() left} property.
7751     *
7752     * @param x The visual x position of this view, in pixels.
7753     */
7754    public void setX(float x) {
7755        setTranslationX(x - mLeft);
7756    }
7757
7758    /**
7759     * The visual y position of this view, in pixels. This is equivalent to the
7760     * {@link #setTranslationY(float) translationY} property plus the current
7761     * {@link #getTop() top} property.
7762     *
7763     * @return The visual y position of this view, in pixels.
7764     */
7765    public float getY() {
7766        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
7767    }
7768
7769    /**
7770     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7771     * {@link #setTranslationY(float) translationY} property to be the difference between
7772     * the y value passed in and the current {@link #getTop() top} property.
7773     *
7774     * @param y The visual y position of this view, in pixels.
7775     */
7776    public void setY(float y) {
7777        setTranslationY(y - mTop);
7778    }
7779
7780
7781    /**
7782     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7783     * This position is post-layout, in addition to wherever the object's
7784     * layout placed it.
7785     *
7786     * @return The horizontal position of this view relative to its left position, in pixels.
7787     */
7788    public float getTranslationX() {
7789        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
7790    }
7791
7792    /**
7793     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7794     * This effectively positions the object post-layout, in addition to wherever the object's
7795     * layout placed it.
7796     *
7797     * @param translationX The horizontal position of this view relative to its left position,
7798     * in pixels.
7799     *
7800     * @attr ref android.R.styleable#View_translationX
7801     */
7802    public void setTranslationX(float translationX) {
7803        ensureTransformationInfo();
7804        final TransformationInfo info = mTransformationInfo;
7805        if (info.mTranslationX != translationX) {
7806            invalidateParentCaches();
7807            // Double-invalidation is necessary to capture view's old and new areas
7808            invalidate(false);
7809            info.mTranslationX = translationX;
7810            info.mMatrixDirty = true;
7811            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7812            invalidate(false);
7813        }
7814    }
7815
7816    /**
7817     * The horizontal location of this view relative to its {@link #getTop() top} position.
7818     * This position is post-layout, in addition to wherever the object's
7819     * layout placed it.
7820     *
7821     * @return The vertical position of this view relative to its top position,
7822     * in pixels.
7823     */
7824    public float getTranslationY() {
7825        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
7826    }
7827
7828    /**
7829     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7830     * This effectively positions the object post-layout, in addition to wherever the object's
7831     * layout placed it.
7832     *
7833     * @param translationY The vertical position of this view relative to its top position,
7834     * in pixels.
7835     *
7836     * @attr ref android.R.styleable#View_translationY
7837     */
7838    public void setTranslationY(float translationY) {
7839        ensureTransformationInfo();
7840        final TransformationInfo info = mTransformationInfo;
7841        if (info.mTranslationY != translationY) {
7842            invalidateParentCaches();
7843            // Double-invalidation is necessary to capture view's old and new areas
7844            invalidate(false);
7845            info.mTranslationY = translationY;
7846            info.mMatrixDirty = true;
7847            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7848            invalidate(false);
7849        }
7850    }
7851
7852    /**
7853     * @hide
7854     */
7855    public void setFastTranslationX(float x) {
7856        ensureTransformationInfo();
7857        final TransformationInfo info = mTransformationInfo;
7858        info.mTranslationX = x;
7859        info.mMatrixDirty = true;
7860    }
7861
7862    /**
7863     * @hide
7864     */
7865    public void setFastTranslationY(float y) {
7866        ensureTransformationInfo();
7867        final TransformationInfo info = mTransformationInfo;
7868        info.mTranslationY = y;
7869        info.mMatrixDirty = true;
7870    }
7871
7872    /**
7873     * @hide
7874     */
7875    public void setFastX(float x) {
7876        ensureTransformationInfo();
7877        final TransformationInfo info = mTransformationInfo;
7878        info.mTranslationX = x - mLeft;
7879        info.mMatrixDirty = true;
7880    }
7881
7882    /**
7883     * @hide
7884     */
7885    public void setFastY(float y) {
7886        ensureTransformationInfo();
7887        final TransformationInfo info = mTransformationInfo;
7888        info.mTranslationY = y - mTop;
7889        info.mMatrixDirty = true;
7890    }
7891
7892    /**
7893     * @hide
7894     */
7895    public void setFastScaleX(float x) {
7896        ensureTransformationInfo();
7897        final TransformationInfo info = mTransformationInfo;
7898        info.mScaleX = x;
7899        info.mMatrixDirty = true;
7900    }
7901
7902    /**
7903     * @hide
7904     */
7905    public void setFastScaleY(float y) {
7906        ensureTransformationInfo();
7907        final TransformationInfo info = mTransformationInfo;
7908        info.mScaleY = y;
7909        info.mMatrixDirty = true;
7910    }
7911
7912    /**
7913     * @hide
7914     */
7915    public void setFastAlpha(float alpha) {
7916        ensureTransformationInfo();
7917        mTransformationInfo.mAlpha = alpha;
7918    }
7919
7920    /**
7921     * @hide
7922     */
7923    public void setFastRotationY(float y) {
7924        ensureTransformationInfo();
7925        final TransformationInfo info = mTransformationInfo;
7926        info.mRotationY = y;
7927        info.mMatrixDirty = true;
7928    }
7929
7930    /**
7931     * Hit rectangle in parent's coordinates
7932     *
7933     * @param outRect The hit rectangle of the view.
7934     */
7935    public void getHitRect(Rect outRect) {
7936        updateMatrix();
7937        final TransformationInfo info = mTransformationInfo;
7938        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
7939            outRect.set(mLeft, mTop, mRight, mBottom);
7940        } else {
7941            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
7942            tmpRect.set(-info.mPivotX, -info.mPivotY,
7943                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
7944            info.mMatrix.mapRect(tmpRect);
7945            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
7946                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
7947        }
7948    }
7949
7950    /**
7951     * Determines whether the given point, in local coordinates is inside the view.
7952     */
7953    /*package*/ final boolean pointInView(float localX, float localY) {
7954        return localX >= 0 && localX < (mRight - mLeft)
7955                && localY >= 0 && localY < (mBottom - mTop);
7956    }
7957
7958    /**
7959     * Utility method to determine whether the given point, in local coordinates,
7960     * is inside the view, where the area of the view is expanded by the slop factor.
7961     * This method is called while processing touch-move events to determine if the event
7962     * is still within the view.
7963     */
7964    private boolean pointInView(float localX, float localY, float slop) {
7965        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
7966                localY < ((mBottom - mTop) + slop);
7967    }
7968
7969    /**
7970     * When a view has focus and the user navigates away from it, the next view is searched for
7971     * starting from the rectangle filled in by this method.
7972     *
7973     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
7974     * of the view.  However, if your view maintains some idea of internal selection,
7975     * such as a cursor, or a selected row or column, you should override this method and
7976     * fill in a more specific rectangle.
7977     *
7978     * @param r The rectangle to fill in, in this view's coordinates.
7979     */
7980    public void getFocusedRect(Rect r) {
7981        getDrawingRect(r);
7982    }
7983
7984    /**
7985     * If some part of this view is not clipped by any of its parents, then
7986     * return that area in r in global (root) coordinates. To convert r to local
7987     * coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
7988     * -globalOffset.y)) If the view is completely clipped or translated out,
7989     * return false.
7990     *
7991     * @param r If true is returned, r holds the global coordinates of the
7992     *        visible portion of this view.
7993     * @param globalOffset If true is returned, globalOffset holds the dx,dy
7994     *        between this view and its root. globalOffet may be null.
7995     * @return true if r is non-empty (i.e. part of the view is visible at the
7996     *         root level.
7997     */
7998    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
7999        int width = mRight - mLeft;
8000        int height = mBottom - mTop;
8001        if (width > 0 && height > 0) {
8002            r.set(0, 0, width, height);
8003            if (globalOffset != null) {
8004                globalOffset.set(-mScrollX, -mScrollY);
8005            }
8006            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8007        }
8008        return false;
8009    }
8010
8011    public final boolean getGlobalVisibleRect(Rect r) {
8012        return getGlobalVisibleRect(r, null);
8013    }
8014
8015    public final boolean getLocalVisibleRect(Rect r) {
8016        Point offset = new Point();
8017        if (getGlobalVisibleRect(r, offset)) {
8018            r.offset(-offset.x, -offset.y); // make r local
8019            return true;
8020        }
8021        return false;
8022    }
8023
8024    /**
8025     * Offset this view's vertical location by the specified number of pixels.
8026     *
8027     * @param offset the number of pixels to offset the view by
8028     */
8029    public void offsetTopAndBottom(int offset) {
8030        if (offset != 0) {
8031            updateMatrix();
8032            final boolean matrixIsIdentity = mTransformationInfo == null
8033                    || mTransformationInfo.mMatrixIsIdentity;
8034            if (matrixIsIdentity) {
8035                final ViewParent p = mParent;
8036                if (p != null && mAttachInfo != null) {
8037                    final Rect r = mAttachInfo.mTmpInvalRect;
8038                    int minTop;
8039                    int maxBottom;
8040                    int yLoc;
8041                    if (offset < 0) {
8042                        minTop = mTop + offset;
8043                        maxBottom = mBottom;
8044                        yLoc = offset;
8045                    } else {
8046                        minTop = mTop;
8047                        maxBottom = mBottom + offset;
8048                        yLoc = 0;
8049                    }
8050                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8051                    p.invalidateChild(this, r);
8052                }
8053            } else {
8054                invalidate(false);
8055            }
8056
8057            mTop += offset;
8058            mBottom += offset;
8059
8060            if (!matrixIsIdentity) {
8061                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8062                invalidate(false);
8063            }
8064            invalidateParentIfNeeded();
8065        }
8066    }
8067
8068    /**
8069     * Offset this view's horizontal location by the specified amount of pixels.
8070     *
8071     * @param offset the numer of pixels to offset the view by
8072     */
8073    public void offsetLeftAndRight(int offset) {
8074        if (offset != 0) {
8075            updateMatrix();
8076            final boolean matrixIsIdentity = mTransformationInfo == null
8077                    || mTransformationInfo.mMatrixIsIdentity;
8078            if (matrixIsIdentity) {
8079                final ViewParent p = mParent;
8080                if (p != null && mAttachInfo != null) {
8081                    final Rect r = mAttachInfo.mTmpInvalRect;
8082                    int minLeft;
8083                    int maxRight;
8084                    if (offset < 0) {
8085                        minLeft = mLeft + offset;
8086                        maxRight = mRight;
8087                    } else {
8088                        minLeft = mLeft;
8089                        maxRight = mRight + offset;
8090                    }
8091                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8092                    p.invalidateChild(this, r);
8093                }
8094            } else {
8095                invalidate(false);
8096            }
8097
8098            mLeft += offset;
8099            mRight += offset;
8100
8101            if (!matrixIsIdentity) {
8102                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8103                invalidate(false);
8104            }
8105            invalidateParentIfNeeded();
8106        }
8107    }
8108
8109    /**
8110     * Get the LayoutParams associated with this view. All views should have
8111     * layout parameters. These supply parameters to the <i>parent</i> of this
8112     * view specifying how it should be arranged. There are many subclasses of
8113     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8114     * of ViewGroup that are responsible for arranging their children.
8115     *
8116     * This method may return null if this View is not attached to a parent
8117     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8118     * was not invoked successfully. When a View is attached to a parent
8119     * ViewGroup, this method must not return null.
8120     *
8121     * @return The LayoutParams associated with this view, or null if no
8122     *         parameters have been set yet
8123     */
8124    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8125    public ViewGroup.LayoutParams getLayoutParams() {
8126        return mLayoutParams;
8127    }
8128
8129    /**
8130     * Set the layout parameters associated with this view. These supply
8131     * parameters to the <i>parent</i> of this view specifying how it should be
8132     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8133     * correspond to the different subclasses of ViewGroup that are responsible
8134     * for arranging their children.
8135     *
8136     * @param params The layout parameters for this view, cannot be null
8137     */
8138    public void setLayoutParams(ViewGroup.LayoutParams params) {
8139        if (params == null) {
8140            throw new NullPointerException("Layout parameters cannot be null");
8141        }
8142        mLayoutParams = params;
8143        requestLayout();
8144    }
8145
8146    /**
8147     * Set the scrolled position of your view. This will cause a call to
8148     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8149     * invalidated.
8150     * @param x the x position to scroll to
8151     * @param y the y position to scroll to
8152     */
8153    public void scrollTo(int x, int y) {
8154        if (mScrollX != x || mScrollY != y) {
8155            int oldX = mScrollX;
8156            int oldY = mScrollY;
8157            mScrollX = x;
8158            mScrollY = y;
8159            invalidateParentCaches();
8160            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8161            if (!awakenScrollBars()) {
8162                invalidate(true);
8163            }
8164        }
8165    }
8166
8167    /**
8168     * Move the scrolled position of your view. This will cause a call to
8169     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8170     * invalidated.
8171     * @param x the amount of pixels to scroll by horizontally
8172     * @param y the amount of pixels to scroll by vertically
8173     */
8174    public void scrollBy(int x, int y) {
8175        scrollTo(mScrollX + x, mScrollY + y);
8176    }
8177
8178    /**
8179     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8180     * animation to fade the scrollbars out after a default delay. If a subclass
8181     * provides animated scrolling, the start delay should equal the duration
8182     * of the scrolling animation.</p>
8183     *
8184     * <p>The animation starts only if at least one of the scrollbars is
8185     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8186     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8187     * this method returns true, and false otherwise. If the animation is
8188     * started, this method calls {@link #invalidate()}; in that case the
8189     * caller should not call {@link #invalidate()}.</p>
8190     *
8191     * <p>This method should be invoked every time a subclass directly updates
8192     * the scroll parameters.</p>
8193     *
8194     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8195     * and {@link #scrollTo(int, int)}.</p>
8196     *
8197     * @return true if the animation is played, false otherwise
8198     *
8199     * @see #awakenScrollBars(int)
8200     * @see #scrollBy(int, int)
8201     * @see #scrollTo(int, int)
8202     * @see #isHorizontalScrollBarEnabled()
8203     * @see #isVerticalScrollBarEnabled()
8204     * @see #setHorizontalScrollBarEnabled(boolean)
8205     * @see #setVerticalScrollBarEnabled(boolean)
8206     */
8207    protected boolean awakenScrollBars() {
8208        return mScrollCache != null &&
8209                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8210    }
8211
8212    /**
8213     * Trigger the scrollbars to draw.
8214     * This method differs from awakenScrollBars() only in its default duration.
8215     * initialAwakenScrollBars() will show the scroll bars for longer than
8216     * usual to give the user more of a chance to notice them.
8217     *
8218     * @return true if the animation is played, false otherwise.
8219     */
8220    private boolean initialAwakenScrollBars() {
8221        return mScrollCache != null &&
8222                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8223    }
8224
8225    /**
8226     * <p>
8227     * Trigger the scrollbars to draw. When invoked this method starts an
8228     * animation to fade the scrollbars out after a fixed delay. If a subclass
8229     * provides animated scrolling, the start delay should equal the duration of
8230     * the scrolling animation.
8231     * </p>
8232     *
8233     * <p>
8234     * The animation starts only if at least one of the scrollbars is enabled,
8235     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8236     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8237     * this method returns true, and false otherwise. If the animation is
8238     * started, this method calls {@link #invalidate()}; in that case the caller
8239     * should not call {@link #invalidate()}.
8240     * </p>
8241     *
8242     * <p>
8243     * This method should be invoked everytime a subclass directly updates the
8244     * scroll parameters.
8245     * </p>
8246     *
8247     * @param startDelay the delay, in milliseconds, after which the animation
8248     *        should start; when the delay is 0, the animation starts
8249     *        immediately
8250     * @return true if the animation is played, false otherwise
8251     *
8252     * @see #scrollBy(int, int)
8253     * @see #scrollTo(int, int)
8254     * @see #isHorizontalScrollBarEnabled()
8255     * @see #isVerticalScrollBarEnabled()
8256     * @see #setHorizontalScrollBarEnabled(boolean)
8257     * @see #setVerticalScrollBarEnabled(boolean)
8258     */
8259    protected boolean awakenScrollBars(int startDelay) {
8260        return awakenScrollBars(startDelay, true);
8261    }
8262
8263    /**
8264     * <p>
8265     * Trigger the scrollbars to draw. When invoked this method starts an
8266     * animation to fade the scrollbars out after a fixed delay. If a subclass
8267     * provides animated scrolling, the start delay should equal the duration of
8268     * the scrolling animation.
8269     * </p>
8270     *
8271     * <p>
8272     * The animation starts only if at least one of the scrollbars is enabled,
8273     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8274     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8275     * this method returns true, and false otherwise. If the animation is
8276     * started, this method calls {@link #invalidate()} if the invalidate parameter
8277     * is set to true; in that case the caller
8278     * should not call {@link #invalidate()}.
8279     * </p>
8280     *
8281     * <p>
8282     * This method should be invoked everytime a subclass directly updates the
8283     * scroll parameters.
8284     * </p>
8285     *
8286     * @param startDelay the delay, in milliseconds, after which the animation
8287     *        should start; when the delay is 0, the animation starts
8288     *        immediately
8289     *
8290     * @param invalidate Wheter this method should call invalidate
8291     *
8292     * @return true if the animation is played, false otherwise
8293     *
8294     * @see #scrollBy(int, int)
8295     * @see #scrollTo(int, int)
8296     * @see #isHorizontalScrollBarEnabled()
8297     * @see #isVerticalScrollBarEnabled()
8298     * @see #setHorizontalScrollBarEnabled(boolean)
8299     * @see #setVerticalScrollBarEnabled(boolean)
8300     */
8301    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8302        final ScrollabilityCache scrollCache = mScrollCache;
8303
8304        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8305            return false;
8306        }
8307
8308        if (scrollCache.scrollBar == null) {
8309            scrollCache.scrollBar = new ScrollBarDrawable();
8310        }
8311
8312        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8313
8314            if (invalidate) {
8315                // Invalidate to show the scrollbars
8316                invalidate(true);
8317            }
8318
8319            if (scrollCache.state == ScrollabilityCache.OFF) {
8320                // FIXME: this is copied from WindowManagerService.
8321                // We should get this value from the system when it
8322                // is possible to do so.
8323                final int KEY_REPEAT_FIRST_DELAY = 750;
8324                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8325            }
8326
8327            // Tell mScrollCache when we should start fading. This may
8328            // extend the fade start time if one was already scheduled
8329            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8330            scrollCache.fadeStartTime = fadeStartTime;
8331            scrollCache.state = ScrollabilityCache.ON;
8332
8333            // Schedule our fader to run, unscheduling any old ones first
8334            if (mAttachInfo != null) {
8335                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8336                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8337            }
8338
8339            return true;
8340        }
8341
8342        return false;
8343    }
8344
8345    /**
8346     * Do not invalidate views which are not visible and which are not running an animation. They
8347     * will not get drawn and they should not set dirty flags as if they will be drawn
8348     */
8349    private boolean skipInvalidate() {
8350        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8351                (!(mParent instanceof ViewGroup) ||
8352                        !((ViewGroup) mParent).isViewTransitioning(this));
8353    }
8354    /**
8355     * Mark the the area defined by dirty as needing to be drawn. If the view is
8356     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8357     * in the future. This must be called from a UI thread. To call from a non-UI
8358     * thread, call {@link #postInvalidate()}.
8359     *
8360     * WARNING: This method is destructive to dirty.
8361     * @param dirty the rectangle representing the bounds of the dirty region
8362     */
8363    public void invalidate(Rect dirty) {
8364        if (ViewDebug.TRACE_HIERARCHY) {
8365            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8366        }
8367
8368        if (skipInvalidate()) {
8369            return;
8370        }
8371        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8372                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8373                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8374            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8375            mPrivateFlags |= INVALIDATED;
8376            mPrivateFlags |= DIRTY;
8377            final ViewParent p = mParent;
8378            final AttachInfo ai = mAttachInfo;
8379            //noinspection PointlessBooleanExpression,ConstantConditions
8380            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8381                if (p != null && ai != null && ai.mHardwareAccelerated) {
8382                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8383                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8384                    p.invalidateChild(this, null);
8385                    return;
8386                }
8387            }
8388            if (p != null && ai != null) {
8389                final int scrollX = mScrollX;
8390                final int scrollY = mScrollY;
8391                final Rect r = ai.mTmpInvalRect;
8392                r.set(dirty.left - scrollX, dirty.top - scrollY,
8393                        dirty.right - scrollX, dirty.bottom - scrollY);
8394                mParent.invalidateChild(this, r);
8395            }
8396        }
8397    }
8398
8399    /**
8400     * Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
8401     * The coordinates of the dirty rect are relative to the view.
8402     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8403     * will be called at some point in the future. This must be called from
8404     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8405     * @param l the left position of the dirty region
8406     * @param t the top position of the dirty region
8407     * @param r the right position of the dirty region
8408     * @param b the bottom position of the dirty region
8409     */
8410    public void invalidate(int l, int t, int r, int b) {
8411        if (ViewDebug.TRACE_HIERARCHY) {
8412            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8413        }
8414
8415        if (skipInvalidate()) {
8416            return;
8417        }
8418        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8419                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8420                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8421            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8422            mPrivateFlags |= INVALIDATED;
8423            mPrivateFlags |= DIRTY;
8424            final ViewParent p = mParent;
8425            final AttachInfo ai = mAttachInfo;
8426            //noinspection PointlessBooleanExpression,ConstantConditions
8427            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8428                if (p != null && ai != null && ai.mHardwareAccelerated) {
8429                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8430                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8431                    p.invalidateChild(this, null);
8432                    return;
8433                }
8434            }
8435            if (p != null && ai != null && l < r && t < b) {
8436                final int scrollX = mScrollX;
8437                final int scrollY = mScrollY;
8438                final Rect tmpr = ai.mTmpInvalRect;
8439                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8440                p.invalidateChild(this, tmpr);
8441            }
8442        }
8443    }
8444
8445    /**
8446     * Invalidate the whole view. If the view is visible,
8447     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8448     * the future. This must be called from a UI thread. To call from a non-UI thread,
8449     * call {@link #postInvalidate()}.
8450     */
8451    public void invalidate() {
8452        invalidate(true);
8453    }
8454
8455    /**
8456     * This is where the invalidate() work actually happens. A full invalidate()
8457     * causes the drawing cache to be invalidated, but this function can be called with
8458     * invalidateCache set to false to skip that invalidation step for cases that do not
8459     * need it (for example, a component that remains at the same dimensions with the same
8460     * content).
8461     *
8462     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8463     * well. This is usually true for a full invalidate, but may be set to false if the
8464     * View's contents or dimensions have not changed.
8465     */
8466    void invalidate(boolean invalidateCache) {
8467        if (ViewDebug.TRACE_HIERARCHY) {
8468            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8469        }
8470
8471        if (skipInvalidate()) {
8472            return;
8473        }
8474        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8475                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8476                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8477            mLastIsOpaque = isOpaque();
8478            mPrivateFlags &= ~DRAWN;
8479            mPrivateFlags |= DIRTY;
8480            if (invalidateCache) {
8481                mPrivateFlags |= INVALIDATED;
8482                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8483            }
8484            final AttachInfo ai = mAttachInfo;
8485            final ViewParent p = mParent;
8486            //noinspection PointlessBooleanExpression,ConstantConditions
8487            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8488                if (p != null && ai != null && ai.mHardwareAccelerated) {
8489                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8490                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8491                    p.invalidateChild(this, null);
8492                    return;
8493                }
8494            }
8495
8496            if (p != null && ai != null) {
8497                final Rect r = ai.mTmpInvalRect;
8498                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8499                // Don't call invalidate -- we don't want to internally scroll
8500                // our own bounds
8501                p.invalidateChild(this, r);
8502            }
8503        }
8504    }
8505
8506    /**
8507     * @hide
8508     */
8509    public void fastInvalidate() {
8510        if (skipInvalidate()) {
8511            return;
8512        }
8513        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8514            (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8515            (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8516            if (mParent instanceof View) {
8517                ((View) mParent).mPrivateFlags |= INVALIDATED;
8518            }
8519            mPrivateFlags &= ~DRAWN;
8520            mPrivateFlags |= DIRTY;
8521            mPrivateFlags |= INVALIDATED;
8522            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8523            if (mParent != null && mAttachInfo != null) {
8524                if (mAttachInfo.mHardwareAccelerated) {
8525                    mParent.invalidateChild(this, null);
8526                } else {
8527                    final Rect r = mAttachInfo.mTmpInvalRect;
8528                    r.set(0, 0, mRight - mLeft, mBottom - mTop);
8529                    // Don't call invalidate -- we don't want to internally scroll
8530                    // our own bounds
8531                    mParent.invalidateChild(this, r);
8532                }
8533            }
8534        }
8535    }
8536
8537    /**
8538     * Used to indicate that the parent of this view should clear its caches. This functionality
8539     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8540     * which is necessary when various parent-managed properties of the view change, such as
8541     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8542     * clears the parent caches and does not causes an invalidate event.
8543     *
8544     * @hide
8545     */
8546    protected void invalidateParentCaches() {
8547        if (mParent instanceof View) {
8548            ((View) mParent).mPrivateFlags |= INVALIDATED;
8549        }
8550    }
8551
8552    /**
8553     * Used to indicate that the parent of this view should be invalidated. This functionality
8554     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8555     * which is necessary when various parent-managed properties of the view change, such as
8556     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8557     * an invalidation event to the parent.
8558     *
8559     * @hide
8560     */
8561    protected void invalidateParentIfNeeded() {
8562        if (isHardwareAccelerated() && mParent instanceof View) {
8563            ((View) mParent).invalidate(true);
8564        }
8565    }
8566
8567    /**
8568     * Indicates whether this View is opaque. An opaque View guarantees that it will
8569     * draw all the pixels overlapping its bounds using a fully opaque color.
8570     *
8571     * Subclasses of View should override this method whenever possible to indicate
8572     * whether an instance is opaque. Opaque Views are treated in a special way by
8573     * the View hierarchy, possibly allowing it to perform optimizations during
8574     * invalidate/draw passes.
8575     *
8576     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8577     */
8578    @ViewDebug.ExportedProperty(category = "drawing")
8579    public boolean isOpaque() {
8580        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8581                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8582                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8583    }
8584
8585    /**
8586     * @hide
8587     */
8588    protected void computeOpaqueFlags() {
8589        // Opaque if:
8590        //   - Has a background
8591        //   - Background is opaque
8592        //   - Doesn't have scrollbars or scrollbars are inside overlay
8593
8594        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8595            mPrivateFlags |= OPAQUE_BACKGROUND;
8596        } else {
8597            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8598        }
8599
8600        final int flags = mViewFlags;
8601        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8602                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8603            mPrivateFlags |= OPAQUE_SCROLLBARS;
8604        } else {
8605            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8606        }
8607    }
8608
8609    /**
8610     * @hide
8611     */
8612    protected boolean hasOpaqueScrollbars() {
8613        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8614    }
8615
8616    /**
8617     * @return A handler associated with the thread running the View. This
8618     * handler can be used to pump events in the UI events queue.
8619     */
8620    public Handler getHandler() {
8621        if (mAttachInfo != null) {
8622            return mAttachInfo.mHandler;
8623        }
8624        return null;
8625    }
8626
8627    /**
8628     * <p>Causes the Runnable to be added to the message queue.
8629     * The runnable will be run on the user interface thread.</p>
8630     *
8631     * <p>This method can be invoked from outside of the UI thread
8632     * only when this View is attached to a window.</p>
8633     *
8634     * @param action The Runnable that will be executed.
8635     *
8636     * @return Returns true if the Runnable was successfully placed in to the
8637     *         message queue.  Returns false on failure, usually because the
8638     *         looper processing the message queue is exiting.
8639     */
8640    public boolean post(Runnable action) {
8641        Handler handler;
8642        AttachInfo attachInfo = mAttachInfo;
8643        if (attachInfo != null) {
8644            handler = attachInfo.mHandler;
8645        } else {
8646            // Assume that post will succeed later
8647            ViewRootImpl.getRunQueue().post(action);
8648            return true;
8649        }
8650
8651        return handler.post(action);
8652    }
8653
8654    /**
8655     * <p>Causes the Runnable to be added to the message queue, to be run
8656     * after the specified amount of time elapses.
8657     * The runnable will be run on the user interface thread.</p>
8658     *
8659     * <p>This method can be invoked from outside of the UI thread
8660     * only when this View is attached to a window.</p>
8661     *
8662     * @param action The Runnable that will be executed.
8663     * @param delayMillis The delay (in milliseconds) until the Runnable
8664     *        will be executed.
8665     *
8666     * @return true if the Runnable was successfully placed in to the
8667     *         message queue.  Returns false on failure, usually because the
8668     *         looper processing the message queue is exiting.  Note that a
8669     *         result of true does not mean the Runnable will be processed --
8670     *         if the looper is quit before the delivery time of the message
8671     *         occurs then the message will be dropped.
8672     */
8673    public boolean postDelayed(Runnable action, long delayMillis) {
8674        Handler handler;
8675        AttachInfo attachInfo = mAttachInfo;
8676        if (attachInfo != null) {
8677            handler = attachInfo.mHandler;
8678        } else {
8679            // Assume that post will succeed later
8680            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8681            return true;
8682        }
8683
8684        return handler.postDelayed(action, delayMillis);
8685    }
8686
8687    /**
8688     * <p>Removes the specified Runnable from the message queue.</p>
8689     *
8690     * <p>This method can be invoked from outside of the UI thread
8691     * only when this View is attached to a window.</p>
8692     *
8693     * @param action The Runnable to remove from the message handling queue
8694     *
8695     * @return true if this view could ask the Handler to remove the Runnable,
8696     *         false otherwise. When the returned value is true, the Runnable
8697     *         may or may not have been actually removed from the message queue
8698     *         (for instance, if the Runnable was not in the queue already.)
8699     */
8700    public boolean removeCallbacks(Runnable action) {
8701        Handler handler;
8702        AttachInfo attachInfo = mAttachInfo;
8703        if (attachInfo != null) {
8704            handler = attachInfo.mHandler;
8705        } else {
8706            // Assume that post will succeed later
8707            ViewRootImpl.getRunQueue().removeCallbacks(action);
8708            return true;
8709        }
8710
8711        handler.removeCallbacks(action);
8712        return true;
8713    }
8714
8715    /**
8716     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8717     * Use this to invalidate the View from a non-UI thread.</p>
8718     *
8719     * <p>This method can be invoked from outside of the UI thread
8720     * only when this View is attached to a window.</p>
8721     *
8722     * @see #invalidate()
8723     */
8724    public void postInvalidate() {
8725        postInvalidateDelayed(0);
8726    }
8727
8728    /**
8729     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8730     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8731     *
8732     * <p>This method can be invoked from outside of the UI thread
8733     * only when this View is attached to a window.</p>
8734     *
8735     * @param left The left coordinate of the rectangle to invalidate.
8736     * @param top The top coordinate of the rectangle to invalidate.
8737     * @param right The right coordinate of the rectangle to invalidate.
8738     * @param bottom The bottom coordinate of the rectangle to invalidate.
8739     *
8740     * @see #invalidate(int, int, int, int)
8741     * @see #invalidate(Rect)
8742     */
8743    public void postInvalidate(int left, int top, int right, int bottom) {
8744        postInvalidateDelayed(0, left, top, right, bottom);
8745    }
8746
8747    /**
8748     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8749     * loop. Waits for the specified amount of time.</p>
8750     *
8751     * <p>This method can be invoked from outside of the UI thread
8752     * only when this View is attached to a window.</p>
8753     *
8754     * @param delayMilliseconds the duration in milliseconds to delay the
8755     *         invalidation by
8756     */
8757    public void postInvalidateDelayed(long delayMilliseconds) {
8758        // We try only with the AttachInfo because there's no point in invalidating
8759        // if we are not attached to our window
8760        AttachInfo attachInfo = mAttachInfo;
8761        if (attachInfo != null) {
8762            Message msg = Message.obtain();
8763            msg.what = AttachInfo.INVALIDATE_MSG;
8764            msg.obj = this;
8765            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8766        }
8767    }
8768
8769    /**
8770     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8771     * through the event loop. Waits for the specified amount of time.</p>
8772     *
8773     * <p>This method can be invoked from outside of the UI thread
8774     * only when this View is attached to a window.</p>
8775     *
8776     * @param delayMilliseconds the duration in milliseconds to delay the
8777     *         invalidation by
8778     * @param left The left coordinate of the rectangle to invalidate.
8779     * @param top The top coordinate of the rectangle to invalidate.
8780     * @param right The right coordinate of the rectangle to invalidate.
8781     * @param bottom The bottom coordinate of the rectangle to invalidate.
8782     */
8783    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8784            int right, int bottom) {
8785
8786        // We try only with the AttachInfo because there's no point in invalidating
8787        // if we are not attached to our window
8788        AttachInfo attachInfo = mAttachInfo;
8789        if (attachInfo != null) {
8790            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8791            info.target = this;
8792            info.left = left;
8793            info.top = top;
8794            info.right = right;
8795            info.bottom = bottom;
8796
8797            final Message msg = Message.obtain();
8798            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8799            msg.obj = info;
8800            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8801        }
8802    }
8803
8804    /**
8805     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8806     * This event is sent at most once every
8807     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8808     */
8809    private void postSendViewScrolledAccessibilityEventCallback() {
8810        if (mSendViewScrolledAccessibilityEvent == null) {
8811            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8812        }
8813        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8814            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8815            postDelayed(mSendViewScrolledAccessibilityEvent,
8816                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8817        }
8818    }
8819
8820    /**
8821     * Called by a parent to request that a child update its values for mScrollX
8822     * and mScrollY if necessary. This will typically be done if the child is
8823     * animating a scroll using a {@link android.widget.Scroller Scroller}
8824     * object.
8825     */
8826    public void computeScroll() {
8827    }
8828
8829    /**
8830     * <p>Indicate whether the horizontal edges are faded when the view is
8831     * scrolled horizontally.</p>
8832     *
8833     * @return true if the horizontal edges should are faded on scroll, false
8834     *         otherwise
8835     *
8836     * @see #setHorizontalFadingEdgeEnabled(boolean)
8837     * @attr ref android.R.styleable#View_requiresFadingEdge
8838     */
8839    public boolean isHorizontalFadingEdgeEnabled() {
8840        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8841    }
8842
8843    /**
8844     * <p>Define whether the horizontal edges should be faded when this view
8845     * is scrolled horizontally.</p>
8846     *
8847     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8848     *                                    be faded when the view is scrolled
8849     *                                    horizontally
8850     *
8851     * @see #isHorizontalFadingEdgeEnabled()
8852     * @attr ref android.R.styleable#View_requiresFadingEdge
8853     */
8854    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8855        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8856            if (horizontalFadingEdgeEnabled) {
8857                initScrollCache();
8858            }
8859
8860            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8861        }
8862    }
8863
8864    /**
8865     * <p>Indicate whether the vertical edges are faded when the view is
8866     * scrolled horizontally.</p>
8867     *
8868     * @return true if the vertical edges should are faded on scroll, false
8869     *         otherwise
8870     *
8871     * @see #setVerticalFadingEdgeEnabled(boolean)
8872     * @attr ref android.R.styleable#View_requiresFadingEdge
8873     */
8874    public boolean isVerticalFadingEdgeEnabled() {
8875        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8876    }
8877
8878    /**
8879     * <p>Define whether the vertical edges should be faded when this view
8880     * is scrolled vertically.</p>
8881     *
8882     * @param verticalFadingEdgeEnabled true if the vertical edges should
8883     *                                  be faded when the view is scrolled
8884     *                                  vertically
8885     *
8886     * @see #isVerticalFadingEdgeEnabled()
8887     * @attr ref android.R.styleable#View_requiresFadingEdge
8888     */
8889    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8890        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8891            if (verticalFadingEdgeEnabled) {
8892                initScrollCache();
8893            }
8894
8895            mViewFlags ^= FADING_EDGE_VERTICAL;
8896        }
8897    }
8898
8899    /**
8900     * Returns the strength, or intensity, of the top faded edge. The strength is
8901     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8902     * returns 0.0 or 1.0 but no value in between.
8903     *
8904     * Subclasses should override this method to provide a smoother fade transition
8905     * when scrolling occurs.
8906     *
8907     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8908     */
8909    protected float getTopFadingEdgeStrength() {
8910        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8911    }
8912
8913    /**
8914     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8915     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8916     * returns 0.0 or 1.0 but no value in between.
8917     *
8918     * Subclasses should override this method to provide a smoother fade transition
8919     * when scrolling occurs.
8920     *
8921     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8922     */
8923    protected float getBottomFadingEdgeStrength() {
8924        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8925                computeVerticalScrollRange() ? 1.0f : 0.0f;
8926    }
8927
8928    /**
8929     * Returns the strength, or intensity, of the left faded edge. The strength is
8930     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8931     * returns 0.0 or 1.0 but no value in between.
8932     *
8933     * Subclasses should override this method to provide a smoother fade transition
8934     * when scrolling occurs.
8935     *
8936     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8937     */
8938    protected float getLeftFadingEdgeStrength() {
8939        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8940    }
8941
8942    /**
8943     * Returns the strength, or intensity, of the right faded edge. The strength is
8944     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8945     * returns 0.0 or 1.0 but no value in between.
8946     *
8947     * Subclasses should override this method to provide a smoother fade transition
8948     * when scrolling occurs.
8949     *
8950     * @return the intensity of the right fade as a float between 0.0f and 1.0f
8951     */
8952    protected float getRightFadingEdgeStrength() {
8953        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
8954                computeHorizontalScrollRange() ? 1.0f : 0.0f;
8955    }
8956
8957    /**
8958     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
8959     * scrollbar is not drawn by default.</p>
8960     *
8961     * @return true if the horizontal scrollbar should be painted, false
8962     *         otherwise
8963     *
8964     * @see #setHorizontalScrollBarEnabled(boolean)
8965     */
8966    public boolean isHorizontalScrollBarEnabled() {
8967        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
8968    }
8969
8970    /**
8971     * <p>Define whether the horizontal scrollbar should be drawn or not. The
8972     * scrollbar is not drawn by default.</p>
8973     *
8974     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
8975     *                                   be painted
8976     *
8977     * @see #isHorizontalScrollBarEnabled()
8978     */
8979    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
8980        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
8981            mViewFlags ^= SCROLLBARS_HORIZONTAL;
8982            computeOpaqueFlags();
8983            resolvePadding();
8984        }
8985    }
8986
8987    /**
8988     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
8989     * scrollbar is not drawn by default.</p>
8990     *
8991     * @return true if the vertical scrollbar should be painted, false
8992     *         otherwise
8993     *
8994     * @see #setVerticalScrollBarEnabled(boolean)
8995     */
8996    public boolean isVerticalScrollBarEnabled() {
8997        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
8998    }
8999
9000    /**
9001     * <p>Define whether the vertical scrollbar should be drawn or not. The
9002     * scrollbar is not drawn by default.</p>
9003     *
9004     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9005     *                                 be painted
9006     *
9007     * @see #isVerticalScrollBarEnabled()
9008     */
9009    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9010        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9011            mViewFlags ^= SCROLLBARS_VERTICAL;
9012            computeOpaqueFlags();
9013            resolvePadding();
9014        }
9015    }
9016
9017    /**
9018     * @hide
9019     */
9020    protected void recomputePadding() {
9021        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9022    }
9023
9024    /**
9025     * Define whether scrollbars will fade when the view is not scrolling.
9026     *
9027     * @param fadeScrollbars wheter to enable fading
9028     *
9029     */
9030    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9031        initScrollCache();
9032        final ScrollabilityCache scrollabilityCache = mScrollCache;
9033        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9034        if (fadeScrollbars) {
9035            scrollabilityCache.state = ScrollabilityCache.OFF;
9036        } else {
9037            scrollabilityCache.state = ScrollabilityCache.ON;
9038        }
9039    }
9040
9041    /**
9042     *
9043     * Returns true if scrollbars will fade when this view is not scrolling
9044     *
9045     * @return true if scrollbar fading is enabled
9046     */
9047    public boolean isScrollbarFadingEnabled() {
9048        return mScrollCache != null && mScrollCache.fadeScrollBars;
9049    }
9050
9051    /**
9052     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9053     * inset. When inset, they add to the padding of the view. And the scrollbars
9054     * can be drawn inside the padding area or on the edge of the view. For example,
9055     * if a view has a background drawable and you want to draw the scrollbars
9056     * inside the padding specified by the drawable, you can use
9057     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9058     * appear at the edge of the view, ignoring the padding, then you can use
9059     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9060     * @param style the style of the scrollbars. Should be one of
9061     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9062     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9063     * @see #SCROLLBARS_INSIDE_OVERLAY
9064     * @see #SCROLLBARS_INSIDE_INSET
9065     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9066     * @see #SCROLLBARS_OUTSIDE_INSET
9067     */
9068    public void setScrollBarStyle(int style) {
9069        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9070            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9071            computeOpaqueFlags();
9072            resolvePadding();
9073        }
9074    }
9075
9076    /**
9077     * <p>Returns the current scrollbar style.</p>
9078     * @return the current scrollbar style
9079     * @see #SCROLLBARS_INSIDE_OVERLAY
9080     * @see #SCROLLBARS_INSIDE_INSET
9081     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9082     * @see #SCROLLBARS_OUTSIDE_INSET
9083     */
9084    @ViewDebug.ExportedProperty(mapping = {
9085            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9086            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9087            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9088            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9089    })
9090    public int getScrollBarStyle() {
9091        return mViewFlags & SCROLLBARS_STYLE_MASK;
9092    }
9093
9094    /**
9095     * <p>Compute the horizontal range that the horizontal scrollbar
9096     * represents.</p>
9097     *
9098     * <p>The range is expressed in arbitrary units that must be the same as the
9099     * units used by {@link #computeHorizontalScrollExtent()} and
9100     * {@link #computeHorizontalScrollOffset()}.</p>
9101     *
9102     * <p>The default range is the drawing width of this view.</p>
9103     *
9104     * @return the total horizontal range represented by the horizontal
9105     *         scrollbar
9106     *
9107     * @see #computeHorizontalScrollExtent()
9108     * @see #computeHorizontalScrollOffset()
9109     * @see android.widget.ScrollBarDrawable
9110     */
9111    protected int computeHorizontalScrollRange() {
9112        return getWidth();
9113    }
9114
9115    /**
9116     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9117     * within the horizontal range. This value is used to compute the position
9118     * of the thumb within the scrollbar's track.</p>
9119     *
9120     * <p>The range is expressed in arbitrary units that must be the same as the
9121     * units used by {@link #computeHorizontalScrollRange()} and
9122     * {@link #computeHorizontalScrollExtent()}.</p>
9123     *
9124     * <p>The default offset is the scroll offset of this view.</p>
9125     *
9126     * @return the horizontal offset of the scrollbar's thumb
9127     *
9128     * @see #computeHorizontalScrollRange()
9129     * @see #computeHorizontalScrollExtent()
9130     * @see android.widget.ScrollBarDrawable
9131     */
9132    protected int computeHorizontalScrollOffset() {
9133        return mScrollX;
9134    }
9135
9136    /**
9137     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9138     * within the horizontal range. This value is used to compute the length
9139     * of the thumb within the scrollbar's track.</p>
9140     *
9141     * <p>The range is expressed in arbitrary units that must be the same as the
9142     * units used by {@link #computeHorizontalScrollRange()} and
9143     * {@link #computeHorizontalScrollOffset()}.</p>
9144     *
9145     * <p>The default extent is the drawing width of this view.</p>
9146     *
9147     * @return the horizontal extent of the scrollbar's thumb
9148     *
9149     * @see #computeHorizontalScrollRange()
9150     * @see #computeHorizontalScrollOffset()
9151     * @see android.widget.ScrollBarDrawable
9152     */
9153    protected int computeHorizontalScrollExtent() {
9154        return getWidth();
9155    }
9156
9157    /**
9158     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9159     *
9160     * <p>The range is expressed in arbitrary units that must be the same as the
9161     * units used by {@link #computeVerticalScrollExtent()} and
9162     * {@link #computeVerticalScrollOffset()}.</p>
9163     *
9164     * @return the total vertical range represented by the vertical scrollbar
9165     *
9166     * <p>The default range is the drawing height of this view.</p>
9167     *
9168     * @see #computeVerticalScrollExtent()
9169     * @see #computeVerticalScrollOffset()
9170     * @see android.widget.ScrollBarDrawable
9171     */
9172    protected int computeVerticalScrollRange() {
9173        return getHeight();
9174    }
9175
9176    /**
9177     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9178     * within the horizontal range. This value is used to compute the position
9179     * of the thumb within the scrollbar's track.</p>
9180     *
9181     * <p>The range is expressed in arbitrary units that must be the same as the
9182     * units used by {@link #computeVerticalScrollRange()} and
9183     * {@link #computeVerticalScrollExtent()}.</p>
9184     *
9185     * <p>The default offset is the scroll offset of this view.</p>
9186     *
9187     * @return the vertical offset of the scrollbar's thumb
9188     *
9189     * @see #computeVerticalScrollRange()
9190     * @see #computeVerticalScrollExtent()
9191     * @see android.widget.ScrollBarDrawable
9192     */
9193    protected int computeVerticalScrollOffset() {
9194        return mScrollY;
9195    }
9196
9197    /**
9198     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9199     * within the vertical range. This value is used to compute the length
9200     * of the thumb within the scrollbar's track.</p>
9201     *
9202     * <p>The range is expressed in arbitrary units that must be the same as the
9203     * units used by {@link #computeVerticalScrollRange()} and
9204     * {@link #computeVerticalScrollOffset()}.</p>
9205     *
9206     * <p>The default extent is the drawing height of this view.</p>
9207     *
9208     * @return the vertical extent of the scrollbar's thumb
9209     *
9210     * @see #computeVerticalScrollRange()
9211     * @see #computeVerticalScrollOffset()
9212     * @see android.widget.ScrollBarDrawable
9213     */
9214    protected int computeVerticalScrollExtent() {
9215        return getHeight();
9216    }
9217
9218    /**
9219     * Check if this view can be scrolled horizontally in a certain direction.
9220     *
9221     * @param direction Negative to check scrolling left, positive to check scrolling right.
9222     * @return true if this view can be scrolled in the specified direction, false otherwise.
9223     */
9224    public boolean canScrollHorizontally(int direction) {
9225        final int offset = computeHorizontalScrollOffset();
9226        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9227        if (range == 0) return false;
9228        if (direction < 0) {
9229            return offset > 0;
9230        } else {
9231            return offset < range - 1;
9232        }
9233    }
9234
9235    /**
9236     * Check if this view can be scrolled vertically in a certain direction.
9237     *
9238     * @param direction Negative to check scrolling up, positive to check scrolling down.
9239     * @return true if this view can be scrolled in the specified direction, false otherwise.
9240     */
9241    public boolean canScrollVertically(int direction) {
9242        final int offset = computeVerticalScrollOffset();
9243        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9244        if (range == 0) return false;
9245        if (direction < 0) {
9246            return offset > 0;
9247        } else {
9248            return offset < range - 1;
9249        }
9250    }
9251
9252    /**
9253     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9254     * scrollbars are painted only if they have been awakened first.</p>
9255     *
9256     * @param canvas the canvas on which to draw the scrollbars
9257     *
9258     * @see #awakenScrollBars(int)
9259     */
9260    protected final void onDrawScrollBars(Canvas canvas) {
9261        // scrollbars are drawn only when the animation is running
9262        final ScrollabilityCache cache = mScrollCache;
9263        if (cache != null) {
9264
9265            int state = cache.state;
9266
9267            if (state == ScrollabilityCache.OFF) {
9268                return;
9269            }
9270
9271            boolean invalidate = false;
9272
9273            if (state == ScrollabilityCache.FADING) {
9274                // We're fading -- get our fade interpolation
9275                if (cache.interpolatorValues == null) {
9276                    cache.interpolatorValues = new float[1];
9277                }
9278
9279                float[] values = cache.interpolatorValues;
9280
9281                // Stops the animation if we're done
9282                if (cache.scrollBarInterpolator.timeToValues(values) ==
9283                        Interpolator.Result.FREEZE_END) {
9284                    cache.state = ScrollabilityCache.OFF;
9285                } else {
9286                    cache.scrollBar.setAlpha(Math.round(values[0]));
9287                }
9288
9289                // This will make the scroll bars inval themselves after
9290                // drawing. We only want this when we're fading so that
9291                // we prevent excessive redraws
9292                invalidate = true;
9293            } else {
9294                // We're just on -- but we may have been fading before so
9295                // reset alpha
9296                cache.scrollBar.setAlpha(255);
9297            }
9298
9299
9300            final int viewFlags = mViewFlags;
9301
9302            final boolean drawHorizontalScrollBar =
9303                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9304            final boolean drawVerticalScrollBar =
9305                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9306                && !isVerticalScrollBarHidden();
9307
9308            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9309                final int width = mRight - mLeft;
9310                final int height = mBottom - mTop;
9311
9312                final ScrollBarDrawable scrollBar = cache.scrollBar;
9313
9314                final int scrollX = mScrollX;
9315                final int scrollY = mScrollY;
9316                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9317
9318                int left, top, right, bottom;
9319
9320                if (drawHorizontalScrollBar) {
9321                    int size = scrollBar.getSize(false);
9322                    if (size <= 0) {
9323                        size = cache.scrollBarSize;
9324                    }
9325
9326                    scrollBar.setParameters(computeHorizontalScrollRange(),
9327                                            computeHorizontalScrollOffset(),
9328                                            computeHorizontalScrollExtent(), false);
9329                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9330                            getVerticalScrollbarWidth() : 0;
9331                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9332                    left = scrollX + (mPaddingLeft & inside);
9333                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9334                    bottom = top + size;
9335                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9336                    if (invalidate) {
9337                        invalidate(left, top, right, bottom);
9338                    }
9339                }
9340
9341                if (drawVerticalScrollBar) {
9342                    int size = scrollBar.getSize(true);
9343                    if (size <= 0) {
9344                        size = cache.scrollBarSize;
9345                    }
9346
9347                    scrollBar.setParameters(computeVerticalScrollRange(),
9348                                            computeVerticalScrollOffset(),
9349                                            computeVerticalScrollExtent(), true);
9350                    switch (mVerticalScrollbarPosition) {
9351                        default:
9352                        case SCROLLBAR_POSITION_DEFAULT:
9353                        case SCROLLBAR_POSITION_RIGHT:
9354                            left = scrollX + width - size - (mUserPaddingRight & inside);
9355                            break;
9356                        case SCROLLBAR_POSITION_LEFT:
9357                            left = scrollX + (mUserPaddingLeft & inside);
9358                            break;
9359                    }
9360                    top = scrollY + (mPaddingTop & inside);
9361                    right = left + size;
9362                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9363                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9364                    if (invalidate) {
9365                        invalidate(left, top, right, bottom);
9366                    }
9367                }
9368            }
9369        }
9370    }
9371
9372    /**
9373     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9374     * FastScroller is visible.
9375     * @return whether to temporarily hide the vertical scrollbar
9376     * @hide
9377     */
9378    protected boolean isVerticalScrollBarHidden() {
9379        return false;
9380    }
9381
9382    /**
9383     * <p>Draw the horizontal scrollbar if
9384     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9385     *
9386     * @param canvas the canvas on which to draw the scrollbar
9387     * @param scrollBar the scrollbar's drawable
9388     *
9389     * @see #isHorizontalScrollBarEnabled()
9390     * @see #computeHorizontalScrollRange()
9391     * @see #computeHorizontalScrollExtent()
9392     * @see #computeHorizontalScrollOffset()
9393     * @see android.widget.ScrollBarDrawable
9394     * @hide
9395     */
9396    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9397            int l, int t, int r, int b) {
9398        scrollBar.setBounds(l, t, r, b);
9399        scrollBar.draw(canvas);
9400    }
9401
9402    /**
9403     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9404     * returns true.</p>
9405     *
9406     * @param canvas the canvas on which to draw the scrollbar
9407     * @param scrollBar the scrollbar's drawable
9408     *
9409     * @see #isVerticalScrollBarEnabled()
9410     * @see #computeVerticalScrollRange()
9411     * @see #computeVerticalScrollExtent()
9412     * @see #computeVerticalScrollOffset()
9413     * @see android.widget.ScrollBarDrawable
9414     * @hide
9415     */
9416    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9417            int l, int t, int r, int b) {
9418        scrollBar.setBounds(l, t, r, b);
9419        scrollBar.draw(canvas);
9420    }
9421
9422    /**
9423     * Implement this to do your drawing.
9424     *
9425     * @param canvas the canvas on which the background will be drawn
9426     */
9427    protected void onDraw(Canvas canvas) {
9428    }
9429
9430    /*
9431     * Caller is responsible for calling requestLayout if necessary.
9432     * (This allows addViewInLayout to not request a new layout.)
9433     */
9434    void assignParent(ViewParent parent) {
9435        if (mParent == null) {
9436            mParent = parent;
9437        } else if (parent == null) {
9438            mParent = null;
9439        } else {
9440            throw new RuntimeException("view " + this + " being added, but"
9441                    + " it already has a parent");
9442        }
9443    }
9444
9445    /**
9446     * This is called when the view is attached to a window.  At this point it
9447     * has a Surface and will start drawing.  Note that this function is
9448     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9449     * however it may be called any time before the first onDraw -- including
9450     * before or after {@link #onMeasure(int, int)}.
9451     *
9452     * @see #onDetachedFromWindow()
9453     */
9454    protected void onAttachedToWindow() {
9455        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9456            mParent.requestTransparentRegion(this);
9457        }
9458        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9459            initialAwakenScrollBars();
9460            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9461        }
9462        jumpDrawablesToCurrentState();
9463        // Order is important here: LayoutDirection MUST be resolved before Padding
9464        // and TextDirection
9465        resolveLayoutDirectionIfNeeded();
9466        resolvePadding();
9467        resolveTextDirection();
9468        if (isFocused()) {
9469            InputMethodManager imm = InputMethodManager.peekInstance();
9470            imm.focusIn(this);
9471        }
9472    }
9473
9474    /**
9475     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9476     * that the parent directionality can and will be resolved before its children.
9477     */
9478    private void resolveLayoutDirectionIfNeeded() {
9479        // Do not resolve if it is not needed
9480        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9481
9482        // Clear any previous layout direction resolution
9483        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9484
9485        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9486        // TextDirectionHeuristic
9487        resetResolvedTextDirection();
9488
9489        // Set resolved depending on layout direction
9490        switch (getLayoutDirection()) {
9491            case LAYOUT_DIRECTION_INHERIT:
9492                // We cannot do the resolution if there is no parent
9493                if (mParent == null) return;
9494
9495                // If this is root view, no need to look at parent's layout dir.
9496                if (mParent instanceof ViewGroup) {
9497                    ViewGroup viewGroup = ((ViewGroup) mParent);
9498
9499                    // Check if the parent view group can resolve
9500                    if (! viewGroup.canResolveLayoutDirection()) {
9501                        return;
9502                    }
9503                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9504                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9505                    }
9506                }
9507                break;
9508            case LAYOUT_DIRECTION_RTL:
9509                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9510                break;
9511            case LAYOUT_DIRECTION_LOCALE:
9512                if(isLayoutDirectionRtl(Locale.getDefault())) {
9513                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9514                }
9515                break;
9516            default:
9517                // Nothing to do, LTR by default
9518        }
9519
9520        // Set to resolved
9521        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9522    }
9523
9524    /**
9525     * @hide
9526     */
9527    protected void resolvePadding() {
9528        // If the user specified the absolute padding (either with android:padding or
9529        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9530        // use the default padding or the padding from the background drawable
9531        // (stored at this point in mPadding*)
9532        switch (getResolvedLayoutDirection()) {
9533            case LAYOUT_DIRECTION_RTL:
9534                // Start user padding override Right user padding. Otherwise, if Right user
9535                // padding is not defined, use the default Right padding. If Right user padding
9536                // is defined, just use it.
9537                if (mUserPaddingStart >= 0) {
9538                    mUserPaddingRight = mUserPaddingStart;
9539                } else if (mUserPaddingRight < 0) {
9540                    mUserPaddingRight = mPaddingRight;
9541                }
9542                if (mUserPaddingEnd >= 0) {
9543                    mUserPaddingLeft = mUserPaddingEnd;
9544                } else if (mUserPaddingLeft < 0) {
9545                    mUserPaddingLeft = mPaddingLeft;
9546                }
9547                break;
9548            case LAYOUT_DIRECTION_LTR:
9549            default:
9550                // Start user padding override Left user padding. Otherwise, if Left user
9551                // padding is not defined, use the default left padding. If Left user padding
9552                // is defined, just use it.
9553                if (mUserPaddingStart >= 0) {
9554                    mUserPaddingLeft = mUserPaddingStart;
9555                } else if (mUserPaddingLeft < 0) {
9556                    mUserPaddingLeft = mPaddingLeft;
9557                }
9558                if (mUserPaddingEnd >= 0) {
9559                    mUserPaddingRight = mUserPaddingEnd;
9560                } else if (mUserPaddingRight < 0) {
9561                    mUserPaddingRight = mPaddingRight;
9562                }
9563        }
9564
9565        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9566
9567        recomputePadding();
9568    }
9569
9570    /**
9571     * Return true if layout direction resolution can be done
9572     *
9573     * @hide
9574     */
9575    protected boolean canResolveLayoutDirection() {
9576        switch (getLayoutDirection()) {
9577            case LAYOUT_DIRECTION_INHERIT:
9578                return (mParent != null);
9579            default:
9580                return true;
9581        }
9582    }
9583
9584    /**
9585     * Reset the resolved layout direction.
9586     *
9587     * Subclasses need to override this method to clear cached information that depends on the
9588     * resolved layout direction, or to inform child views that inherit their layout direction.
9589     * Overrides must also call the superclass implementation at the start of their implementation.
9590     *
9591     * @hide
9592     */
9593    protected void resetResolvedLayoutDirection() {
9594        // Reset the current View resolution
9595        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9596    }
9597
9598    /**
9599     * Check if a Locale is corresponding to a RTL script.
9600     *
9601     * @param locale Locale to check
9602     * @return true if a Locale is corresponding to a RTL script.
9603     *
9604     * @hide
9605     */
9606    protected static boolean isLayoutDirectionRtl(Locale locale) {
9607        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9608                LocaleUtil.getLayoutDirectionFromLocale(locale));
9609    }
9610
9611    /**
9612     * This is called when the view is detached from a window.  At this point it
9613     * no longer has a surface for drawing.
9614     *
9615     * @see #onAttachedToWindow()
9616     */
9617    protected void onDetachedFromWindow() {
9618        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9619
9620        removeUnsetPressCallback();
9621        removeLongPressCallback();
9622        removePerformClickCallback();
9623        removeSendViewScrolledAccessibilityEventCallback();
9624
9625        destroyDrawingCache();
9626
9627        destroyLayer();
9628
9629        if (mDisplayList != null) {
9630            mDisplayList.invalidate();
9631        }
9632
9633        if (mAttachInfo != null) {
9634            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9635        }
9636
9637        mCurrentAnimation = null;
9638
9639        resetResolvedLayoutDirection();
9640        resetResolvedTextDirection();
9641    }
9642
9643    /**
9644     * @return The number of times this view has been attached to a window
9645     */
9646    protected int getWindowAttachCount() {
9647        return mWindowAttachCount;
9648    }
9649
9650    /**
9651     * Retrieve a unique token identifying the window this view is attached to.
9652     * @return Return the window's token for use in
9653     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9654     */
9655    public IBinder getWindowToken() {
9656        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9657    }
9658
9659    /**
9660     * Retrieve a unique token identifying the top-level "real" window of
9661     * the window that this view is attached to.  That is, this is like
9662     * {@link #getWindowToken}, except if the window this view in is a panel
9663     * window (attached to another containing window), then the token of
9664     * the containing window is returned instead.
9665     *
9666     * @return Returns the associated window token, either
9667     * {@link #getWindowToken()} or the containing window's token.
9668     */
9669    public IBinder getApplicationWindowToken() {
9670        AttachInfo ai = mAttachInfo;
9671        if (ai != null) {
9672            IBinder appWindowToken = ai.mPanelParentWindowToken;
9673            if (appWindowToken == null) {
9674                appWindowToken = ai.mWindowToken;
9675            }
9676            return appWindowToken;
9677        }
9678        return null;
9679    }
9680
9681    /**
9682     * Retrieve private session object this view hierarchy is using to
9683     * communicate with the window manager.
9684     * @return the session object to communicate with the window manager
9685     */
9686    /*package*/ IWindowSession getWindowSession() {
9687        return mAttachInfo != null ? mAttachInfo.mSession : null;
9688    }
9689
9690    /**
9691     * @param info the {@link android.view.View.AttachInfo} to associated with
9692     *        this view
9693     */
9694    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9695        //System.out.println("Attached! " + this);
9696        mAttachInfo = info;
9697        mWindowAttachCount++;
9698        // We will need to evaluate the drawable state at least once.
9699        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9700        if (mFloatingTreeObserver != null) {
9701            info.mTreeObserver.merge(mFloatingTreeObserver);
9702            mFloatingTreeObserver = null;
9703        }
9704        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9705            mAttachInfo.mScrollContainers.add(this);
9706            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9707        }
9708        performCollectViewAttributes(visibility);
9709        onAttachedToWindow();
9710
9711        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9712                mOnAttachStateChangeListeners;
9713        if (listeners != null && listeners.size() > 0) {
9714            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9715            // perform the dispatching. The iterator is a safe guard against listeners that
9716            // could mutate the list by calling the various add/remove methods. This prevents
9717            // the array from being modified while we iterate it.
9718            for (OnAttachStateChangeListener listener : listeners) {
9719                listener.onViewAttachedToWindow(this);
9720            }
9721        }
9722
9723        int vis = info.mWindowVisibility;
9724        if (vis != GONE) {
9725            onWindowVisibilityChanged(vis);
9726        }
9727        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9728            // If nobody has evaluated the drawable state yet, then do it now.
9729            refreshDrawableState();
9730        }
9731    }
9732
9733    void dispatchDetachedFromWindow() {
9734        AttachInfo info = mAttachInfo;
9735        if (info != null) {
9736            int vis = info.mWindowVisibility;
9737            if (vis != GONE) {
9738                onWindowVisibilityChanged(GONE);
9739            }
9740        }
9741
9742        onDetachedFromWindow();
9743
9744        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9745                mOnAttachStateChangeListeners;
9746        if (listeners != null && listeners.size() > 0) {
9747            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9748            // perform the dispatching. The iterator is a safe guard against listeners that
9749            // could mutate the list by calling the various add/remove methods. This prevents
9750            // the array from being modified while we iterate it.
9751            for (OnAttachStateChangeListener listener : listeners) {
9752                listener.onViewDetachedFromWindow(this);
9753            }
9754        }
9755
9756        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9757            mAttachInfo.mScrollContainers.remove(this);
9758            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9759        }
9760
9761        mAttachInfo = null;
9762    }
9763
9764    /**
9765     * Store this view hierarchy's frozen state into the given container.
9766     *
9767     * @param container The SparseArray in which to save the view's state.
9768     *
9769     * @see #restoreHierarchyState(android.util.SparseArray)
9770     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9771     * @see #onSaveInstanceState()
9772     */
9773    public void saveHierarchyState(SparseArray<Parcelable> container) {
9774        dispatchSaveInstanceState(container);
9775    }
9776
9777    /**
9778     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9779     * this view and its children. May be overridden to modify how freezing happens to a
9780     * view's children; for example, some views may want to not store state for their children.
9781     *
9782     * @param container The SparseArray in which to save the view's state.
9783     *
9784     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9785     * @see #saveHierarchyState(android.util.SparseArray)
9786     * @see #onSaveInstanceState()
9787     */
9788    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9789        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9790            mPrivateFlags &= ~SAVE_STATE_CALLED;
9791            Parcelable state = onSaveInstanceState();
9792            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9793                throw new IllegalStateException(
9794                        "Derived class did not call super.onSaveInstanceState()");
9795            }
9796            if (state != null) {
9797                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9798                // + ": " + state);
9799                container.put(mID, state);
9800            }
9801        }
9802    }
9803
9804    /**
9805     * Hook allowing a view to generate a representation of its internal state
9806     * that can later be used to create a new instance with that same state.
9807     * This state should only contain information that is not persistent or can
9808     * not be reconstructed later. For example, you will never store your
9809     * current position on screen because that will be computed again when a
9810     * new instance of the view is placed in its view hierarchy.
9811     * <p>
9812     * Some examples of things you may store here: the current cursor position
9813     * in a text view (but usually not the text itself since that is stored in a
9814     * content provider or other persistent storage), the currently selected
9815     * item in a list view.
9816     *
9817     * @return Returns a Parcelable object containing the view's current dynamic
9818     *         state, or null if there is nothing interesting to save. The
9819     *         default implementation returns null.
9820     * @see #onRestoreInstanceState(android.os.Parcelable)
9821     * @see #saveHierarchyState(android.util.SparseArray)
9822     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9823     * @see #setSaveEnabled(boolean)
9824     */
9825    protected Parcelable onSaveInstanceState() {
9826        mPrivateFlags |= SAVE_STATE_CALLED;
9827        return BaseSavedState.EMPTY_STATE;
9828    }
9829
9830    /**
9831     * Restore this view hierarchy's frozen state from the given container.
9832     *
9833     * @param container The SparseArray which holds previously frozen states.
9834     *
9835     * @see #saveHierarchyState(android.util.SparseArray)
9836     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9837     * @see #onRestoreInstanceState(android.os.Parcelable)
9838     */
9839    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9840        dispatchRestoreInstanceState(container);
9841    }
9842
9843    /**
9844     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9845     * state for this view and its children. May be overridden to modify how restoring
9846     * happens to a view's children; for example, some views may want to not store state
9847     * for their children.
9848     *
9849     * @param container The SparseArray which holds previously saved state.
9850     *
9851     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9852     * @see #restoreHierarchyState(android.util.SparseArray)
9853     * @see #onRestoreInstanceState(android.os.Parcelable)
9854     */
9855    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9856        if (mID != NO_ID) {
9857            Parcelable state = container.get(mID);
9858            if (state != null) {
9859                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9860                // + ": " + state);
9861                mPrivateFlags &= ~SAVE_STATE_CALLED;
9862                onRestoreInstanceState(state);
9863                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9864                    throw new IllegalStateException(
9865                            "Derived class did not call super.onRestoreInstanceState()");
9866                }
9867            }
9868        }
9869    }
9870
9871    /**
9872     * Hook allowing a view to re-apply a representation of its internal state that had previously
9873     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9874     * null state.
9875     *
9876     * @param state The frozen state that had previously been returned by
9877     *        {@link #onSaveInstanceState}.
9878     *
9879     * @see #onSaveInstanceState()
9880     * @see #restoreHierarchyState(android.util.SparseArray)
9881     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9882     */
9883    protected void onRestoreInstanceState(Parcelable state) {
9884        mPrivateFlags |= SAVE_STATE_CALLED;
9885        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9886            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9887                    + "received " + state.getClass().toString() + " instead. This usually happens "
9888                    + "when two views of different type have the same id in the same hierarchy. "
9889                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9890                    + "other views do not use the same id.");
9891        }
9892    }
9893
9894    /**
9895     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9896     *
9897     * @return the drawing start time in milliseconds
9898     */
9899    public long getDrawingTime() {
9900        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9901    }
9902
9903    /**
9904     * <p>Enables or disables the duplication of the parent's state into this view. When
9905     * duplication is enabled, this view gets its drawable state from its parent rather
9906     * than from its own internal properties.</p>
9907     *
9908     * <p>Note: in the current implementation, setting this property to true after the
9909     * view was added to a ViewGroup might have no effect at all. This property should
9910     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9911     *
9912     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9913     * property is enabled, an exception will be thrown.</p>
9914     *
9915     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9916     * parent, these states should not be affected by this method.</p>
9917     *
9918     * @param enabled True to enable duplication of the parent's drawable state, false
9919     *                to disable it.
9920     *
9921     * @see #getDrawableState()
9922     * @see #isDuplicateParentStateEnabled()
9923     */
9924    public void setDuplicateParentStateEnabled(boolean enabled) {
9925        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9926    }
9927
9928    /**
9929     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9930     *
9931     * @return True if this view's drawable state is duplicated from the parent,
9932     *         false otherwise
9933     *
9934     * @see #getDrawableState()
9935     * @see #setDuplicateParentStateEnabled(boolean)
9936     */
9937    public boolean isDuplicateParentStateEnabled() {
9938        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9939    }
9940
9941    /**
9942     * <p>Specifies the type of layer backing this view. The layer can be
9943     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
9944     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
9945     *
9946     * <p>A layer is associated with an optional {@link android.graphics.Paint}
9947     * instance that controls how the layer is composed on screen. The following
9948     * properties of the paint are taken into account when composing the layer:</p>
9949     * <ul>
9950     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
9951     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
9952     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
9953     * </ul>
9954     *
9955     * <p>If this view has an alpha value set to < 1.0 by calling
9956     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
9957     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
9958     * equivalent to setting a hardware layer on this view and providing a paint with
9959     * the desired alpha value.<p>
9960     *
9961     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
9962     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
9963     * for more information on when and how to use layers.</p>
9964     *
9965     * @param layerType The ype of layer to use with this view, must be one of
9966     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
9967     *        {@link #LAYER_TYPE_HARDWARE}
9968     * @param paint The paint used to compose the layer. This argument is optional
9969     *        and can be null. It is ignored when the layer type is
9970     *        {@link #LAYER_TYPE_NONE}
9971     *
9972     * @see #getLayerType()
9973     * @see #LAYER_TYPE_NONE
9974     * @see #LAYER_TYPE_SOFTWARE
9975     * @see #LAYER_TYPE_HARDWARE
9976     * @see #setAlpha(float)
9977     *
9978     * @attr ref android.R.styleable#View_layerType
9979     */
9980    public void setLayerType(int layerType, Paint paint) {
9981        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
9982            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
9983                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
9984        }
9985
9986        if (layerType == mLayerType) {
9987            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
9988                mLayerPaint = paint == null ? new Paint() : paint;
9989                invalidateParentCaches();
9990                invalidate(true);
9991            }
9992            return;
9993        }
9994
9995        // Destroy any previous software drawing cache if needed
9996        switch (mLayerType) {
9997            case LAYER_TYPE_HARDWARE:
9998                destroyLayer();
9999                // fall through - unaccelerated views may use software layer mechanism instead
10000            case LAYER_TYPE_SOFTWARE:
10001                destroyDrawingCache();
10002                break;
10003            default:
10004                break;
10005        }
10006
10007        mLayerType = layerType;
10008        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10009        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10010        mLocalDirtyRect = layerDisabled ? null : new Rect();
10011
10012        invalidateParentCaches();
10013        invalidate(true);
10014    }
10015
10016    /**
10017     * Indicates whether this view has a static layer. A view with layer type
10018     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10019     * dynamic.
10020     */
10021    boolean hasStaticLayer() {
10022        return mLayerType == LAYER_TYPE_NONE;
10023    }
10024
10025    /**
10026     * Indicates what type of layer is currently associated with this view. By default
10027     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10028     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10029     * for more information on the different types of layers.
10030     *
10031     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10032     *         {@link #LAYER_TYPE_HARDWARE}
10033     *
10034     * @see #setLayerType(int, android.graphics.Paint)
10035     * @see #buildLayer()
10036     * @see #LAYER_TYPE_NONE
10037     * @see #LAYER_TYPE_SOFTWARE
10038     * @see #LAYER_TYPE_HARDWARE
10039     */
10040    public int getLayerType() {
10041        return mLayerType;
10042    }
10043
10044    /**
10045     * Forces this view's layer to be created and this view to be rendered
10046     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10047     * invoking this method will have no effect.
10048     *
10049     * This method can for instance be used to render a view into its layer before
10050     * starting an animation. If this view is complex, rendering into the layer
10051     * before starting the animation will avoid skipping frames.
10052     *
10053     * @throws IllegalStateException If this view is not attached to a window
10054     *
10055     * @see #setLayerType(int, android.graphics.Paint)
10056     */
10057    public void buildLayer() {
10058        if (mLayerType == LAYER_TYPE_NONE) return;
10059
10060        if (mAttachInfo == null) {
10061            throw new IllegalStateException("This view must be attached to a window first");
10062        }
10063
10064        switch (mLayerType) {
10065            case LAYER_TYPE_HARDWARE:
10066                getHardwareLayer();
10067                break;
10068            case LAYER_TYPE_SOFTWARE:
10069                buildDrawingCache(true);
10070                break;
10071        }
10072    }
10073
10074    /**
10075     * <p>Returns a hardware layer that can be used to draw this view again
10076     * without executing its draw method.</p>
10077     *
10078     * @return A HardwareLayer ready to render, or null if an error occurred.
10079     */
10080    HardwareLayer getHardwareLayer() {
10081        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10082                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10083            return null;
10084        }
10085
10086        final int width = mRight - mLeft;
10087        final int height = mBottom - mTop;
10088
10089        if (width == 0 || height == 0) {
10090            return null;
10091        }
10092
10093        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10094            if (mHardwareLayer == null) {
10095                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10096                        width, height, isOpaque());
10097                mLocalDirtyRect.setEmpty();
10098            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10099                mHardwareLayer.resize(width, height);
10100                mLocalDirtyRect.setEmpty();
10101            }
10102
10103            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
10104            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
10105            mAttachInfo.mHardwareCanvas = canvas;
10106            try {
10107                canvas.setViewport(width, height);
10108                canvas.onPreDraw(mLocalDirtyRect);
10109                mLocalDirtyRect.setEmpty();
10110
10111                final int restoreCount = canvas.save();
10112
10113                computeScroll();
10114                canvas.translate(-mScrollX, -mScrollY);
10115
10116                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10117
10118                // Fast path for layouts with no backgrounds
10119                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10120                    mPrivateFlags &= ~DIRTY_MASK;
10121                    dispatchDraw(canvas);
10122                } else {
10123                    draw(canvas);
10124                }
10125
10126                canvas.restoreToCount(restoreCount);
10127            } finally {
10128                canvas.onPostDraw();
10129                mHardwareLayer.end(currentCanvas);
10130                mAttachInfo.mHardwareCanvas = currentCanvas;
10131            }
10132        }
10133
10134        return mHardwareLayer;
10135    }
10136
10137    boolean destroyLayer() {
10138        if (mHardwareLayer != null) {
10139            mHardwareLayer.destroy();
10140            mHardwareLayer = null;
10141            return true;
10142        }
10143        return false;
10144    }
10145
10146    /**
10147     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10148     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10149     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10150     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10151     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10152     * null.</p>
10153     *
10154     * <p>Enabling the drawing cache is similar to
10155     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10156     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10157     * drawing cache has no effect on rendering because the system uses a different mechanism
10158     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10159     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10160     * for information on how to enable software and hardware layers.</p>
10161     *
10162     * <p>This API can be used to manually generate
10163     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10164     * {@link #getDrawingCache()}.</p>
10165     *
10166     * @param enabled true to enable the drawing cache, false otherwise
10167     *
10168     * @see #isDrawingCacheEnabled()
10169     * @see #getDrawingCache()
10170     * @see #buildDrawingCache()
10171     * @see #setLayerType(int, android.graphics.Paint)
10172     */
10173    public void setDrawingCacheEnabled(boolean enabled) {
10174        mCachingFailed = false;
10175        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10176    }
10177
10178    /**
10179     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10180     *
10181     * @return true if the drawing cache is enabled
10182     *
10183     * @see #setDrawingCacheEnabled(boolean)
10184     * @see #getDrawingCache()
10185     */
10186    @ViewDebug.ExportedProperty(category = "drawing")
10187    public boolean isDrawingCacheEnabled() {
10188        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10189    }
10190
10191    /**
10192     * Debugging utility which recursively outputs the dirty state of a view and its
10193     * descendants.
10194     *
10195     * @hide
10196     */
10197    @SuppressWarnings({"UnusedDeclaration"})
10198    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10199        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10200                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10201                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10202                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10203        if (clear) {
10204            mPrivateFlags &= clearMask;
10205        }
10206        if (this instanceof ViewGroup) {
10207            ViewGroup parent = (ViewGroup) this;
10208            final int count = parent.getChildCount();
10209            for (int i = 0; i < count; i++) {
10210                final View child = parent.getChildAt(i);
10211                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10212            }
10213        }
10214    }
10215
10216    /**
10217     * This method is used by ViewGroup to cause its children to restore or recreate their
10218     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10219     * to recreate its own display list, which would happen if it went through the normal
10220     * draw/dispatchDraw mechanisms.
10221     *
10222     * @hide
10223     */
10224    protected void dispatchGetDisplayList() {}
10225
10226    /**
10227     * A view that is not attached or hardware accelerated cannot create a display list.
10228     * This method checks these conditions and returns the appropriate result.
10229     *
10230     * @return true if view has the ability to create a display list, false otherwise.
10231     *
10232     * @hide
10233     */
10234    public boolean canHaveDisplayList() {
10235        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10236    }
10237
10238    /**
10239     * <p>Returns a display list that can be used to draw this view again
10240     * without executing its draw method.</p>
10241     *
10242     * @return A DisplayList ready to replay, or null if caching is not enabled.
10243     *
10244     * @hide
10245     */
10246    public DisplayList getDisplayList() {
10247        if (!canHaveDisplayList()) {
10248            return null;
10249        }
10250
10251        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10252                mDisplayList == null || !mDisplayList.isValid() ||
10253                mRecreateDisplayList)) {
10254            // Don't need to recreate the display list, just need to tell our
10255            // children to restore/recreate theirs
10256            if (mDisplayList != null && mDisplayList.isValid() &&
10257                    !mRecreateDisplayList) {
10258                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10259                mPrivateFlags &= ~DIRTY_MASK;
10260                dispatchGetDisplayList();
10261
10262                return mDisplayList;
10263            }
10264
10265            // If we got here, we're recreating it. Mark it as such to ensure that
10266            // we copy in child display lists into ours in drawChild()
10267            mRecreateDisplayList = true;
10268            if (mDisplayList == null) {
10269                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList();
10270                // If we're creating a new display list, make sure our parent gets invalidated
10271                // since they will need to recreate their display list to account for this
10272                // new child display list.
10273                invalidateParentCaches();
10274            }
10275
10276            final HardwareCanvas canvas = mDisplayList.start();
10277            int restoreCount = 0;
10278            try {
10279                int width = mRight - mLeft;
10280                int height = mBottom - mTop;
10281
10282                canvas.setViewport(width, height);
10283                // The dirty rect should always be null for a display list
10284                canvas.onPreDraw(null);
10285
10286                computeScroll();
10287
10288                restoreCount = canvas.save();
10289                canvas.translate(-mScrollX, -mScrollY);
10290                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10291                mPrivateFlags &= ~DIRTY_MASK;
10292
10293                // Fast path for layouts with no backgrounds
10294                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10295                    dispatchDraw(canvas);
10296                } else {
10297                    draw(canvas);
10298                }
10299            } finally {
10300                canvas.restoreToCount(restoreCount);
10301                canvas.onPostDraw();
10302
10303                mDisplayList.end();
10304            }
10305        } else {
10306            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10307            mPrivateFlags &= ~DIRTY_MASK;
10308        }
10309
10310        return mDisplayList;
10311    }
10312
10313    /**
10314     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10315     *
10316     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10317     *
10318     * @see #getDrawingCache(boolean)
10319     */
10320    public Bitmap getDrawingCache() {
10321        return getDrawingCache(false);
10322    }
10323
10324    /**
10325     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10326     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10327     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10328     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10329     * request the drawing cache by calling this method and draw it on screen if the
10330     * returned bitmap is not null.</p>
10331     *
10332     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10333     * this method will create a bitmap of the same size as this view. Because this bitmap
10334     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10335     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10336     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10337     * size than the view. This implies that your application must be able to handle this
10338     * size.</p>
10339     *
10340     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10341     *        the current density of the screen when the application is in compatibility
10342     *        mode.
10343     *
10344     * @return A bitmap representing this view or null if cache is disabled.
10345     *
10346     * @see #setDrawingCacheEnabled(boolean)
10347     * @see #isDrawingCacheEnabled()
10348     * @see #buildDrawingCache(boolean)
10349     * @see #destroyDrawingCache()
10350     */
10351    public Bitmap getDrawingCache(boolean autoScale) {
10352        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10353            return null;
10354        }
10355        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10356            buildDrawingCache(autoScale);
10357        }
10358        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10359    }
10360
10361    /**
10362     * <p>Frees the resources used by the drawing cache. If you call
10363     * {@link #buildDrawingCache()} manually without calling
10364     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10365     * should cleanup the cache with this method afterwards.</p>
10366     *
10367     * @see #setDrawingCacheEnabled(boolean)
10368     * @see #buildDrawingCache()
10369     * @see #getDrawingCache()
10370     */
10371    public void destroyDrawingCache() {
10372        if (mDrawingCache != null) {
10373            mDrawingCache.recycle();
10374            mDrawingCache = null;
10375        }
10376        if (mUnscaledDrawingCache != null) {
10377            mUnscaledDrawingCache.recycle();
10378            mUnscaledDrawingCache = null;
10379        }
10380    }
10381
10382    /**
10383     * Setting a solid background color for the drawing cache's bitmaps will improve
10384     * performance and memory usage. Note, though that this should only be used if this
10385     * view will always be drawn on top of a solid color.
10386     *
10387     * @param color The background color to use for the drawing cache's bitmap
10388     *
10389     * @see #setDrawingCacheEnabled(boolean)
10390     * @see #buildDrawingCache()
10391     * @see #getDrawingCache()
10392     */
10393    public void setDrawingCacheBackgroundColor(int color) {
10394        if (color != mDrawingCacheBackgroundColor) {
10395            mDrawingCacheBackgroundColor = color;
10396            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10397        }
10398    }
10399
10400    /**
10401     * @see #setDrawingCacheBackgroundColor(int)
10402     *
10403     * @return The background color to used for the drawing cache's bitmap
10404     */
10405    public int getDrawingCacheBackgroundColor() {
10406        return mDrawingCacheBackgroundColor;
10407    }
10408
10409    /**
10410     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10411     *
10412     * @see #buildDrawingCache(boolean)
10413     */
10414    public void buildDrawingCache() {
10415        buildDrawingCache(false);
10416    }
10417
10418    /**
10419     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10420     *
10421     * <p>If you call {@link #buildDrawingCache()} manually without calling
10422     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10423     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10424     *
10425     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10426     * this method will create a bitmap of the same size as this view. Because this bitmap
10427     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10428     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10429     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10430     * size than the view. This implies that your application must be able to handle this
10431     * size.</p>
10432     *
10433     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10434     * you do not need the drawing cache bitmap, calling this method will increase memory
10435     * usage and cause the view to be rendered in software once, thus negatively impacting
10436     * performance.</p>
10437     *
10438     * @see #getDrawingCache()
10439     * @see #destroyDrawingCache()
10440     */
10441    public void buildDrawingCache(boolean autoScale) {
10442        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10443                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10444            mCachingFailed = false;
10445
10446            if (ViewDebug.TRACE_HIERARCHY) {
10447                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10448            }
10449
10450            int width = mRight - mLeft;
10451            int height = mBottom - mTop;
10452
10453            final AttachInfo attachInfo = mAttachInfo;
10454            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10455
10456            if (autoScale && scalingRequired) {
10457                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10458                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10459            }
10460
10461            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10462            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10463            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10464
10465            if (width <= 0 || height <= 0 ||
10466                     // Projected bitmap size in bytes
10467                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10468                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10469                destroyDrawingCache();
10470                mCachingFailed = true;
10471                return;
10472            }
10473
10474            boolean clear = true;
10475            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10476
10477            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10478                Bitmap.Config quality;
10479                if (!opaque) {
10480                    // Never pick ARGB_4444 because it looks awful
10481                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10482                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10483                        case DRAWING_CACHE_QUALITY_AUTO:
10484                            quality = Bitmap.Config.ARGB_8888;
10485                            break;
10486                        case DRAWING_CACHE_QUALITY_LOW:
10487                            quality = Bitmap.Config.ARGB_8888;
10488                            break;
10489                        case DRAWING_CACHE_QUALITY_HIGH:
10490                            quality = Bitmap.Config.ARGB_8888;
10491                            break;
10492                        default:
10493                            quality = Bitmap.Config.ARGB_8888;
10494                            break;
10495                    }
10496                } else {
10497                    // Optimization for translucent windows
10498                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10499                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10500                }
10501
10502                // Try to cleanup memory
10503                if (bitmap != null) bitmap.recycle();
10504
10505                try {
10506                    bitmap = Bitmap.createBitmap(width, height, quality);
10507                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10508                    if (autoScale) {
10509                        mDrawingCache = bitmap;
10510                    } else {
10511                        mUnscaledDrawingCache = bitmap;
10512                    }
10513                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10514                } catch (OutOfMemoryError e) {
10515                    // If there is not enough memory to create the bitmap cache, just
10516                    // ignore the issue as bitmap caches are not required to draw the
10517                    // view hierarchy
10518                    if (autoScale) {
10519                        mDrawingCache = null;
10520                    } else {
10521                        mUnscaledDrawingCache = null;
10522                    }
10523                    mCachingFailed = true;
10524                    return;
10525                }
10526
10527                clear = drawingCacheBackgroundColor != 0;
10528            }
10529
10530            Canvas canvas;
10531            if (attachInfo != null) {
10532                canvas = attachInfo.mCanvas;
10533                if (canvas == null) {
10534                    canvas = new Canvas();
10535                }
10536                canvas.setBitmap(bitmap);
10537                // Temporarily clobber the cached Canvas in case one of our children
10538                // is also using a drawing cache. Without this, the children would
10539                // steal the canvas by attaching their own bitmap to it and bad, bad
10540                // thing would happen (invisible views, corrupted drawings, etc.)
10541                attachInfo.mCanvas = null;
10542            } else {
10543                // This case should hopefully never or seldom happen
10544                canvas = new Canvas(bitmap);
10545            }
10546
10547            if (clear) {
10548                bitmap.eraseColor(drawingCacheBackgroundColor);
10549            }
10550
10551            computeScroll();
10552            final int restoreCount = canvas.save();
10553
10554            if (autoScale && scalingRequired) {
10555                final float scale = attachInfo.mApplicationScale;
10556                canvas.scale(scale, scale);
10557            }
10558
10559            canvas.translate(-mScrollX, -mScrollY);
10560
10561            mPrivateFlags |= DRAWN;
10562            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10563                    mLayerType != LAYER_TYPE_NONE) {
10564                mPrivateFlags |= DRAWING_CACHE_VALID;
10565            }
10566
10567            // Fast path for layouts with no backgrounds
10568            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10569                if (ViewDebug.TRACE_HIERARCHY) {
10570                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10571                }
10572                mPrivateFlags &= ~DIRTY_MASK;
10573                dispatchDraw(canvas);
10574            } else {
10575                draw(canvas);
10576            }
10577
10578            canvas.restoreToCount(restoreCount);
10579            canvas.setBitmap(null);
10580
10581            if (attachInfo != null) {
10582                // Restore the cached Canvas for our siblings
10583                attachInfo.mCanvas = canvas;
10584            }
10585        }
10586    }
10587
10588    /**
10589     * Create a snapshot of the view into a bitmap.  We should probably make
10590     * some form of this public, but should think about the API.
10591     */
10592    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10593        int width = mRight - mLeft;
10594        int height = mBottom - mTop;
10595
10596        final AttachInfo attachInfo = mAttachInfo;
10597        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10598        width = (int) ((width * scale) + 0.5f);
10599        height = (int) ((height * scale) + 0.5f);
10600
10601        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10602        if (bitmap == null) {
10603            throw new OutOfMemoryError();
10604        }
10605
10606        Resources resources = getResources();
10607        if (resources != null) {
10608            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10609        }
10610
10611        Canvas canvas;
10612        if (attachInfo != null) {
10613            canvas = attachInfo.mCanvas;
10614            if (canvas == null) {
10615                canvas = new Canvas();
10616            }
10617            canvas.setBitmap(bitmap);
10618            // Temporarily clobber the cached Canvas in case one of our children
10619            // is also using a drawing cache. Without this, the children would
10620            // steal the canvas by attaching their own bitmap to it and bad, bad
10621            // things would happen (invisible views, corrupted drawings, etc.)
10622            attachInfo.mCanvas = null;
10623        } else {
10624            // This case should hopefully never or seldom happen
10625            canvas = new Canvas(bitmap);
10626        }
10627
10628        if ((backgroundColor & 0xff000000) != 0) {
10629            bitmap.eraseColor(backgroundColor);
10630        }
10631
10632        computeScroll();
10633        final int restoreCount = canvas.save();
10634        canvas.scale(scale, scale);
10635        canvas.translate(-mScrollX, -mScrollY);
10636
10637        // Temporarily remove the dirty mask
10638        int flags = mPrivateFlags;
10639        mPrivateFlags &= ~DIRTY_MASK;
10640
10641        // Fast path for layouts with no backgrounds
10642        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10643            dispatchDraw(canvas);
10644        } else {
10645            draw(canvas);
10646        }
10647
10648        mPrivateFlags = flags;
10649
10650        canvas.restoreToCount(restoreCount);
10651        canvas.setBitmap(null);
10652
10653        if (attachInfo != null) {
10654            // Restore the cached Canvas for our siblings
10655            attachInfo.mCanvas = canvas;
10656        }
10657
10658        return bitmap;
10659    }
10660
10661    /**
10662     * Indicates whether this View is currently in edit mode. A View is usually
10663     * in edit mode when displayed within a developer tool. For instance, if
10664     * this View is being drawn by a visual user interface builder, this method
10665     * should return true.
10666     *
10667     * Subclasses should check the return value of this method to provide
10668     * different behaviors if their normal behavior might interfere with the
10669     * host environment. For instance: the class spawns a thread in its
10670     * constructor, the drawing code relies on device-specific features, etc.
10671     *
10672     * This method is usually checked in the drawing code of custom widgets.
10673     *
10674     * @return True if this View is in edit mode, false otherwise.
10675     */
10676    public boolean isInEditMode() {
10677        return false;
10678    }
10679
10680    /**
10681     * If the View draws content inside its padding and enables fading edges,
10682     * it needs to support padding offsets. Padding offsets are added to the
10683     * fading edges to extend the length of the fade so that it covers pixels
10684     * drawn inside the padding.
10685     *
10686     * Subclasses of this class should override this method if they need
10687     * to draw content inside the padding.
10688     *
10689     * @return True if padding offset must be applied, false otherwise.
10690     *
10691     * @see #getLeftPaddingOffset()
10692     * @see #getRightPaddingOffset()
10693     * @see #getTopPaddingOffset()
10694     * @see #getBottomPaddingOffset()
10695     *
10696     * @since CURRENT
10697     */
10698    protected boolean isPaddingOffsetRequired() {
10699        return false;
10700    }
10701
10702    /**
10703     * Amount by which to extend the left fading region. Called only when
10704     * {@link #isPaddingOffsetRequired()} returns true.
10705     *
10706     * @return The left padding offset in pixels.
10707     *
10708     * @see #isPaddingOffsetRequired()
10709     *
10710     * @since CURRENT
10711     */
10712    protected int getLeftPaddingOffset() {
10713        return 0;
10714    }
10715
10716    /**
10717     * Amount by which to extend the right fading region. Called only when
10718     * {@link #isPaddingOffsetRequired()} returns true.
10719     *
10720     * @return The right padding offset in pixels.
10721     *
10722     * @see #isPaddingOffsetRequired()
10723     *
10724     * @since CURRENT
10725     */
10726    protected int getRightPaddingOffset() {
10727        return 0;
10728    }
10729
10730    /**
10731     * Amount by which to extend the top fading region. Called only when
10732     * {@link #isPaddingOffsetRequired()} returns true.
10733     *
10734     * @return The top padding offset in pixels.
10735     *
10736     * @see #isPaddingOffsetRequired()
10737     *
10738     * @since CURRENT
10739     */
10740    protected int getTopPaddingOffset() {
10741        return 0;
10742    }
10743
10744    /**
10745     * Amount by which to extend the bottom fading region. Called only when
10746     * {@link #isPaddingOffsetRequired()} returns true.
10747     *
10748     * @return The bottom padding offset in pixels.
10749     *
10750     * @see #isPaddingOffsetRequired()
10751     *
10752     * @since CURRENT
10753     */
10754    protected int getBottomPaddingOffset() {
10755        return 0;
10756    }
10757
10758    /**
10759     * @hide
10760     * @param offsetRequired
10761     */
10762    protected int getFadeTop(boolean offsetRequired) {
10763        int top = mPaddingTop;
10764        if (offsetRequired) top += getTopPaddingOffset();
10765        return top;
10766    }
10767
10768    /**
10769     * @hide
10770     * @param offsetRequired
10771     */
10772    protected int getFadeHeight(boolean offsetRequired) {
10773        int padding = mPaddingTop;
10774        if (offsetRequired) padding += getTopPaddingOffset();
10775        return mBottom - mTop - mPaddingBottom - padding;
10776    }
10777
10778    /**
10779     * <p>Indicates whether this view is attached to an hardware accelerated
10780     * window or not.</p>
10781     *
10782     * <p>Even if this method returns true, it does not mean that every call
10783     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10784     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10785     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10786     * window is hardware accelerated,
10787     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10788     * return false, and this method will return true.</p>
10789     *
10790     * @return True if the view is attached to a window and the window is
10791     *         hardware accelerated; false in any other case.
10792     */
10793    public boolean isHardwareAccelerated() {
10794        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10795    }
10796
10797    /**
10798     * Manually render this view (and all of its children) to the given Canvas.
10799     * The view must have already done a full layout before this function is
10800     * called.  When implementing a view, implement
10801     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
10802     * If you do need to override this method, call the superclass version.
10803     *
10804     * @param canvas The Canvas to which the View is rendered.
10805     */
10806    public void draw(Canvas canvas) {
10807        if (ViewDebug.TRACE_HIERARCHY) {
10808            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10809        }
10810
10811        final int privateFlags = mPrivateFlags;
10812        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
10813                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
10814        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
10815
10816        /*
10817         * Draw traversal performs several drawing steps which must be executed
10818         * in the appropriate order:
10819         *
10820         *      1. Draw the background
10821         *      2. If necessary, save the canvas' layers to prepare for fading
10822         *      3. Draw view's content
10823         *      4. Draw children
10824         *      5. If necessary, draw the fading edges and restore layers
10825         *      6. Draw decorations (scrollbars for instance)
10826         */
10827
10828        // Step 1, draw the background, if needed
10829        int saveCount;
10830
10831        if (!dirtyOpaque) {
10832            final Drawable background = mBGDrawable;
10833            if (background != null) {
10834                final int scrollX = mScrollX;
10835                final int scrollY = mScrollY;
10836
10837                if (mBackgroundSizeChanged) {
10838                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
10839                    mBackgroundSizeChanged = false;
10840                }
10841
10842                if ((scrollX | scrollY) == 0) {
10843                    background.draw(canvas);
10844                } else {
10845                    canvas.translate(scrollX, scrollY);
10846                    background.draw(canvas);
10847                    canvas.translate(-scrollX, -scrollY);
10848                }
10849            }
10850        }
10851
10852        // skip step 2 & 5 if possible (common case)
10853        final int viewFlags = mViewFlags;
10854        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
10855        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
10856        if (!verticalEdges && !horizontalEdges) {
10857            // Step 3, draw the content
10858            if (!dirtyOpaque) onDraw(canvas);
10859
10860            // Step 4, draw the children
10861            dispatchDraw(canvas);
10862
10863            // Step 6, draw decorations (scrollbars)
10864            onDrawScrollBars(canvas);
10865
10866            // we're done...
10867            return;
10868        }
10869
10870        /*
10871         * Here we do the full fledged routine...
10872         * (this is an uncommon case where speed matters less,
10873         * this is why we repeat some of the tests that have been
10874         * done above)
10875         */
10876
10877        boolean drawTop = false;
10878        boolean drawBottom = false;
10879        boolean drawLeft = false;
10880        boolean drawRight = false;
10881
10882        float topFadeStrength = 0.0f;
10883        float bottomFadeStrength = 0.0f;
10884        float leftFadeStrength = 0.0f;
10885        float rightFadeStrength = 0.0f;
10886
10887        // Step 2, save the canvas' layers
10888        int paddingLeft = mPaddingLeft;
10889
10890        final boolean offsetRequired = isPaddingOffsetRequired();
10891        if (offsetRequired) {
10892            paddingLeft += getLeftPaddingOffset();
10893        }
10894
10895        int left = mScrollX + paddingLeft;
10896        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
10897        int top = mScrollY + getFadeTop(offsetRequired);
10898        int bottom = top + getFadeHeight(offsetRequired);
10899
10900        if (offsetRequired) {
10901            right += getRightPaddingOffset();
10902            bottom += getBottomPaddingOffset();
10903        }
10904
10905        final ScrollabilityCache scrollabilityCache = mScrollCache;
10906        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
10907        int length = (int) fadeHeight;
10908
10909        // clip the fade length if top and bottom fades overlap
10910        // overlapping fades produce odd-looking artifacts
10911        if (verticalEdges && (top + length > bottom - length)) {
10912            length = (bottom - top) / 2;
10913        }
10914
10915        // also clip horizontal fades if necessary
10916        if (horizontalEdges && (left + length > right - length)) {
10917            length = (right - left) / 2;
10918        }
10919
10920        if (verticalEdges) {
10921            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
10922            drawTop = topFadeStrength * fadeHeight > 1.0f;
10923            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
10924            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
10925        }
10926
10927        if (horizontalEdges) {
10928            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
10929            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
10930            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
10931            drawRight = rightFadeStrength * fadeHeight > 1.0f;
10932        }
10933
10934        saveCount = canvas.getSaveCount();
10935
10936        int solidColor = getSolidColor();
10937        if (solidColor == 0) {
10938            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
10939
10940            if (drawTop) {
10941                canvas.saveLayer(left, top, right, top + length, null, flags);
10942            }
10943
10944            if (drawBottom) {
10945                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
10946            }
10947
10948            if (drawLeft) {
10949                canvas.saveLayer(left, top, left + length, bottom, null, flags);
10950            }
10951
10952            if (drawRight) {
10953                canvas.saveLayer(right - length, top, right, bottom, null, flags);
10954            }
10955        } else {
10956            scrollabilityCache.setFadeColor(solidColor);
10957        }
10958
10959        // Step 3, draw the content
10960        if (!dirtyOpaque) onDraw(canvas);
10961
10962        // Step 4, draw the children
10963        dispatchDraw(canvas);
10964
10965        // Step 5, draw the fade effect and restore layers
10966        final Paint p = scrollabilityCache.paint;
10967        final Matrix matrix = scrollabilityCache.matrix;
10968        final Shader fade = scrollabilityCache.shader;
10969
10970        if (drawTop) {
10971            matrix.setScale(1, fadeHeight * topFadeStrength);
10972            matrix.postTranslate(left, top);
10973            fade.setLocalMatrix(matrix);
10974            canvas.drawRect(left, top, right, top + length, p);
10975        }
10976
10977        if (drawBottom) {
10978            matrix.setScale(1, fadeHeight * bottomFadeStrength);
10979            matrix.postRotate(180);
10980            matrix.postTranslate(left, bottom);
10981            fade.setLocalMatrix(matrix);
10982            canvas.drawRect(left, bottom - length, right, bottom, p);
10983        }
10984
10985        if (drawLeft) {
10986            matrix.setScale(1, fadeHeight * leftFadeStrength);
10987            matrix.postRotate(-90);
10988            matrix.postTranslate(left, top);
10989            fade.setLocalMatrix(matrix);
10990            canvas.drawRect(left, top, left + length, bottom, p);
10991        }
10992
10993        if (drawRight) {
10994            matrix.setScale(1, fadeHeight * rightFadeStrength);
10995            matrix.postRotate(90);
10996            matrix.postTranslate(right, top);
10997            fade.setLocalMatrix(matrix);
10998            canvas.drawRect(right - length, top, right, bottom, p);
10999        }
11000
11001        canvas.restoreToCount(saveCount);
11002
11003        // Step 6, draw decorations (scrollbars)
11004        onDrawScrollBars(canvas);
11005    }
11006
11007    /**
11008     * Override this if your view is known to always be drawn on top of a solid color background,
11009     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11010     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11011     * should be set to 0xFF.
11012     *
11013     * @see #setVerticalFadingEdgeEnabled(boolean)
11014     * @see #setHorizontalFadingEdgeEnabled(boolean)
11015     *
11016     * @return The known solid color background for this view, or 0 if the color may vary
11017     */
11018    @ViewDebug.ExportedProperty(category = "drawing")
11019    public int getSolidColor() {
11020        return 0;
11021    }
11022
11023    /**
11024     * Build a human readable string representation of the specified view flags.
11025     *
11026     * @param flags the view flags to convert to a string
11027     * @return a String representing the supplied flags
11028     */
11029    private static String printFlags(int flags) {
11030        String output = "";
11031        int numFlags = 0;
11032        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11033            output += "TAKES_FOCUS";
11034            numFlags++;
11035        }
11036
11037        switch (flags & VISIBILITY_MASK) {
11038        case INVISIBLE:
11039            if (numFlags > 0) {
11040                output += " ";
11041            }
11042            output += "INVISIBLE";
11043            // USELESS HERE numFlags++;
11044            break;
11045        case GONE:
11046            if (numFlags > 0) {
11047                output += " ";
11048            }
11049            output += "GONE";
11050            // USELESS HERE numFlags++;
11051            break;
11052        default:
11053            break;
11054        }
11055        return output;
11056    }
11057
11058    /**
11059     * Build a human readable string representation of the specified private
11060     * view flags.
11061     *
11062     * @param privateFlags the private view flags to convert to a string
11063     * @return a String representing the supplied flags
11064     */
11065    private static String printPrivateFlags(int privateFlags) {
11066        String output = "";
11067        int numFlags = 0;
11068
11069        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11070            output += "WANTS_FOCUS";
11071            numFlags++;
11072        }
11073
11074        if ((privateFlags & FOCUSED) == FOCUSED) {
11075            if (numFlags > 0) {
11076                output += " ";
11077            }
11078            output += "FOCUSED";
11079            numFlags++;
11080        }
11081
11082        if ((privateFlags & SELECTED) == SELECTED) {
11083            if (numFlags > 0) {
11084                output += " ";
11085            }
11086            output += "SELECTED";
11087            numFlags++;
11088        }
11089
11090        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11091            if (numFlags > 0) {
11092                output += " ";
11093            }
11094            output += "IS_ROOT_NAMESPACE";
11095            numFlags++;
11096        }
11097
11098        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11099            if (numFlags > 0) {
11100                output += " ";
11101            }
11102            output += "HAS_BOUNDS";
11103            numFlags++;
11104        }
11105
11106        if ((privateFlags & DRAWN) == DRAWN) {
11107            if (numFlags > 0) {
11108                output += " ";
11109            }
11110            output += "DRAWN";
11111            // USELESS HERE numFlags++;
11112        }
11113        return output;
11114    }
11115
11116    /**
11117     * <p>Indicates whether or not this view's layout will be requested during
11118     * the next hierarchy layout pass.</p>
11119     *
11120     * @return true if the layout will be forced during next layout pass
11121     */
11122    public boolean isLayoutRequested() {
11123        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11124    }
11125
11126    /**
11127     * Assign a size and position to a view and all of its
11128     * descendants
11129     *
11130     * <p>This is the second phase of the layout mechanism.
11131     * (The first is measuring). In this phase, each parent calls
11132     * layout on all of its children to position them.
11133     * This is typically done using the child measurements
11134     * that were stored in the measure pass().</p>
11135     *
11136     * <p>Derived classes should not override this method.
11137     * Derived classes with children should override
11138     * onLayout. In that method, they should
11139     * call layout on each of their children.</p>
11140     *
11141     * @param l Left position, relative to parent
11142     * @param t Top position, relative to parent
11143     * @param r Right position, relative to parent
11144     * @param b Bottom position, relative to parent
11145     */
11146    @SuppressWarnings({"unchecked"})
11147    public void layout(int l, int t, int r, int b) {
11148        int oldL = mLeft;
11149        int oldT = mTop;
11150        int oldB = mBottom;
11151        int oldR = mRight;
11152        boolean changed = setFrame(l, t, r, b);
11153        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11154            if (ViewDebug.TRACE_HIERARCHY) {
11155                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11156            }
11157
11158            onLayout(changed, l, t, r, b);
11159            mPrivateFlags &= ~LAYOUT_REQUIRED;
11160
11161            if (mOnLayoutChangeListeners != null) {
11162                ArrayList<OnLayoutChangeListener> listenersCopy =
11163                        (ArrayList<OnLayoutChangeListener>) mOnLayoutChangeListeners.clone();
11164                int numListeners = listenersCopy.size();
11165                for (int i = 0; i < numListeners; ++i) {
11166                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11167                }
11168            }
11169        }
11170        mPrivateFlags &= ~FORCE_LAYOUT;
11171    }
11172
11173    /**
11174     * Called from layout when this view should
11175     * assign a size and position to each of its children.
11176     *
11177     * Derived classes with children should override
11178     * this method and call layout on each of
11179     * their children.
11180     * @param changed This is a new size or position for this view
11181     * @param left Left position, relative to parent
11182     * @param top Top position, relative to parent
11183     * @param right Right position, relative to parent
11184     * @param bottom Bottom position, relative to parent
11185     */
11186    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11187    }
11188
11189    /**
11190     * Assign a size and position to this view.
11191     *
11192     * This is called from layout.
11193     *
11194     * @param left Left position, relative to parent
11195     * @param top Top position, relative to parent
11196     * @param right Right position, relative to parent
11197     * @param bottom Bottom position, relative to parent
11198     * @return true if the new size and position are different than the
11199     *         previous ones
11200     * {@hide}
11201     */
11202    protected boolean setFrame(int left, int top, int right, int bottom) {
11203        boolean changed = false;
11204
11205        if (DBG) {
11206            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11207                    + right + "," + bottom + ")");
11208        }
11209
11210        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11211            changed = true;
11212
11213            // Remember our drawn bit
11214            int drawn = mPrivateFlags & DRAWN;
11215
11216            int oldWidth = mRight - mLeft;
11217            int oldHeight = mBottom - mTop;
11218            int newWidth = right - left;
11219            int newHeight = bottom - top;
11220            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11221
11222            // Invalidate our old position
11223            invalidate(sizeChanged);
11224
11225            mLeft = left;
11226            mTop = top;
11227            mRight = right;
11228            mBottom = bottom;
11229
11230            mPrivateFlags |= HAS_BOUNDS;
11231
11232
11233            if (sizeChanged) {
11234                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11235                    // A change in dimension means an auto-centered pivot point changes, too
11236                    if (mTransformationInfo != null) {
11237                        mTransformationInfo.mMatrixDirty = true;
11238                    }
11239                }
11240                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11241            }
11242
11243            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11244                // If we are visible, force the DRAWN bit to on so that
11245                // this invalidate will go through (at least to our parent).
11246                // This is because someone may have invalidated this view
11247                // before this call to setFrame came in, thereby clearing
11248                // the DRAWN bit.
11249                mPrivateFlags |= DRAWN;
11250                invalidate(sizeChanged);
11251                // parent display list may need to be recreated based on a change in the bounds
11252                // of any child
11253                invalidateParentCaches();
11254            }
11255
11256            // Reset drawn bit to original value (invalidate turns it off)
11257            mPrivateFlags |= drawn;
11258
11259            mBackgroundSizeChanged = true;
11260        }
11261        return changed;
11262    }
11263
11264    /**
11265     * Finalize inflating a view from XML.  This is called as the last phase
11266     * of inflation, after all child views have been added.
11267     *
11268     * <p>Even if the subclass overrides onFinishInflate, they should always be
11269     * sure to call the super method, so that we get called.
11270     */
11271    protected void onFinishInflate() {
11272    }
11273
11274    /**
11275     * Returns the resources associated with this view.
11276     *
11277     * @return Resources object.
11278     */
11279    public Resources getResources() {
11280        return mResources;
11281    }
11282
11283    /**
11284     * Invalidates the specified Drawable.
11285     *
11286     * @param drawable the drawable to invalidate
11287     */
11288    public void invalidateDrawable(Drawable drawable) {
11289        if (verifyDrawable(drawable)) {
11290            final Rect dirty = drawable.getBounds();
11291            final int scrollX = mScrollX;
11292            final int scrollY = mScrollY;
11293
11294            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11295                    dirty.right + scrollX, dirty.bottom + scrollY);
11296        }
11297    }
11298
11299    /**
11300     * Schedules an action on a drawable to occur at a specified time.
11301     *
11302     * @param who the recipient of the action
11303     * @param what the action to run on the drawable
11304     * @param when the time at which the action must occur. Uses the
11305     *        {@link SystemClock#uptimeMillis} timebase.
11306     */
11307    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11308        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11309            mAttachInfo.mHandler.postAtTime(what, who, when);
11310        }
11311    }
11312
11313    /**
11314     * Cancels a scheduled action on a drawable.
11315     *
11316     * @param who the recipient of the action
11317     * @param what the action to cancel
11318     */
11319    public void unscheduleDrawable(Drawable who, Runnable what) {
11320        if (verifyDrawable(who) && what != null && mAttachInfo != null) {
11321            mAttachInfo.mHandler.removeCallbacks(what, who);
11322        }
11323    }
11324
11325    /**
11326     * Unschedule any events associated with the given Drawable.  This can be
11327     * used when selecting a new Drawable into a view, so that the previous
11328     * one is completely unscheduled.
11329     *
11330     * @param who The Drawable to unschedule.
11331     *
11332     * @see #drawableStateChanged
11333     */
11334    public void unscheduleDrawable(Drawable who) {
11335        if (mAttachInfo != null) {
11336            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11337        }
11338    }
11339
11340    /**
11341    * Return the layout direction of a given Drawable.
11342    *
11343    * @param who the Drawable to query
11344    *
11345    * @hide
11346    */
11347    public int getResolvedLayoutDirection(Drawable who) {
11348        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11349    }
11350
11351    /**
11352     * If your view subclass is displaying its own Drawable objects, it should
11353     * override this function and return true for any Drawable it is
11354     * displaying.  This allows animations for those drawables to be
11355     * scheduled.
11356     *
11357     * <p>Be sure to call through to the super class when overriding this
11358     * function.
11359     *
11360     * @param who The Drawable to verify.  Return true if it is one you are
11361     *            displaying, else return the result of calling through to the
11362     *            super class.
11363     *
11364     * @return boolean If true than the Drawable is being displayed in the
11365     *         view; else false and it is not allowed to animate.
11366     *
11367     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11368     * @see #drawableStateChanged()
11369     */
11370    protected boolean verifyDrawable(Drawable who) {
11371        return who == mBGDrawable;
11372    }
11373
11374    /**
11375     * This function is called whenever the state of the view changes in such
11376     * a way that it impacts the state of drawables being shown.
11377     *
11378     * <p>Be sure to call through to the superclass when overriding this
11379     * function.
11380     *
11381     * @see Drawable#setState(int[])
11382     */
11383    protected void drawableStateChanged() {
11384        Drawable d = mBGDrawable;
11385        if (d != null && d.isStateful()) {
11386            d.setState(getDrawableState());
11387        }
11388    }
11389
11390    /**
11391     * Call this to force a view to update its drawable state. This will cause
11392     * drawableStateChanged to be called on this view. Views that are interested
11393     * in the new state should call getDrawableState.
11394     *
11395     * @see #drawableStateChanged
11396     * @see #getDrawableState
11397     */
11398    public void refreshDrawableState() {
11399        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11400        drawableStateChanged();
11401
11402        ViewParent parent = mParent;
11403        if (parent != null) {
11404            parent.childDrawableStateChanged(this);
11405        }
11406    }
11407
11408    /**
11409     * Return an array of resource IDs of the drawable states representing the
11410     * current state of the view.
11411     *
11412     * @return The current drawable state
11413     *
11414     * @see Drawable#setState(int[])
11415     * @see #drawableStateChanged()
11416     * @see #onCreateDrawableState(int)
11417     */
11418    public final int[] getDrawableState() {
11419        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11420            return mDrawableState;
11421        } else {
11422            mDrawableState = onCreateDrawableState(0);
11423            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11424            return mDrawableState;
11425        }
11426    }
11427
11428    /**
11429     * Generate the new {@link android.graphics.drawable.Drawable} state for
11430     * this view. This is called by the view
11431     * system when the cached Drawable state is determined to be invalid.  To
11432     * retrieve the current state, you should use {@link #getDrawableState}.
11433     *
11434     * @param extraSpace if non-zero, this is the number of extra entries you
11435     * would like in the returned array in which you can place your own
11436     * states.
11437     *
11438     * @return Returns an array holding the current {@link Drawable} state of
11439     * the view.
11440     *
11441     * @see #mergeDrawableStates(int[], int[])
11442     */
11443    protected int[] onCreateDrawableState(int extraSpace) {
11444        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11445                mParent instanceof View) {
11446            return ((View) mParent).onCreateDrawableState(extraSpace);
11447        }
11448
11449        int[] drawableState;
11450
11451        int privateFlags = mPrivateFlags;
11452
11453        int viewStateIndex = 0;
11454        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11455        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11456        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11457        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11458        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11459        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11460        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11461                HardwareRenderer.isAvailable()) {
11462            // This is set if HW acceleration is requested, even if the current
11463            // process doesn't allow it.  This is just to allow app preview
11464            // windows to better match their app.
11465            viewStateIndex |= VIEW_STATE_ACCELERATED;
11466        }
11467        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11468
11469        final int privateFlags2 = mPrivateFlags2;
11470        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11471        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11472
11473        drawableState = VIEW_STATE_SETS[viewStateIndex];
11474
11475        //noinspection ConstantIfStatement
11476        if (false) {
11477            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11478            Log.i("View", toString()
11479                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11480                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11481                    + " fo=" + hasFocus()
11482                    + " sl=" + ((privateFlags & SELECTED) != 0)
11483                    + " wf=" + hasWindowFocus()
11484                    + ": " + Arrays.toString(drawableState));
11485        }
11486
11487        if (extraSpace == 0) {
11488            return drawableState;
11489        }
11490
11491        final int[] fullState;
11492        if (drawableState != null) {
11493            fullState = new int[drawableState.length + extraSpace];
11494            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11495        } else {
11496            fullState = new int[extraSpace];
11497        }
11498
11499        return fullState;
11500    }
11501
11502    /**
11503     * Merge your own state values in <var>additionalState</var> into the base
11504     * state values <var>baseState</var> that were returned by
11505     * {@link #onCreateDrawableState(int)}.
11506     *
11507     * @param baseState The base state values returned by
11508     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11509     * own additional state values.
11510     *
11511     * @param additionalState The additional state values you would like
11512     * added to <var>baseState</var>; this array is not modified.
11513     *
11514     * @return As a convenience, the <var>baseState</var> array you originally
11515     * passed into the function is returned.
11516     *
11517     * @see #onCreateDrawableState(int)
11518     */
11519    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11520        final int N = baseState.length;
11521        int i = N - 1;
11522        while (i >= 0 && baseState[i] == 0) {
11523            i--;
11524        }
11525        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
11526        return baseState;
11527    }
11528
11529    /**
11530     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
11531     * on all Drawable objects associated with this view.
11532     */
11533    public void jumpDrawablesToCurrentState() {
11534        if (mBGDrawable != null) {
11535            mBGDrawable.jumpToCurrentState();
11536        }
11537    }
11538
11539    /**
11540     * Sets the background color for this view.
11541     * @param color the color of the background
11542     */
11543    @RemotableViewMethod
11544    public void setBackgroundColor(int color) {
11545        if (mBGDrawable instanceof ColorDrawable) {
11546            ((ColorDrawable) mBGDrawable).setColor(color);
11547        } else {
11548            setBackgroundDrawable(new ColorDrawable(color));
11549        }
11550    }
11551
11552    /**
11553     * Set the background to a given resource. The resource should refer to
11554     * a Drawable object or 0 to remove the background.
11555     * @param resid The identifier of the resource.
11556     * @attr ref android.R.styleable#View_background
11557     */
11558    @RemotableViewMethod
11559    public void setBackgroundResource(int resid) {
11560        if (resid != 0 && resid == mBackgroundResource) {
11561            return;
11562        }
11563
11564        Drawable d= null;
11565        if (resid != 0) {
11566            d = mResources.getDrawable(resid);
11567        }
11568        setBackgroundDrawable(d);
11569
11570        mBackgroundResource = resid;
11571    }
11572
11573    /**
11574     * Set the background to a given Drawable, or remove the background. If the
11575     * background has padding, this View's padding is set to the background's
11576     * padding. However, when a background is removed, this View's padding isn't
11577     * touched. If setting the padding is desired, please use
11578     * {@link #setPadding(int, int, int, int)}.
11579     *
11580     * @param d The Drawable to use as the background, or null to remove the
11581     *        background
11582     */
11583    public void setBackgroundDrawable(Drawable d) {
11584        if (d == mBGDrawable) {
11585            return;
11586        }
11587
11588        boolean requestLayout = false;
11589
11590        mBackgroundResource = 0;
11591
11592        /*
11593         * Regardless of whether we're setting a new background or not, we want
11594         * to clear the previous drawable.
11595         */
11596        if (mBGDrawable != null) {
11597            mBGDrawable.setCallback(null);
11598            unscheduleDrawable(mBGDrawable);
11599        }
11600
11601        if (d != null) {
11602            Rect padding = sThreadLocal.get();
11603            if (padding == null) {
11604                padding = new Rect();
11605                sThreadLocal.set(padding);
11606            }
11607            if (d.getPadding(padding)) {
11608                switch (d.getResolvedLayoutDirectionSelf()) {
11609                    case LAYOUT_DIRECTION_RTL:
11610                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
11611                        break;
11612                    case LAYOUT_DIRECTION_LTR:
11613                    default:
11614                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
11615                }
11616            }
11617
11618            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
11619            // if it has a different minimum size, we should layout again
11620            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
11621                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
11622                requestLayout = true;
11623            }
11624
11625            d.setCallback(this);
11626            if (d.isStateful()) {
11627                d.setState(getDrawableState());
11628            }
11629            d.setVisible(getVisibility() == VISIBLE, false);
11630            mBGDrawable = d;
11631
11632            if ((mPrivateFlags & SKIP_DRAW) != 0) {
11633                mPrivateFlags &= ~SKIP_DRAW;
11634                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
11635                requestLayout = true;
11636            }
11637        } else {
11638            /* Remove the background */
11639            mBGDrawable = null;
11640
11641            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
11642                /*
11643                 * This view ONLY drew the background before and we're removing
11644                 * the background, so now it won't draw anything
11645                 * (hence we SKIP_DRAW)
11646                 */
11647                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
11648                mPrivateFlags |= SKIP_DRAW;
11649            }
11650
11651            /*
11652             * When the background is set, we try to apply its padding to this
11653             * View. When the background is removed, we don't touch this View's
11654             * padding. This is noted in the Javadocs. Hence, we don't need to
11655             * requestLayout(), the invalidate() below is sufficient.
11656             */
11657
11658            // The old background's minimum size could have affected this
11659            // View's layout, so let's requestLayout
11660            requestLayout = true;
11661        }
11662
11663        computeOpaqueFlags();
11664
11665        if (requestLayout) {
11666            requestLayout();
11667        }
11668
11669        mBackgroundSizeChanged = true;
11670        invalidate(true);
11671    }
11672
11673    /**
11674     * Gets the background drawable
11675     * @return The drawable used as the background for this view, if any.
11676     */
11677    public Drawable getBackground() {
11678        return mBGDrawable;
11679    }
11680
11681    /**
11682     * Sets the padding. The view may add on the space required to display
11683     * the scrollbars, depending on the style and visibility of the scrollbars.
11684     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
11685     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
11686     * from the values set in this call.
11687     *
11688     * @attr ref android.R.styleable#View_padding
11689     * @attr ref android.R.styleable#View_paddingBottom
11690     * @attr ref android.R.styleable#View_paddingLeft
11691     * @attr ref android.R.styleable#View_paddingRight
11692     * @attr ref android.R.styleable#View_paddingTop
11693     * @param left the left padding in pixels
11694     * @param top the top padding in pixels
11695     * @param right the right padding in pixels
11696     * @param bottom the bottom padding in pixels
11697     */
11698    public void setPadding(int left, int top, int right, int bottom) {
11699        boolean changed = false;
11700
11701        mUserPaddingRelative = false;
11702
11703        mUserPaddingLeft = left;
11704        mUserPaddingRight = right;
11705        mUserPaddingBottom = bottom;
11706
11707        final int viewFlags = mViewFlags;
11708
11709        // Common case is there are no scroll bars.
11710        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
11711            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
11712                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
11713                        ? 0 : getVerticalScrollbarWidth();
11714                switch (mVerticalScrollbarPosition) {
11715                    case SCROLLBAR_POSITION_DEFAULT:
11716                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
11717                            left += offset;
11718                        } else {
11719                            right += offset;
11720                        }
11721                        break;
11722                    case SCROLLBAR_POSITION_RIGHT:
11723                        right += offset;
11724                        break;
11725                    case SCROLLBAR_POSITION_LEFT:
11726                        left += offset;
11727                        break;
11728                }
11729            }
11730            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
11731                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
11732                        ? 0 : getHorizontalScrollbarHeight();
11733            }
11734        }
11735
11736        if (mPaddingLeft != left) {
11737            changed = true;
11738            mPaddingLeft = left;
11739        }
11740        if (mPaddingTop != top) {
11741            changed = true;
11742            mPaddingTop = top;
11743        }
11744        if (mPaddingRight != right) {
11745            changed = true;
11746            mPaddingRight = right;
11747        }
11748        if (mPaddingBottom != bottom) {
11749            changed = true;
11750            mPaddingBottom = bottom;
11751        }
11752
11753        if (changed) {
11754            requestLayout();
11755        }
11756    }
11757
11758    /**
11759     * Sets the relative padding. The view may add on the space required to display
11760     * the scrollbars, depending on the style and visibility of the scrollbars.
11761     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
11762     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
11763     * from the values set in this call.
11764     *
11765     * @attr ref android.R.styleable#View_padding
11766     * @attr ref android.R.styleable#View_paddingBottom
11767     * @attr ref android.R.styleable#View_paddingStart
11768     * @attr ref android.R.styleable#View_paddingEnd
11769     * @attr ref android.R.styleable#View_paddingTop
11770     * @param start the start padding in pixels
11771     * @param top the top padding in pixels
11772     * @param end the end padding in pixels
11773     * @param bottom the bottom padding in pixels
11774     *
11775     * @hide
11776     */
11777    public void setPaddingRelative(int start, int top, int end, int bottom) {
11778        mUserPaddingRelative = true;
11779
11780        mUserPaddingStart = start;
11781        mUserPaddingEnd = end;
11782
11783        switch(getResolvedLayoutDirection()) {
11784            case LAYOUT_DIRECTION_RTL:
11785                setPadding(end, top, start, bottom);
11786                break;
11787            case LAYOUT_DIRECTION_LTR:
11788            default:
11789                setPadding(start, top, end, bottom);
11790        }
11791    }
11792
11793    /**
11794     * Returns the top padding of this view.
11795     *
11796     * @return the top padding in pixels
11797     */
11798    public int getPaddingTop() {
11799        return mPaddingTop;
11800    }
11801
11802    /**
11803     * Returns the bottom padding of this view. If there are inset and enabled
11804     * scrollbars, this value may include the space required to display the
11805     * scrollbars as well.
11806     *
11807     * @return the bottom padding in pixels
11808     */
11809    public int getPaddingBottom() {
11810        return mPaddingBottom;
11811    }
11812
11813    /**
11814     * Returns the left padding of this view. If there are inset and enabled
11815     * scrollbars, this value may include the space required to display the
11816     * scrollbars as well.
11817     *
11818     * @return the left padding in pixels
11819     */
11820    public int getPaddingLeft() {
11821        return mPaddingLeft;
11822    }
11823
11824    /**
11825     * Returns the start padding of this view. If there are inset and enabled
11826     * scrollbars, this value may include the space required to display the
11827     * scrollbars as well.
11828     *
11829     * @return the start padding in pixels
11830     *
11831     * @hide
11832     */
11833    public int getPaddingStart() {
11834        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11835                mPaddingRight : mPaddingLeft;
11836    }
11837
11838    /**
11839     * Returns the right padding of this view. If there are inset and enabled
11840     * scrollbars, this value may include the space required to display the
11841     * scrollbars as well.
11842     *
11843     * @return the right padding in pixels
11844     */
11845    public int getPaddingRight() {
11846        return mPaddingRight;
11847    }
11848
11849    /**
11850     * Returns the end padding of this view. If there are inset and enabled
11851     * scrollbars, this value may include the space required to display the
11852     * scrollbars as well.
11853     *
11854     * @return the end padding in pixels
11855     *
11856     * @hide
11857     */
11858    public int getPaddingEnd() {
11859        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
11860                mPaddingLeft : mPaddingRight;
11861    }
11862
11863    /**
11864     * Return if the padding as been set thru relative values
11865     * {@link #setPaddingRelative(int, int, int, int)} or thru
11866     * @attr ref android.R.styleable#View_paddingStart or
11867     * @attr ref android.R.styleable#View_paddingEnd
11868     *
11869     * @return true if the padding is relative or false if it is not.
11870     *
11871     * @hide
11872     */
11873    public boolean isPaddingRelative() {
11874        return mUserPaddingRelative;
11875    }
11876
11877    /**
11878     * Changes the selection state of this view. A view can be selected or not.
11879     * Note that selection is not the same as focus. Views are typically
11880     * selected in the context of an AdapterView like ListView or GridView;
11881     * the selected view is the view that is highlighted.
11882     *
11883     * @param selected true if the view must be selected, false otherwise
11884     */
11885    public void setSelected(boolean selected) {
11886        if (((mPrivateFlags & SELECTED) != 0) != selected) {
11887            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
11888            if (!selected) resetPressedState();
11889            invalidate(true);
11890            refreshDrawableState();
11891            dispatchSetSelected(selected);
11892        }
11893    }
11894
11895    /**
11896     * Dispatch setSelected to all of this View's children.
11897     *
11898     * @see #setSelected(boolean)
11899     *
11900     * @param selected The new selected state
11901     */
11902    protected void dispatchSetSelected(boolean selected) {
11903    }
11904
11905    /**
11906     * Indicates the selection state of this view.
11907     *
11908     * @return true if the view is selected, false otherwise
11909     */
11910    @ViewDebug.ExportedProperty
11911    public boolean isSelected() {
11912        return (mPrivateFlags & SELECTED) != 0;
11913    }
11914
11915    /**
11916     * Changes the activated state of this view. A view can be activated or not.
11917     * Note that activation is not the same as selection.  Selection is
11918     * a transient property, representing the view (hierarchy) the user is
11919     * currently interacting with.  Activation is a longer-term state that the
11920     * user can move views in and out of.  For example, in a list view with
11921     * single or multiple selection enabled, the views in the current selection
11922     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
11923     * here.)  The activated state is propagated down to children of the view it
11924     * is set on.
11925     *
11926     * @param activated true if the view must be activated, false otherwise
11927     */
11928    public void setActivated(boolean activated) {
11929        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
11930            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
11931            invalidate(true);
11932            refreshDrawableState();
11933            dispatchSetActivated(activated);
11934        }
11935    }
11936
11937    /**
11938     * Dispatch setActivated to all of this View's children.
11939     *
11940     * @see #setActivated(boolean)
11941     *
11942     * @param activated The new activated state
11943     */
11944    protected void dispatchSetActivated(boolean activated) {
11945    }
11946
11947    /**
11948     * Indicates the activation state of this view.
11949     *
11950     * @return true if the view is activated, false otherwise
11951     */
11952    @ViewDebug.ExportedProperty
11953    public boolean isActivated() {
11954        return (mPrivateFlags & ACTIVATED) != 0;
11955    }
11956
11957    /**
11958     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
11959     * observer can be used to get notifications when global events, like
11960     * layout, happen.
11961     *
11962     * The returned ViewTreeObserver observer is not guaranteed to remain
11963     * valid for the lifetime of this View. If the caller of this method keeps
11964     * a long-lived reference to ViewTreeObserver, it should always check for
11965     * the return value of {@link ViewTreeObserver#isAlive()}.
11966     *
11967     * @return The ViewTreeObserver for this view's hierarchy.
11968     */
11969    public ViewTreeObserver getViewTreeObserver() {
11970        if (mAttachInfo != null) {
11971            return mAttachInfo.mTreeObserver;
11972        }
11973        if (mFloatingTreeObserver == null) {
11974            mFloatingTreeObserver = new ViewTreeObserver();
11975        }
11976        return mFloatingTreeObserver;
11977    }
11978
11979    /**
11980     * <p>Finds the topmost view in the current view hierarchy.</p>
11981     *
11982     * @return the topmost view containing this view
11983     */
11984    public View getRootView() {
11985        if (mAttachInfo != null) {
11986            final View v = mAttachInfo.mRootView;
11987            if (v != null) {
11988                return v;
11989            }
11990        }
11991
11992        View parent = this;
11993
11994        while (parent.mParent != null && parent.mParent instanceof View) {
11995            parent = (View) parent.mParent;
11996        }
11997
11998        return parent;
11999    }
12000
12001    /**
12002     * <p>Computes the coordinates of this view on the screen. The argument
12003     * must be an array of two integers. After the method returns, the array
12004     * contains the x and y location in that order.</p>
12005     *
12006     * @param location an array of two integers in which to hold the coordinates
12007     */
12008    public void getLocationOnScreen(int[] location) {
12009        getLocationInWindow(location);
12010
12011        final AttachInfo info = mAttachInfo;
12012        if (info != null) {
12013            location[0] += info.mWindowLeft;
12014            location[1] += info.mWindowTop;
12015        }
12016    }
12017
12018    /**
12019     * <p>Computes the coordinates of this view in its window. The argument
12020     * must be an array of two integers. After the method returns, the array
12021     * contains the x and y location in that order.</p>
12022     *
12023     * @param location an array of two integers in which to hold the coordinates
12024     */
12025    public void getLocationInWindow(int[] location) {
12026        if (location == null || location.length < 2) {
12027            throw new IllegalArgumentException("location must be an array of "
12028                    + "two integers");
12029        }
12030
12031        location[0] = mLeft;
12032        location[1] = mTop;
12033        if (mTransformationInfo != null) {
12034            location[0] += (int) (mTransformationInfo.mTranslationX + 0.5f);
12035            location[1] += (int) (mTransformationInfo.mTranslationY + 0.5f);
12036        }
12037
12038        ViewParent viewParent = mParent;
12039        while (viewParent instanceof View) {
12040            final View view = (View)viewParent;
12041            location[0] += view.mLeft - view.mScrollX;
12042            location[1] += view.mTop - view.mScrollY;
12043            if (view.mTransformationInfo != null) {
12044                location[0] += (int) (view.mTransformationInfo.mTranslationX + 0.5f);
12045                location[1] += (int) (view.mTransformationInfo.mTranslationY + 0.5f);
12046            }
12047            viewParent = view.mParent;
12048        }
12049
12050        if (viewParent instanceof ViewRootImpl) {
12051            // *cough*
12052            final ViewRootImpl vr = (ViewRootImpl)viewParent;
12053            location[1] -= vr.mCurScrollY;
12054        }
12055    }
12056
12057    /**
12058     * {@hide}
12059     * @param id the id of the view to be found
12060     * @return the view of the specified id, null if cannot be found
12061     */
12062    protected View findViewTraversal(int id) {
12063        if (id == mID) {
12064            return this;
12065        }
12066        return null;
12067    }
12068
12069    /**
12070     * {@hide}
12071     * @param tag the tag of the view to be found
12072     * @return the view of specified tag, null if cannot be found
12073     */
12074    protected View findViewWithTagTraversal(Object tag) {
12075        if (tag != null && tag.equals(mTag)) {
12076            return this;
12077        }
12078        return null;
12079    }
12080
12081    /**
12082     * {@hide}
12083     * @param predicate The predicate to evaluate.
12084     * @param childToSkip If not null, ignores this child during the recursive traversal.
12085     * @return The first view that matches the predicate or null.
12086     */
12087    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12088        if (predicate.apply(this)) {
12089            return this;
12090        }
12091        return null;
12092    }
12093
12094    /**
12095     * Look for a child view with the given id.  If this view has the given
12096     * id, return this view.
12097     *
12098     * @param id The id to search for.
12099     * @return The view that has the given id in the hierarchy or null
12100     */
12101    public final View findViewById(int id) {
12102        if (id < 0) {
12103            return null;
12104        }
12105        return findViewTraversal(id);
12106    }
12107
12108    /**
12109     * Finds a view by its unuque and stable accessibility id.
12110     *
12111     * @param accessibilityId The searched accessibility id.
12112     * @return The found view.
12113     */
12114    final View findViewByAccessibilityId(int accessibilityId) {
12115        if (accessibilityId < 0) {
12116            return null;
12117        }
12118        return findViewByAccessibilityIdTraversal(accessibilityId);
12119    }
12120
12121    /**
12122     * Performs the traversal to find a view by its unuque and stable accessibility id.
12123     *
12124     * <strong>Note:</strong>This method does not stop at the root namespace
12125     * boundary since the user can touch the screen at an arbitrary location
12126     * potentially crossing the root namespace bounday which will send an
12127     * accessibility event to accessibility services and they should be able
12128     * to obtain the event source. Also accessibility ids are guaranteed to be
12129     * unique in the window.
12130     *
12131     * @param accessibilityId The accessibility id.
12132     * @return The found view.
12133     */
12134    View findViewByAccessibilityIdTraversal(int accessibilityId) {
12135        if (getAccessibilityViewId() == accessibilityId) {
12136            return this;
12137        }
12138        return null;
12139    }
12140
12141    /**
12142     * Look for a child view with the given tag.  If this view has the given
12143     * tag, return this view.
12144     *
12145     * @param tag The tag to search for, using "tag.equals(getTag())".
12146     * @return The View that has the given tag in the hierarchy or null
12147     */
12148    public final View findViewWithTag(Object tag) {
12149        if (tag == null) {
12150            return null;
12151        }
12152        return findViewWithTagTraversal(tag);
12153    }
12154
12155    /**
12156     * {@hide}
12157     * Look for a child view that matches the specified predicate.
12158     * If this view matches the predicate, return this view.
12159     *
12160     * @param predicate The predicate to evaluate.
12161     * @return The first view that matches the predicate or null.
12162     */
12163    public final View findViewByPredicate(Predicate<View> predicate) {
12164        return findViewByPredicateTraversal(predicate, null);
12165    }
12166
12167    /**
12168     * {@hide}
12169     * Look for a child view that matches the specified predicate,
12170     * starting with the specified view and its descendents and then
12171     * recusively searching the ancestors and siblings of that view
12172     * until this view is reached.
12173     *
12174     * This method is useful in cases where the predicate does not match
12175     * a single unique view (perhaps multiple views use the same id)
12176     * and we are trying to find the view that is "closest" in scope to the
12177     * starting view.
12178     *
12179     * @param start The view to start from.
12180     * @param predicate The predicate to evaluate.
12181     * @return The first view that matches the predicate or null.
12182     */
12183    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12184        View childToSkip = null;
12185        for (;;) {
12186            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12187            if (view != null || start == this) {
12188                return view;
12189            }
12190
12191            ViewParent parent = start.getParent();
12192            if (parent == null || !(parent instanceof View)) {
12193                return null;
12194            }
12195
12196            childToSkip = start;
12197            start = (View) parent;
12198        }
12199    }
12200
12201    /**
12202     * Sets the identifier for this view. The identifier does not have to be
12203     * unique in this view's hierarchy. The identifier should be a positive
12204     * number.
12205     *
12206     * @see #NO_ID
12207     * @see #getId()
12208     * @see #findViewById(int)
12209     *
12210     * @param id a number used to identify the view
12211     *
12212     * @attr ref android.R.styleable#View_id
12213     */
12214    public void setId(int id) {
12215        mID = id;
12216    }
12217
12218    /**
12219     * {@hide}
12220     *
12221     * @param isRoot true if the view belongs to the root namespace, false
12222     *        otherwise
12223     */
12224    public void setIsRootNamespace(boolean isRoot) {
12225        if (isRoot) {
12226            mPrivateFlags |= IS_ROOT_NAMESPACE;
12227        } else {
12228            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12229        }
12230    }
12231
12232    /**
12233     * {@hide}
12234     *
12235     * @return true if the view belongs to the root namespace, false otherwise
12236     */
12237    public boolean isRootNamespace() {
12238        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12239    }
12240
12241    /**
12242     * Returns this view's identifier.
12243     *
12244     * @return a positive integer used to identify the view or {@link #NO_ID}
12245     *         if the view has no ID
12246     *
12247     * @see #setId(int)
12248     * @see #findViewById(int)
12249     * @attr ref android.R.styleable#View_id
12250     */
12251    @ViewDebug.CapturedViewProperty
12252    public int getId() {
12253        return mID;
12254    }
12255
12256    /**
12257     * Returns this view's tag.
12258     *
12259     * @return the Object stored in this view as a tag
12260     *
12261     * @see #setTag(Object)
12262     * @see #getTag(int)
12263     */
12264    @ViewDebug.ExportedProperty
12265    public Object getTag() {
12266        return mTag;
12267    }
12268
12269    /**
12270     * Sets the tag associated with this view. A tag can be used to mark
12271     * a view in its hierarchy and does not have to be unique within the
12272     * hierarchy. Tags can also be used to store data within a view without
12273     * resorting to another data structure.
12274     *
12275     * @param tag an Object to tag the view with
12276     *
12277     * @see #getTag()
12278     * @see #setTag(int, Object)
12279     */
12280    public void setTag(final Object tag) {
12281        mTag = tag;
12282    }
12283
12284    /**
12285     * Returns the tag associated with this view and the specified key.
12286     *
12287     * @param key The key identifying the tag
12288     *
12289     * @return the Object stored in this view as a tag
12290     *
12291     * @see #setTag(int, Object)
12292     * @see #getTag()
12293     */
12294    public Object getTag(int key) {
12295        if (mKeyedTags != null) return mKeyedTags.get(key);
12296        return null;
12297    }
12298
12299    /**
12300     * Sets a tag associated with this view and a key. A tag can be used
12301     * to mark a view in its hierarchy and does not have to be unique within
12302     * the hierarchy. Tags can also be used to store data within a view
12303     * without resorting to another data structure.
12304     *
12305     * The specified key should be an id declared in the resources of the
12306     * application to ensure it is unique (see the <a
12307     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
12308     * Keys identified as belonging to
12309     * the Android framework or not associated with any package will cause
12310     * an {@link IllegalArgumentException} to be thrown.
12311     *
12312     * @param key The key identifying the tag
12313     * @param tag An Object to tag the view with
12314     *
12315     * @throws IllegalArgumentException If they specified key is not valid
12316     *
12317     * @see #setTag(Object)
12318     * @see #getTag(int)
12319     */
12320    public void setTag(int key, final Object tag) {
12321        // If the package id is 0x00 or 0x01, it's either an undefined package
12322        // or a framework id
12323        if ((key >>> 24) < 2) {
12324            throw new IllegalArgumentException("The key must be an application-specific "
12325                    + "resource id.");
12326        }
12327
12328        setKeyedTag(key, tag);
12329    }
12330
12331    /**
12332     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12333     * framework id.
12334     *
12335     * @hide
12336     */
12337    public void setTagInternal(int key, Object tag) {
12338        if ((key >>> 24) != 0x1) {
12339            throw new IllegalArgumentException("The key must be a framework-specific "
12340                    + "resource id.");
12341        }
12342
12343        setKeyedTag(key, tag);
12344    }
12345
12346    private void setKeyedTag(int key, Object tag) {
12347        if (mKeyedTags == null) {
12348            mKeyedTags = new SparseArray<Object>();
12349        }
12350
12351        mKeyedTags.put(key, tag);
12352    }
12353
12354    /**
12355     * @param consistency The type of consistency. See ViewDebug for more information.
12356     *
12357     * @hide
12358     */
12359    protected boolean dispatchConsistencyCheck(int consistency) {
12360        return onConsistencyCheck(consistency);
12361    }
12362
12363    /**
12364     * Method that subclasses should implement to check their consistency. The type of
12365     * consistency check is indicated by the bit field passed as a parameter.
12366     *
12367     * @param consistency The type of consistency. See ViewDebug for more information.
12368     *
12369     * @throws IllegalStateException if the view is in an inconsistent state.
12370     *
12371     * @hide
12372     */
12373    protected boolean onConsistencyCheck(int consistency) {
12374        boolean result = true;
12375
12376        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12377        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12378
12379        if (checkLayout) {
12380            if (getParent() == null) {
12381                result = false;
12382                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12383                        "View " + this + " does not have a parent.");
12384            }
12385
12386            if (mAttachInfo == null) {
12387                result = false;
12388                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12389                        "View " + this + " is not attached to a window.");
12390            }
12391        }
12392
12393        if (checkDrawing) {
12394            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12395            // from their draw() method
12396
12397            if ((mPrivateFlags & DRAWN) != DRAWN &&
12398                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12399                result = false;
12400                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12401                        "View " + this + " was invalidated but its drawing cache is valid.");
12402            }
12403        }
12404
12405        return result;
12406    }
12407
12408    /**
12409     * Prints information about this view in the log output, with the tag
12410     * {@link #VIEW_LOG_TAG}.
12411     *
12412     * @hide
12413     */
12414    public void debug() {
12415        debug(0);
12416    }
12417
12418    /**
12419     * Prints information about this view in the log output, with the tag
12420     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12421     * indentation defined by the <code>depth</code>.
12422     *
12423     * @param depth the indentation level
12424     *
12425     * @hide
12426     */
12427    protected void debug(int depth) {
12428        String output = debugIndent(depth - 1);
12429
12430        output += "+ " + this;
12431        int id = getId();
12432        if (id != -1) {
12433            output += " (id=" + id + ")";
12434        }
12435        Object tag = getTag();
12436        if (tag != null) {
12437            output += " (tag=" + tag + ")";
12438        }
12439        Log.d(VIEW_LOG_TAG, output);
12440
12441        if ((mPrivateFlags & FOCUSED) != 0) {
12442            output = debugIndent(depth) + " FOCUSED";
12443            Log.d(VIEW_LOG_TAG, output);
12444        }
12445
12446        output = debugIndent(depth);
12447        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12448                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12449                + "} ";
12450        Log.d(VIEW_LOG_TAG, output);
12451
12452        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12453                || mPaddingBottom != 0) {
12454            output = debugIndent(depth);
12455            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12456                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12457            Log.d(VIEW_LOG_TAG, output);
12458        }
12459
12460        output = debugIndent(depth);
12461        output += "mMeasureWidth=" + mMeasuredWidth +
12462                " mMeasureHeight=" + mMeasuredHeight;
12463        Log.d(VIEW_LOG_TAG, output);
12464
12465        output = debugIndent(depth);
12466        if (mLayoutParams == null) {
12467            output += "BAD! no layout params";
12468        } else {
12469            output = mLayoutParams.debug(output);
12470        }
12471        Log.d(VIEW_LOG_TAG, output);
12472
12473        output = debugIndent(depth);
12474        output += "flags={";
12475        output += View.printFlags(mViewFlags);
12476        output += "}";
12477        Log.d(VIEW_LOG_TAG, output);
12478
12479        output = debugIndent(depth);
12480        output += "privateFlags={";
12481        output += View.printPrivateFlags(mPrivateFlags);
12482        output += "}";
12483        Log.d(VIEW_LOG_TAG, output);
12484    }
12485
12486    /**
12487     * Creates an string of whitespaces used for indentation.
12488     *
12489     * @param depth the indentation level
12490     * @return a String containing (depth * 2 + 3) * 2 white spaces
12491     *
12492     * @hide
12493     */
12494    protected static String debugIndent(int depth) {
12495        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12496        for (int i = 0; i < (depth * 2) + 3; i++) {
12497            spaces.append(' ').append(' ');
12498        }
12499        return spaces.toString();
12500    }
12501
12502    /**
12503     * <p>Return the offset of the widget's text baseline from the widget's top
12504     * boundary. If this widget does not support baseline alignment, this
12505     * method returns -1. </p>
12506     *
12507     * @return the offset of the baseline within the widget's bounds or -1
12508     *         if baseline alignment is not supported
12509     */
12510    @ViewDebug.ExportedProperty(category = "layout")
12511    public int getBaseline() {
12512        return -1;
12513    }
12514
12515    /**
12516     * Call this when something has changed which has invalidated the
12517     * layout of this view. This will schedule a layout pass of the view
12518     * tree.
12519     */
12520    public void requestLayout() {
12521        if (ViewDebug.TRACE_HIERARCHY) {
12522            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
12523        }
12524
12525        mPrivateFlags |= FORCE_LAYOUT;
12526        mPrivateFlags |= INVALIDATED;
12527
12528        if (mParent != null) {
12529            if (mLayoutParams != null) {
12530                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
12531            }
12532            if (!mParent.isLayoutRequested()) {
12533                mParent.requestLayout();
12534            }
12535        }
12536    }
12537
12538    /**
12539     * Forces this view to be laid out during the next layout pass.
12540     * This method does not call requestLayout() or forceLayout()
12541     * on the parent.
12542     */
12543    public void forceLayout() {
12544        mPrivateFlags |= FORCE_LAYOUT;
12545        mPrivateFlags |= INVALIDATED;
12546    }
12547
12548    /**
12549     * <p>
12550     * This is called to find out how big a view should be. The parent
12551     * supplies constraint information in the width and height parameters.
12552     * </p>
12553     *
12554     * <p>
12555     * The actual mesurement work of a view is performed in
12556     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
12557     * {@link #onMeasure(int, int)} can and must be overriden by subclasses.
12558     * </p>
12559     *
12560     *
12561     * @param widthMeasureSpec Horizontal space requirements as imposed by the
12562     *        parent
12563     * @param heightMeasureSpec Vertical space requirements as imposed by the
12564     *        parent
12565     *
12566     * @see #onMeasure(int, int)
12567     */
12568    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
12569        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
12570                widthMeasureSpec != mOldWidthMeasureSpec ||
12571                heightMeasureSpec != mOldHeightMeasureSpec) {
12572
12573            // first clears the measured dimension flag
12574            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
12575
12576            if (ViewDebug.TRACE_HIERARCHY) {
12577                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
12578            }
12579
12580            // measure ourselves, this should set the measured dimension flag back
12581            onMeasure(widthMeasureSpec, heightMeasureSpec);
12582
12583            // flag not set, setMeasuredDimension() was not invoked, we raise
12584            // an exception to warn the developer
12585            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
12586                throw new IllegalStateException("onMeasure() did not set the"
12587                        + " measured dimension by calling"
12588                        + " setMeasuredDimension()");
12589            }
12590
12591            mPrivateFlags |= LAYOUT_REQUIRED;
12592        }
12593
12594        mOldWidthMeasureSpec = widthMeasureSpec;
12595        mOldHeightMeasureSpec = heightMeasureSpec;
12596    }
12597
12598    /**
12599     * <p>
12600     * Measure the view and its content to determine the measured width and the
12601     * measured height. This method is invoked by {@link #measure(int, int)} and
12602     * should be overriden by subclasses to provide accurate and efficient
12603     * measurement of their contents.
12604     * </p>
12605     *
12606     * <p>
12607     * <strong>CONTRACT:</strong> When overriding this method, you
12608     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
12609     * measured width and height of this view. Failure to do so will trigger an
12610     * <code>IllegalStateException</code>, thrown by
12611     * {@link #measure(int, int)}. Calling the superclass'
12612     * {@link #onMeasure(int, int)} is a valid use.
12613     * </p>
12614     *
12615     * <p>
12616     * The base class implementation of measure defaults to the background size,
12617     * unless a larger size is allowed by the MeasureSpec. Subclasses should
12618     * override {@link #onMeasure(int, int)} to provide better measurements of
12619     * their content.
12620     * </p>
12621     *
12622     * <p>
12623     * If this method is overridden, it is the subclass's responsibility to make
12624     * sure the measured height and width are at least the view's minimum height
12625     * and width ({@link #getSuggestedMinimumHeight()} and
12626     * {@link #getSuggestedMinimumWidth()}).
12627     * </p>
12628     *
12629     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
12630     *                         The requirements are encoded with
12631     *                         {@link android.view.View.MeasureSpec}.
12632     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
12633     *                         The requirements are encoded with
12634     *                         {@link android.view.View.MeasureSpec}.
12635     *
12636     * @see #getMeasuredWidth()
12637     * @see #getMeasuredHeight()
12638     * @see #setMeasuredDimension(int, int)
12639     * @see #getSuggestedMinimumHeight()
12640     * @see #getSuggestedMinimumWidth()
12641     * @see android.view.View.MeasureSpec#getMode(int)
12642     * @see android.view.View.MeasureSpec#getSize(int)
12643     */
12644    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12645        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
12646                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
12647    }
12648
12649    /**
12650     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
12651     * measured width and measured height. Failing to do so will trigger an
12652     * exception at measurement time.</p>
12653     *
12654     * @param measuredWidth The measured width of this view.  May be a complex
12655     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12656     * {@link #MEASURED_STATE_TOO_SMALL}.
12657     * @param measuredHeight The measured height of this view.  May be a complex
12658     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
12659     * {@link #MEASURED_STATE_TOO_SMALL}.
12660     */
12661    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
12662        mMeasuredWidth = measuredWidth;
12663        mMeasuredHeight = measuredHeight;
12664
12665        mPrivateFlags |= MEASURED_DIMENSION_SET;
12666    }
12667
12668    /**
12669     * Merge two states as returned by {@link #getMeasuredState()}.
12670     * @param curState The current state as returned from a view or the result
12671     * of combining multiple views.
12672     * @param newState The new view state to combine.
12673     * @return Returns a new integer reflecting the combination of the two
12674     * states.
12675     */
12676    public static int combineMeasuredStates(int curState, int newState) {
12677        return curState | newState;
12678    }
12679
12680    /**
12681     * Version of {@link #resolveSizeAndState(int, int, int)}
12682     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
12683     */
12684    public static int resolveSize(int size, int measureSpec) {
12685        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
12686    }
12687
12688    /**
12689     * Utility to reconcile a desired size and state, with constraints imposed
12690     * by a MeasureSpec.  Will take the desired size, unless a different size
12691     * is imposed by the constraints.  The returned value is a compound integer,
12692     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
12693     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
12694     * size is smaller than the size the view wants to be.
12695     *
12696     * @param size How big the view wants to be
12697     * @param measureSpec Constraints imposed by the parent
12698     * @return Size information bit mask as defined by
12699     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
12700     */
12701    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
12702        int result = size;
12703        int specMode = MeasureSpec.getMode(measureSpec);
12704        int specSize =  MeasureSpec.getSize(measureSpec);
12705        switch (specMode) {
12706        case MeasureSpec.UNSPECIFIED:
12707            result = size;
12708            break;
12709        case MeasureSpec.AT_MOST:
12710            if (specSize < size) {
12711                result = specSize | MEASURED_STATE_TOO_SMALL;
12712            } else {
12713                result = size;
12714            }
12715            break;
12716        case MeasureSpec.EXACTLY:
12717            result = specSize;
12718            break;
12719        }
12720        return result | (childMeasuredState&MEASURED_STATE_MASK);
12721    }
12722
12723    /**
12724     * Utility to return a default size. Uses the supplied size if the
12725     * MeasureSpec imposed no constraints. Will get larger if allowed
12726     * by the MeasureSpec.
12727     *
12728     * @param size Default size for this view
12729     * @param measureSpec Constraints imposed by the parent
12730     * @return The size this view should be.
12731     */
12732    public static int getDefaultSize(int size, int measureSpec) {
12733        int result = size;
12734        int specMode = MeasureSpec.getMode(measureSpec);
12735        int specSize = MeasureSpec.getSize(measureSpec);
12736
12737        switch (specMode) {
12738        case MeasureSpec.UNSPECIFIED:
12739            result = size;
12740            break;
12741        case MeasureSpec.AT_MOST:
12742        case MeasureSpec.EXACTLY:
12743            result = specSize;
12744            break;
12745        }
12746        return result;
12747    }
12748
12749    /**
12750     * Returns the suggested minimum height that the view should use. This
12751     * returns the maximum of the view's minimum height
12752     * and the background's minimum height
12753     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
12754     * <p>
12755     * When being used in {@link #onMeasure(int, int)}, the caller should still
12756     * ensure the returned height is within the requirements of the parent.
12757     *
12758     * @return The suggested minimum height of the view.
12759     */
12760    protected int getSuggestedMinimumHeight() {
12761        int suggestedMinHeight = mMinHeight;
12762
12763        if (mBGDrawable != null) {
12764            final int bgMinHeight = mBGDrawable.getMinimumHeight();
12765            if (suggestedMinHeight < bgMinHeight) {
12766                suggestedMinHeight = bgMinHeight;
12767            }
12768        }
12769
12770        return suggestedMinHeight;
12771    }
12772
12773    /**
12774     * Returns the suggested minimum width that the view should use. This
12775     * returns the maximum of the view's minimum width)
12776     * and the background's minimum width
12777     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
12778     * <p>
12779     * When being used in {@link #onMeasure(int, int)}, the caller should still
12780     * ensure the returned width is within the requirements of the parent.
12781     *
12782     * @return The suggested minimum width of the view.
12783     */
12784    protected int getSuggestedMinimumWidth() {
12785        int suggestedMinWidth = mMinWidth;
12786
12787        if (mBGDrawable != null) {
12788            final int bgMinWidth = mBGDrawable.getMinimumWidth();
12789            if (suggestedMinWidth < bgMinWidth) {
12790                suggestedMinWidth = bgMinWidth;
12791            }
12792        }
12793
12794        return suggestedMinWidth;
12795    }
12796
12797    /**
12798     * Sets the minimum height of the view. It is not guaranteed the view will
12799     * be able to achieve this minimum height (for example, if its parent layout
12800     * constrains it with less available height).
12801     *
12802     * @param minHeight The minimum height the view will try to be.
12803     */
12804    public void setMinimumHeight(int minHeight) {
12805        mMinHeight = minHeight;
12806    }
12807
12808    /**
12809     * Sets the minimum width of the view. It is not guaranteed the view will
12810     * be able to achieve this minimum width (for example, if its parent layout
12811     * constrains it with less available width).
12812     *
12813     * @param minWidth The minimum width the view will try to be.
12814     */
12815    public void setMinimumWidth(int minWidth) {
12816        mMinWidth = minWidth;
12817    }
12818
12819    /**
12820     * Get the animation currently associated with this view.
12821     *
12822     * @return The animation that is currently playing or
12823     *         scheduled to play for this view.
12824     */
12825    public Animation getAnimation() {
12826        return mCurrentAnimation;
12827    }
12828
12829    /**
12830     * Start the specified animation now.
12831     *
12832     * @param animation the animation to start now
12833     */
12834    public void startAnimation(Animation animation) {
12835        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
12836        setAnimation(animation);
12837        invalidateParentCaches();
12838        invalidate(true);
12839    }
12840
12841    /**
12842     * Cancels any animations for this view.
12843     */
12844    public void clearAnimation() {
12845        if (mCurrentAnimation != null) {
12846            mCurrentAnimation.detach();
12847        }
12848        mCurrentAnimation = null;
12849        invalidateParentIfNeeded();
12850    }
12851
12852    /**
12853     * Sets the next animation to play for this view.
12854     * If you want the animation to play immediately, use
12855     * startAnimation. This method provides allows fine-grained
12856     * control over the start time and invalidation, but you
12857     * must make sure that 1) the animation has a start time set, and
12858     * 2) the view will be invalidated when the animation is supposed to
12859     * start.
12860     *
12861     * @param animation The next animation, or null.
12862     */
12863    public void setAnimation(Animation animation) {
12864        mCurrentAnimation = animation;
12865        if (animation != null) {
12866            animation.reset();
12867        }
12868    }
12869
12870    /**
12871     * Invoked by a parent ViewGroup to notify the start of the animation
12872     * currently associated with this view. If you override this method,
12873     * always call super.onAnimationStart();
12874     *
12875     * @see #setAnimation(android.view.animation.Animation)
12876     * @see #getAnimation()
12877     */
12878    protected void onAnimationStart() {
12879        mPrivateFlags |= ANIMATION_STARTED;
12880    }
12881
12882    /**
12883     * Invoked by a parent ViewGroup to notify the end of the animation
12884     * currently associated with this view. If you override this method,
12885     * always call super.onAnimationEnd();
12886     *
12887     * @see #setAnimation(android.view.animation.Animation)
12888     * @see #getAnimation()
12889     */
12890    protected void onAnimationEnd() {
12891        mPrivateFlags &= ~ANIMATION_STARTED;
12892    }
12893
12894    /**
12895     * Invoked if there is a Transform that involves alpha. Subclass that can
12896     * draw themselves with the specified alpha should return true, and then
12897     * respect that alpha when their onDraw() is called. If this returns false
12898     * then the view may be redirected to draw into an offscreen buffer to
12899     * fulfill the request, which will look fine, but may be slower than if the
12900     * subclass handles it internally. The default implementation returns false.
12901     *
12902     * @param alpha The alpha (0..255) to apply to the view's drawing
12903     * @return true if the view can draw with the specified alpha.
12904     */
12905    protected boolean onSetAlpha(int alpha) {
12906        return false;
12907    }
12908
12909    /**
12910     * This is used by the RootView to perform an optimization when
12911     * the view hierarchy contains one or several SurfaceView.
12912     * SurfaceView is always considered transparent, but its children are not,
12913     * therefore all View objects remove themselves from the global transparent
12914     * region (passed as a parameter to this function).
12915     *
12916     * @param region The transparent region for this ViewAncestor (window).
12917     *
12918     * @return Returns true if the effective visibility of the view at this
12919     * point is opaque, regardless of the transparent region; returns false
12920     * if it is possible for underlying windows to be seen behind the view.
12921     *
12922     * {@hide}
12923     */
12924    public boolean gatherTransparentRegion(Region region) {
12925        final AttachInfo attachInfo = mAttachInfo;
12926        if (region != null && attachInfo != null) {
12927            final int pflags = mPrivateFlags;
12928            if ((pflags & SKIP_DRAW) == 0) {
12929                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
12930                // remove it from the transparent region.
12931                final int[] location = attachInfo.mTransparentLocation;
12932                getLocationInWindow(location);
12933                region.op(location[0], location[1], location[0] + mRight - mLeft,
12934                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
12935            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
12936                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
12937                // exists, so we remove the background drawable's non-transparent
12938                // parts from this transparent region.
12939                applyDrawableToTransparentRegion(mBGDrawable, region);
12940            }
12941        }
12942        return true;
12943    }
12944
12945    /**
12946     * Play a sound effect for this view.
12947     *
12948     * <p>The framework will play sound effects for some built in actions, such as
12949     * clicking, but you may wish to play these effects in your widget,
12950     * for instance, for internal navigation.
12951     *
12952     * <p>The sound effect will only be played if sound effects are enabled by the user, and
12953     * {@link #isSoundEffectsEnabled()} is true.
12954     *
12955     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
12956     */
12957    public void playSoundEffect(int soundConstant) {
12958        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
12959            return;
12960        }
12961        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
12962    }
12963
12964    /**
12965     * BZZZTT!!1!
12966     *
12967     * <p>Provide haptic feedback to the user for this view.
12968     *
12969     * <p>The framework will provide haptic feedback for some built in actions,
12970     * such as long presses, but you may wish to provide feedback for your
12971     * own widget.
12972     *
12973     * <p>The feedback will only be performed if
12974     * {@link #isHapticFeedbackEnabled()} is true.
12975     *
12976     * @param feedbackConstant One of the constants defined in
12977     * {@link HapticFeedbackConstants}
12978     */
12979    public boolean performHapticFeedback(int feedbackConstant) {
12980        return performHapticFeedback(feedbackConstant, 0);
12981    }
12982
12983    /**
12984     * BZZZTT!!1!
12985     *
12986     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
12987     *
12988     * @param feedbackConstant One of the constants defined in
12989     * {@link HapticFeedbackConstants}
12990     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
12991     */
12992    public boolean performHapticFeedback(int feedbackConstant, int flags) {
12993        if (mAttachInfo == null) {
12994            return false;
12995        }
12996        //noinspection SimplifiableIfStatement
12997        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
12998                && !isHapticFeedbackEnabled()) {
12999            return false;
13000        }
13001        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13002                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13003    }
13004
13005    /**
13006     * Request that the visibility of the status bar be changed.
13007     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13008     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13009     */
13010    public void setSystemUiVisibility(int visibility) {
13011        if (visibility != mSystemUiVisibility) {
13012            mSystemUiVisibility = visibility;
13013            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13014                mParent.recomputeViewAttributes(this);
13015            }
13016        }
13017    }
13018
13019    /**
13020     * Returns the status bar visibility that this view has requested.
13021     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13022     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13023     */
13024    public int getSystemUiVisibility() {
13025        return mSystemUiVisibility;
13026    }
13027
13028    /**
13029     * Set a listener to receive callbacks when the visibility of the system bar changes.
13030     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13031     */
13032    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13033        mOnSystemUiVisibilityChangeListener = l;
13034        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13035            mParent.recomputeViewAttributes(this);
13036        }
13037    }
13038
13039    /**
13040     */
13041    public void dispatchSystemUiVisibilityChanged(int visibility) {
13042        if (mOnSystemUiVisibilityChangeListener != null) {
13043            mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13044                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13045        }
13046    }
13047
13048    /**
13049     * Creates an image that the system displays during the drag and drop
13050     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13051     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13052     * appearance as the given View. The default also positions the center of the drag shadow
13053     * directly under the touch point. If no View is provided (the constructor with no parameters
13054     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13055     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13056     * default is an invisible drag shadow.
13057     * <p>
13058     * You are not required to use the View you provide to the constructor as the basis of the
13059     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13060     * anything you want as the drag shadow.
13061     * </p>
13062     * <p>
13063     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13064     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13065     *  size and position of the drag shadow. It uses this data to construct a
13066     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13067     *  so that your application can draw the shadow image in the Canvas.
13068     * </p>
13069     */
13070    public static class DragShadowBuilder {
13071        private final WeakReference<View> mView;
13072
13073        /**
13074         * Constructs a shadow image builder based on a View. By default, the resulting drag
13075         * shadow will have the same appearance and dimensions as the View, with the touch point
13076         * over the center of the View.
13077         * @param view A View. Any View in scope can be used.
13078         */
13079        public DragShadowBuilder(View view) {
13080            mView = new WeakReference<View>(view);
13081        }
13082
13083        /**
13084         * Construct a shadow builder object with no associated View.  This
13085         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13086         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13087         * to supply the drag shadow's dimensions and appearance without
13088         * reference to any View object. If they are not overridden, then the result is an
13089         * invisible drag shadow.
13090         */
13091        public DragShadowBuilder() {
13092            mView = new WeakReference<View>(null);
13093        }
13094
13095        /**
13096         * Returns the View object that had been passed to the
13097         * {@link #View.DragShadowBuilder(View)}
13098         * constructor.  If that View parameter was {@code null} or if the
13099         * {@link #View.DragShadowBuilder()}
13100         * constructor was used to instantiate the builder object, this method will return
13101         * null.
13102         *
13103         * @return The View object associate with this builder object.
13104         */
13105        @SuppressWarnings({"JavadocReference"})
13106        final public View getView() {
13107            return mView.get();
13108        }
13109
13110        /**
13111         * Provides the metrics for the shadow image. These include the dimensions of
13112         * the shadow image, and the point within that shadow that should
13113         * be centered under the touch location while dragging.
13114         * <p>
13115         * The default implementation sets the dimensions of the shadow to be the
13116         * same as the dimensions of the View itself and centers the shadow under
13117         * the touch point.
13118         * </p>
13119         *
13120         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13121         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13122         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13123         * image.
13124         *
13125         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13126         * shadow image that should be underneath the touch point during the drag and drop
13127         * operation. Your application must set {@link android.graphics.Point#x} to the
13128         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13129         */
13130        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13131            final View view = mView.get();
13132            if (view != null) {
13133                shadowSize.set(view.getWidth(), view.getHeight());
13134                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13135            } else {
13136                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13137            }
13138        }
13139
13140        /**
13141         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13142         * based on the dimensions it received from the
13143         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13144         *
13145         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13146         */
13147        public void onDrawShadow(Canvas canvas) {
13148            final View view = mView.get();
13149            if (view != null) {
13150                view.draw(canvas);
13151            } else {
13152                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13153            }
13154        }
13155    }
13156
13157    /**
13158     * Starts a drag and drop operation. When your application calls this method, it passes a
13159     * {@link android.view.View.DragShadowBuilder} object to the system. The
13160     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13161     * to get metrics for the drag shadow, and then calls the object's
13162     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13163     * <p>
13164     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13165     *  drag events to all the View objects in your application that are currently visible. It does
13166     *  this either by calling the View object's drag listener (an implementation of
13167     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13168     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13169     *  Both are passed a {@link android.view.DragEvent} object that has a
13170     *  {@link android.view.DragEvent#getAction()} value of
13171     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13172     * </p>
13173     * <p>
13174     * Your application can invoke startDrag() on any attached View object. The View object does not
13175     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13176     * be related to the View the user selected for dragging.
13177     * </p>
13178     * @param data A {@link android.content.ClipData} object pointing to the data to be
13179     * transferred by the drag and drop operation.
13180     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13181     * drag shadow.
13182     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13183     * drop operation. This Object is put into every DragEvent object sent by the system during the
13184     * current drag.
13185     * <p>
13186     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13187     * to the target Views. For example, it can contain flags that differentiate between a
13188     * a copy operation and a move operation.
13189     * </p>
13190     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13191     * so the parameter should be set to 0.
13192     * @return {@code true} if the method completes successfully, or
13193     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13194     * do a drag, and so no drag operation is in progress.
13195     */
13196    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13197            Object myLocalState, int flags) {
13198        if (ViewDebug.DEBUG_DRAG) {
13199            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13200        }
13201        boolean okay = false;
13202
13203        Point shadowSize = new Point();
13204        Point shadowTouchPoint = new Point();
13205        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13206
13207        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13208                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13209            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13210        }
13211
13212        if (ViewDebug.DEBUG_DRAG) {
13213            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13214                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13215        }
13216        Surface surface = new Surface();
13217        try {
13218            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13219                    flags, shadowSize.x, shadowSize.y, surface);
13220            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13221                    + " surface=" + surface);
13222            if (token != null) {
13223                Canvas canvas = surface.lockCanvas(null);
13224                try {
13225                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13226                    shadowBuilder.onDrawShadow(canvas);
13227                } finally {
13228                    surface.unlockCanvasAndPost(canvas);
13229                }
13230
13231                final ViewRootImpl root = getViewRootImpl();
13232
13233                // Cache the local state object for delivery with DragEvents
13234                root.setLocalDragState(myLocalState);
13235
13236                // repurpose 'shadowSize' for the last touch point
13237                root.getLastTouchPoint(shadowSize);
13238
13239                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13240                        shadowSize.x, shadowSize.y,
13241                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13242                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13243
13244                // Off and running!  Release our local surface instance; the drag
13245                // shadow surface is now managed by the system process.
13246                surface.release();
13247            }
13248        } catch (Exception e) {
13249            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13250            surface.destroy();
13251        }
13252
13253        return okay;
13254    }
13255
13256    /**
13257     * Handles drag events sent by the system following a call to
13258     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13259     *<p>
13260     * When the system calls this method, it passes a
13261     * {@link android.view.DragEvent} object. A call to
13262     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13263     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13264     * operation.
13265     * @param event The {@link android.view.DragEvent} sent by the system.
13266     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13267     * in DragEvent, indicating the type of drag event represented by this object.
13268     * @return {@code true} if the method was successful, otherwise {@code false}.
13269     * <p>
13270     *  The method should return {@code true} in response to an action type of
13271     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13272     *  operation.
13273     * </p>
13274     * <p>
13275     *  The method should also return {@code true} in response to an action type of
13276     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13277     *  {@code false} if it didn't.
13278     * </p>
13279     */
13280    public boolean onDragEvent(DragEvent event) {
13281        return false;
13282    }
13283
13284    /**
13285     * Detects if this View is enabled and has a drag event listener.
13286     * If both are true, then it calls the drag event listener with the
13287     * {@link android.view.DragEvent} it received. If the drag event listener returns
13288     * {@code true}, then dispatchDragEvent() returns {@code true}.
13289     * <p>
13290     * For all other cases, the method calls the
13291     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
13292     * method and returns its result.
13293     * </p>
13294     * <p>
13295     * This ensures that a drag event is always consumed, even if the View does not have a drag
13296     * event listener. However, if the View has a listener and the listener returns true, then
13297     * onDragEvent() is not called.
13298     * </p>
13299     */
13300    public boolean dispatchDragEvent(DragEvent event) {
13301        //noinspection SimplifiableIfStatement
13302        if (mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
13303                && mOnDragListener.onDrag(this, event)) {
13304            return true;
13305        }
13306        return onDragEvent(event);
13307    }
13308
13309    boolean canAcceptDrag() {
13310        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13311    }
13312
13313    /**
13314     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13315     * it is ever exposed at all.
13316     * @hide
13317     */
13318    public void onCloseSystemDialogs(String reason) {
13319    }
13320
13321    /**
13322     * Given a Drawable whose bounds have been set to draw into this view,
13323     * update a Region being computed for
13324     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13325     * that any non-transparent parts of the Drawable are removed from the
13326     * given transparent region.
13327     *
13328     * @param dr The Drawable whose transparency is to be applied to the region.
13329     * @param region A Region holding the current transparency information,
13330     * where any parts of the region that are set are considered to be
13331     * transparent.  On return, this region will be modified to have the
13332     * transparency information reduced by the corresponding parts of the
13333     * Drawable that are not transparent.
13334     * {@hide}
13335     */
13336    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13337        if (DBG) {
13338            Log.i("View", "Getting transparent region for: " + this);
13339        }
13340        final Region r = dr.getTransparentRegion();
13341        final Rect db = dr.getBounds();
13342        final AttachInfo attachInfo = mAttachInfo;
13343        if (r != null && attachInfo != null) {
13344            final int w = getRight()-getLeft();
13345            final int h = getBottom()-getTop();
13346            if (db.left > 0) {
13347                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13348                r.op(0, 0, db.left, h, Region.Op.UNION);
13349            }
13350            if (db.right < w) {
13351                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13352                r.op(db.right, 0, w, h, Region.Op.UNION);
13353            }
13354            if (db.top > 0) {
13355                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13356                r.op(0, 0, w, db.top, Region.Op.UNION);
13357            }
13358            if (db.bottom < h) {
13359                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13360                r.op(0, db.bottom, w, h, Region.Op.UNION);
13361            }
13362            final int[] location = attachInfo.mTransparentLocation;
13363            getLocationInWindow(location);
13364            r.translate(location[0], location[1]);
13365            region.op(r, Region.Op.INTERSECT);
13366        } else {
13367            region.op(db, Region.Op.DIFFERENCE);
13368        }
13369    }
13370
13371    private void checkForLongClick(int delayOffset) {
13372        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13373            mHasPerformedLongPress = false;
13374
13375            if (mPendingCheckForLongPress == null) {
13376                mPendingCheckForLongPress = new CheckForLongPress();
13377            }
13378            mPendingCheckForLongPress.rememberWindowAttachCount();
13379            postDelayed(mPendingCheckForLongPress,
13380                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13381        }
13382    }
13383
13384    /**
13385     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13386     * LayoutInflater} class, which provides a full range of options for view inflation.
13387     *
13388     * @param context The Context object for your activity or application.
13389     * @param resource The resource ID to inflate
13390     * @param root A view group that will be the parent.  Used to properly inflate the
13391     * layout_* parameters.
13392     * @see LayoutInflater
13393     */
13394    public static View inflate(Context context, int resource, ViewGroup root) {
13395        LayoutInflater factory = LayoutInflater.from(context);
13396        return factory.inflate(resource, root);
13397    }
13398
13399    /**
13400     * Scroll the view with standard behavior for scrolling beyond the normal
13401     * content boundaries. Views that call this method should override
13402     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13403     * results of an over-scroll operation.
13404     *
13405     * Views can use this method to handle any touch or fling-based scrolling.
13406     *
13407     * @param deltaX Change in X in pixels
13408     * @param deltaY Change in Y in pixels
13409     * @param scrollX Current X scroll value in pixels before applying deltaX
13410     * @param scrollY Current Y scroll value in pixels before applying deltaY
13411     * @param scrollRangeX Maximum content scroll range along the X axis
13412     * @param scrollRangeY Maximum content scroll range along the Y axis
13413     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13414     *          along the X axis.
13415     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13416     *          along the Y axis.
13417     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13418     * @return true if scrolling was clamped to an over-scroll boundary along either
13419     *          axis, false otherwise.
13420     */
13421    @SuppressWarnings({"UnusedParameters"})
13422    protected boolean overScrollBy(int deltaX, int deltaY,
13423            int scrollX, int scrollY,
13424            int scrollRangeX, int scrollRangeY,
13425            int maxOverScrollX, int maxOverScrollY,
13426            boolean isTouchEvent) {
13427        final int overScrollMode = mOverScrollMode;
13428        final boolean canScrollHorizontal =
13429                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13430        final boolean canScrollVertical =
13431                computeVerticalScrollRange() > computeVerticalScrollExtent();
13432        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13433                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13434        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13435                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13436
13437        int newScrollX = scrollX + deltaX;
13438        if (!overScrollHorizontal) {
13439            maxOverScrollX = 0;
13440        }
13441
13442        int newScrollY = scrollY + deltaY;
13443        if (!overScrollVertical) {
13444            maxOverScrollY = 0;
13445        }
13446
13447        // Clamp values if at the limits and record
13448        final int left = -maxOverScrollX;
13449        final int right = maxOverScrollX + scrollRangeX;
13450        final int top = -maxOverScrollY;
13451        final int bottom = maxOverScrollY + scrollRangeY;
13452
13453        boolean clampedX = false;
13454        if (newScrollX > right) {
13455            newScrollX = right;
13456            clampedX = true;
13457        } else if (newScrollX < left) {
13458            newScrollX = left;
13459            clampedX = true;
13460        }
13461
13462        boolean clampedY = false;
13463        if (newScrollY > bottom) {
13464            newScrollY = bottom;
13465            clampedY = true;
13466        } else if (newScrollY < top) {
13467            newScrollY = top;
13468            clampedY = true;
13469        }
13470
13471        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13472
13473        return clampedX || clampedY;
13474    }
13475
13476    /**
13477     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13478     * respond to the results of an over-scroll operation.
13479     *
13480     * @param scrollX New X scroll value in pixels
13481     * @param scrollY New Y scroll value in pixels
13482     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13483     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13484     */
13485    protected void onOverScrolled(int scrollX, int scrollY,
13486            boolean clampedX, boolean clampedY) {
13487        // Intentionally empty.
13488    }
13489
13490    /**
13491     * Returns the over-scroll mode for this view. The result will be
13492     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13493     * (allow over-scrolling only if the view content is larger than the container),
13494     * or {@link #OVER_SCROLL_NEVER}.
13495     *
13496     * @return This view's over-scroll mode.
13497     */
13498    public int getOverScrollMode() {
13499        return mOverScrollMode;
13500    }
13501
13502    /**
13503     * Set the over-scroll mode for this view. Valid over-scroll modes are
13504     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
13505     * (allow over-scrolling only if the view content is larger than the container),
13506     * or {@link #OVER_SCROLL_NEVER}.
13507     *
13508     * Setting the over-scroll mode of a view will have an effect only if the
13509     * view is capable of scrolling.
13510     *
13511     * @param overScrollMode The new over-scroll mode for this view.
13512     */
13513    public void setOverScrollMode(int overScrollMode) {
13514        if (overScrollMode != OVER_SCROLL_ALWAYS &&
13515                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
13516                overScrollMode != OVER_SCROLL_NEVER) {
13517            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
13518        }
13519        mOverScrollMode = overScrollMode;
13520    }
13521
13522    /**
13523     * Gets a scale factor that determines the distance the view should scroll
13524     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
13525     * @return The vertical scroll scale factor.
13526     * @hide
13527     */
13528    protected float getVerticalScrollFactor() {
13529        if (mVerticalScrollFactor == 0) {
13530            TypedValue outValue = new TypedValue();
13531            if (!mContext.getTheme().resolveAttribute(
13532                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
13533                throw new IllegalStateException(
13534                        "Expected theme to define listPreferredItemHeight.");
13535            }
13536            mVerticalScrollFactor = outValue.getDimension(
13537                    mContext.getResources().getDisplayMetrics());
13538        }
13539        return mVerticalScrollFactor;
13540    }
13541
13542    /**
13543     * Gets a scale factor that determines the distance the view should scroll
13544     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
13545     * @return The horizontal scroll scale factor.
13546     * @hide
13547     */
13548    protected float getHorizontalScrollFactor() {
13549        // TODO: Should use something else.
13550        return getVerticalScrollFactor();
13551    }
13552
13553    /**
13554     * Return the value specifying the text direction or policy that was set with
13555     * {@link #setTextDirection(int)}.
13556     *
13557     * @return the defined text direction. It can be one of:
13558     *
13559     * {@link #TEXT_DIRECTION_INHERIT},
13560     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13561     * {@link #TEXT_DIRECTION_ANY_RTL},
13562     * {@link #TEXT_DIRECTION_LTR},
13563     * {@link #TEXT_DIRECTION_RTL},
13564     *
13565     * @hide
13566     */
13567    public int getTextDirection() {
13568        return mTextDirection;
13569    }
13570
13571    /**
13572     * Set the text direction.
13573     *
13574     * @param textDirection the direction to set. Should be one of:
13575     *
13576     * {@link #TEXT_DIRECTION_INHERIT},
13577     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13578     * {@link #TEXT_DIRECTION_ANY_RTL},
13579     * {@link #TEXT_DIRECTION_LTR},
13580     * {@link #TEXT_DIRECTION_RTL},
13581     *
13582     * @hide
13583     */
13584    public void setTextDirection(int textDirection) {
13585        if (textDirection != mTextDirection) {
13586            mTextDirection = textDirection;
13587            resetResolvedTextDirection();
13588            requestLayout();
13589        }
13590    }
13591
13592    /**
13593     * Return the resolved text direction.
13594     *
13595     * @return the resolved text direction. Return one of:
13596     *
13597     * {@link #TEXT_DIRECTION_FIRST_STRONG}
13598     * {@link #TEXT_DIRECTION_ANY_RTL},
13599     * {@link #TEXT_DIRECTION_LTR},
13600     * {@link #TEXT_DIRECTION_RTL},
13601     *
13602     * @hide
13603     */
13604    public int getResolvedTextDirection() {
13605        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
13606            resolveTextDirection();
13607        }
13608        return mResolvedTextDirection;
13609    }
13610
13611    /**
13612     * Resolve the text direction.
13613     *
13614     * @hide
13615     */
13616    protected void resolveTextDirection() {
13617        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
13618            mResolvedTextDirection = mTextDirection;
13619            return;
13620        }
13621        if (mParent != null && mParent instanceof ViewGroup) {
13622            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
13623            return;
13624        }
13625        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
13626    }
13627
13628    /**
13629     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
13630     *
13631     * @hide
13632     */
13633    protected void resetResolvedTextDirection() {
13634        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
13635    }
13636
13637    //
13638    // Properties
13639    //
13640    /**
13641     * A Property wrapper around the <code>alpha</code> functionality handled by the
13642     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
13643     */
13644    public static Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
13645        @Override
13646        public void setValue(View object, float value) {
13647            object.setAlpha(value);
13648        }
13649
13650        @Override
13651        public Float get(View object) {
13652            return object.getAlpha();
13653        }
13654    };
13655
13656    /**
13657     * A Property wrapper around the <code>translationX</code> functionality handled by the
13658     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
13659     */
13660    public static Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
13661        @Override
13662        public void setValue(View object, float value) {
13663            object.setTranslationX(value);
13664        }
13665
13666                @Override
13667        public Float get(View object) {
13668            return object.getTranslationX();
13669        }
13670    };
13671
13672    /**
13673     * A Property wrapper around the <code>translationY</code> functionality handled by the
13674     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
13675     */
13676    public static Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
13677        @Override
13678        public void setValue(View object, float value) {
13679            object.setTranslationY(value);
13680        }
13681
13682        @Override
13683        public Float get(View object) {
13684            return object.getTranslationY();
13685        }
13686    };
13687
13688    /**
13689     * A Property wrapper around the <code>x</code> functionality handled by the
13690     * {@link View#setX(float)} and {@link View#getX()} methods.
13691     */
13692    public static Property<View, Float> X = new FloatProperty<View>("x") {
13693        @Override
13694        public void setValue(View object, float value) {
13695            object.setX(value);
13696        }
13697
13698        @Override
13699        public Float get(View object) {
13700            return object.getX();
13701        }
13702    };
13703
13704    /**
13705     * A Property wrapper around the <code>y</code> functionality handled by the
13706     * {@link View#setY(float)} and {@link View#getY()} methods.
13707     */
13708    public static Property<View, Float> Y = new FloatProperty<View>("y") {
13709        @Override
13710        public void setValue(View object, float value) {
13711            object.setY(value);
13712        }
13713
13714        @Override
13715        public Float get(View object) {
13716            return object.getY();
13717        }
13718    };
13719
13720    /**
13721     * A Property wrapper around the <code>rotation</code> functionality handled by the
13722     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
13723     */
13724    public static Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
13725        @Override
13726        public void setValue(View object, float value) {
13727            object.setRotation(value);
13728        }
13729
13730        @Override
13731        public Float get(View object) {
13732            return object.getRotation();
13733        }
13734    };
13735
13736    /**
13737     * A Property wrapper around the <code>rotationX</code> functionality handled by the
13738     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
13739     */
13740    public static Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
13741        @Override
13742        public void setValue(View object, float value) {
13743            object.setRotationX(value);
13744        }
13745
13746        @Override
13747        public Float get(View object) {
13748            return object.getRotationX();
13749        }
13750    };
13751
13752    /**
13753     * A Property wrapper around the <code>rotationY</code> functionality handled by the
13754     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
13755     */
13756    public static Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
13757        @Override
13758        public void setValue(View object, float value) {
13759            object.setRotationY(value);
13760        }
13761
13762        @Override
13763        public Float get(View object) {
13764            return object.getRotationY();
13765        }
13766    };
13767
13768    /**
13769     * A Property wrapper around the <code>scaleX</code> functionality handled by the
13770     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
13771     */
13772    public static Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
13773        @Override
13774        public void setValue(View object, float value) {
13775            object.setScaleX(value);
13776        }
13777
13778        @Override
13779        public Float get(View object) {
13780            return object.getScaleX();
13781        }
13782    };
13783
13784    /**
13785     * A Property wrapper around the <code>scaleY</code> functionality handled by the
13786     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
13787     */
13788    public static Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
13789        @Override
13790        public void setValue(View object, float value) {
13791            object.setScaleY(value);
13792        }
13793
13794        @Override
13795        public Float get(View object) {
13796            return object.getScaleY();
13797        }
13798    };
13799
13800    /**
13801     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
13802     * Each MeasureSpec represents a requirement for either the width or the height.
13803     * A MeasureSpec is comprised of a size and a mode. There are three possible
13804     * modes:
13805     * <dl>
13806     * <dt>UNSPECIFIED</dt>
13807     * <dd>
13808     * The parent has not imposed any constraint on the child. It can be whatever size
13809     * it wants.
13810     * </dd>
13811     *
13812     * <dt>EXACTLY</dt>
13813     * <dd>
13814     * The parent has determined an exact size for the child. The child is going to be
13815     * given those bounds regardless of how big it wants to be.
13816     * </dd>
13817     *
13818     * <dt>AT_MOST</dt>
13819     * <dd>
13820     * The child can be as large as it wants up to the specified size.
13821     * </dd>
13822     * </dl>
13823     *
13824     * MeasureSpecs are implemented as ints to reduce object allocation. This class
13825     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
13826     */
13827    public static class MeasureSpec {
13828        private static final int MODE_SHIFT = 30;
13829        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
13830
13831        /**
13832         * Measure specification mode: The parent has not imposed any constraint
13833         * on the child. It can be whatever size it wants.
13834         */
13835        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
13836
13837        /**
13838         * Measure specification mode: The parent has determined an exact size
13839         * for the child. The child is going to be given those bounds regardless
13840         * of how big it wants to be.
13841         */
13842        public static final int EXACTLY     = 1 << MODE_SHIFT;
13843
13844        /**
13845         * Measure specification mode: The child can be as large as it wants up
13846         * to the specified size.
13847         */
13848        public static final int AT_MOST     = 2 << MODE_SHIFT;
13849
13850        /**
13851         * Creates a measure specification based on the supplied size and mode.
13852         *
13853         * The mode must always be one of the following:
13854         * <ul>
13855         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
13856         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
13857         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
13858         * </ul>
13859         *
13860         * @param size the size of the measure specification
13861         * @param mode the mode of the measure specification
13862         * @return the measure specification based on size and mode
13863         */
13864        public static int makeMeasureSpec(int size, int mode) {
13865            return size + mode;
13866        }
13867
13868        /**
13869         * Extracts the mode from the supplied measure specification.
13870         *
13871         * @param measureSpec the measure specification to extract the mode from
13872         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
13873         *         {@link android.view.View.MeasureSpec#AT_MOST} or
13874         *         {@link android.view.View.MeasureSpec#EXACTLY}
13875         */
13876        public static int getMode(int measureSpec) {
13877            return (measureSpec & MODE_MASK);
13878        }
13879
13880        /**
13881         * Extracts the size from the supplied measure specification.
13882         *
13883         * @param measureSpec the measure specification to extract the size from
13884         * @return the size in pixels defined in the supplied measure specification
13885         */
13886        public static int getSize(int measureSpec) {
13887            return (measureSpec & ~MODE_MASK);
13888        }
13889
13890        /**
13891         * Returns a String representation of the specified measure
13892         * specification.
13893         *
13894         * @param measureSpec the measure specification to convert to a String
13895         * @return a String with the following format: "MeasureSpec: MODE SIZE"
13896         */
13897        public static String toString(int measureSpec) {
13898            int mode = getMode(measureSpec);
13899            int size = getSize(measureSpec);
13900
13901            StringBuilder sb = new StringBuilder("MeasureSpec: ");
13902
13903            if (mode == UNSPECIFIED)
13904                sb.append("UNSPECIFIED ");
13905            else if (mode == EXACTLY)
13906                sb.append("EXACTLY ");
13907            else if (mode == AT_MOST)
13908                sb.append("AT_MOST ");
13909            else
13910                sb.append(mode).append(" ");
13911
13912            sb.append(size);
13913            return sb.toString();
13914        }
13915    }
13916
13917    class CheckForLongPress implements Runnable {
13918
13919        private int mOriginalWindowAttachCount;
13920
13921        public void run() {
13922            if (isPressed() && (mParent != null)
13923                    && mOriginalWindowAttachCount == mWindowAttachCount) {
13924                if (performLongClick()) {
13925                    mHasPerformedLongPress = true;
13926                }
13927            }
13928        }
13929
13930        public void rememberWindowAttachCount() {
13931            mOriginalWindowAttachCount = mWindowAttachCount;
13932        }
13933    }
13934
13935    private final class CheckForTap implements Runnable {
13936        public void run() {
13937            mPrivateFlags &= ~PREPRESSED;
13938            mPrivateFlags |= PRESSED;
13939            refreshDrawableState();
13940            checkForLongClick(ViewConfiguration.getTapTimeout());
13941        }
13942    }
13943
13944    private final class PerformClick implements Runnable {
13945        public void run() {
13946            performClick();
13947        }
13948    }
13949
13950    /** @hide */
13951    public void hackTurnOffWindowResizeAnim(boolean off) {
13952        mAttachInfo.mTurnOffWindowResizeAnim = off;
13953    }
13954
13955    /**
13956     * This method returns a ViewPropertyAnimator object, which can be used to animate
13957     * specific properties on this View.
13958     *
13959     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
13960     */
13961    public ViewPropertyAnimator animate() {
13962        if (mAnimator == null) {
13963            mAnimator = new ViewPropertyAnimator(this);
13964        }
13965        return mAnimator;
13966    }
13967
13968    /**
13969     * Interface definition for a callback to be invoked when a key event is
13970     * dispatched to this view. The callback will be invoked before the key
13971     * event is given to the view.
13972     */
13973    public interface OnKeyListener {
13974        /**
13975         * Called when a key is dispatched to a view. This allows listeners to
13976         * get a chance to respond before the target view.
13977         *
13978         * @param v The view the key has been dispatched to.
13979         * @param keyCode The code for the physical key that was pressed
13980         * @param event The KeyEvent object containing full information about
13981         *        the event.
13982         * @return True if the listener has consumed the event, false otherwise.
13983         */
13984        boolean onKey(View v, int keyCode, KeyEvent event);
13985    }
13986
13987    /**
13988     * Interface definition for a callback to be invoked when a touch event is
13989     * dispatched to this view. The callback will be invoked before the touch
13990     * event is given to the view.
13991     */
13992    public interface OnTouchListener {
13993        /**
13994         * Called when a touch event is dispatched to a view. This allows listeners to
13995         * get a chance to respond before the target view.
13996         *
13997         * @param v The view the touch event has been dispatched to.
13998         * @param event The MotionEvent object containing full information about
13999         *        the event.
14000         * @return True if the listener has consumed the event, false otherwise.
14001         */
14002        boolean onTouch(View v, MotionEvent event);
14003    }
14004
14005    /**
14006     * Interface definition for a callback to be invoked when a hover event is
14007     * dispatched to this view. The callback will be invoked before the hover
14008     * event is given to the view.
14009     */
14010    public interface OnHoverListener {
14011        /**
14012         * Called when a hover event is dispatched to a view. This allows listeners to
14013         * get a chance to respond before the target view.
14014         *
14015         * @param v The view the hover event has been dispatched to.
14016         * @param event The MotionEvent object containing full information about
14017         *        the event.
14018         * @return True if the listener has consumed the event, false otherwise.
14019         */
14020        boolean onHover(View v, MotionEvent event);
14021    }
14022
14023    /**
14024     * Interface definition for a callback to be invoked when a generic motion event is
14025     * dispatched to this view. The callback will be invoked before the generic motion
14026     * event is given to the view.
14027     */
14028    public interface OnGenericMotionListener {
14029        /**
14030         * Called when a generic motion event is dispatched to a view. This allows listeners to
14031         * get a chance to respond before the target view.
14032         *
14033         * @param v The view the generic motion event has been dispatched to.
14034         * @param event The MotionEvent object containing full information about
14035         *        the event.
14036         * @return True if the listener has consumed the event, false otherwise.
14037         */
14038        boolean onGenericMotion(View v, MotionEvent event);
14039    }
14040
14041    /**
14042     * Interface definition for a callback to be invoked when a view has been clicked and held.
14043     */
14044    public interface OnLongClickListener {
14045        /**
14046         * Called when a view has been clicked and held.
14047         *
14048         * @param v The view that was clicked and held.
14049         *
14050         * @return true if the callback consumed the long click, false otherwise.
14051         */
14052        boolean onLongClick(View v);
14053    }
14054
14055    /**
14056     * Interface definition for a callback to be invoked when a drag is being dispatched
14057     * to this view.  The callback will be invoked before the hosting view's own
14058     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14059     * onDrag(event) behavior, it should return 'false' from this callback.
14060     */
14061    public interface OnDragListener {
14062        /**
14063         * Called when a drag event is dispatched to a view. This allows listeners
14064         * to get a chance to override base View behavior.
14065         *
14066         * @param v The View that received the drag event.
14067         * @param event The {@link android.view.DragEvent} object for the drag event.
14068         * @return {@code true} if the drag event was handled successfully, or {@code false}
14069         * if the drag event was not handled. Note that {@code false} will trigger the View
14070         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14071         */
14072        boolean onDrag(View v, DragEvent event);
14073    }
14074
14075    /**
14076     * Interface definition for a callback to be invoked when the focus state of
14077     * a view changed.
14078     */
14079    public interface OnFocusChangeListener {
14080        /**
14081         * Called when the focus state of a view has changed.
14082         *
14083         * @param v The view whose state has changed.
14084         * @param hasFocus The new focus state of v.
14085         */
14086        void onFocusChange(View v, boolean hasFocus);
14087    }
14088
14089    /**
14090     * Interface definition for a callback to be invoked when a view is clicked.
14091     */
14092    public interface OnClickListener {
14093        /**
14094         * Called when a view has been clicked.
14095         *
14096         * @param v The view that was clicked.
14097         */
14098        void onClick(View v);
14099    }
14100
14101    /**
14102     * Interface definition for a callback to be invoked when the context menu
14103     * for this view is being built.
14104     */
14105    public interface OnCreateContextMenuListener {
14106        /**
14107         * Called when the context menu for this view is being built. It is not
14108         * safe to hold onto the menu after this method returns.
14109         *
14110         * @param menu The context menu that is being built
14111         * @param v The view for which the context menu is being built
14112         * @param menuInfo Extra information about the item for which the
14113         *            context menu should be shown. This information will vary
14114         *            depending on the class of v.
14115         */
14116        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14117    }
14118
14119    /**
14120     * Interface definition for a callback to be invoked when the status bar changes
14121     * visibility.
14122     *
14123     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14124     */
14125    public interface OnSystemUiVisibilityChangeListener {
14126        /**
14127         * Called when the status bar changes visibility because of a call to
14128         * {@link View#setSystemUiVisibility(int)}.
14129         *
14130         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14131         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
14132         */
14133        public void onSystemUiVisibilityChange(int visibility);
14134    }
14135
14136    /**
14137     * Interface definition for a callback to be invoked when this view is attached
14138     * or detached from its window.
14139     */
14140    public interface OnAttachStateChangeListener {
14141        /**
14142         * Called when the view is attached to a window.
14143         * @param v The view that was attached
14144         */
14145        public void onViewAttachedToWindow(View v);
14146        /**
14147         * Called when the view is detached from a window.
14148         * @param v The view that was detached
14149         */
14150        public void onViewDetachedFromWindow(View v);
14151    }
14152
14153    private final class UnsetPressedState implements Runnable {
14154        public void run() {
14155            setPressed(false);
14156        }
14157    }
14158
14159    /**
14160     * Base class for derived classes that want to save and restore their own
14161     * state in {@link android.view.View#onSaveInstanceState()}.
14162     */
14163    public static class BaseSavedState extends AbsSavedState {
14164        /**
14165         * Constructor used when reading from a parcel. Reads the state of the superclass.
14166         *
14167         * @param source
14168         */
14169        public BaseSavedState(Parcel source) {
14170            super(source);
14171        }
14172
14173        /**
14174         * Constructor called by derived classes when creating their SavedState objects
14175         *
14176         * @param superState The state of the superclass of this view
14177         */
14178        public BaseSavedState(Parcelable superState) {
14179            super(superState);
14180        }
14181
14182        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14183                new Parcelable.Creator<BaseSavedState>() {
14184            public BaseSavedState createFromParcel(Parcel in) {
14185                return new BaseSavedState(in);
14186            }
14187
14188            public BaseSavedState[] newArray(int size) {
14189                return new BaseSavedState[size];
14190            }
14191        };
14192    }
14193
14194    /**
14195     * A set of information given to a view when it is attached to its parent
14196     * window.
14197     */
14198    static class AttachInfo {
14199        interface Callbacks {
14200            void playSoundEffect(int effectId);
14201            boolean performHapticFeedback(int effectId, boolean always);
14202        }
14203
14204        /**
14205         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
14206         * to a Handler. This class contains the target (View) to invalidate and
14207         * the coordinates of the dirty rectangle.
14208         *
14209         * For performance purposes, this class also implements a pool of up to
14210         * POOL_LIMIT objects that get reused. This reduces memory allocations
14211         * whenever possible.
14212         */
14213        static class InvalidateInfo implements Poolable<InvalidateInfo> {
14214            private static final int POOL_LIMIT = 10;
14215            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
14216                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
14217                        public InvalidateInfo newInstance() {
14218                            return new InvalidateInfo();
14219                        }
14220
14221                        public void onAcquired(InvalidateInfo element) {
14222                        }
14223
14224                        public void onReleased(InvalidateInfo element) {
14225                            element.target = null;
14226                        }
14227                    }, POOL_LIMIT)
14228            );
14229
14230            private InvalidateInfo mNext;
14231            private boolean mIsPooled;
14232
14233            View target;
14234
14235            int left;
14236            int top;
14237            int right;
14238            int bottom;
14239
14240            public void setNextPoolable(InvalidateInfo element) {
14241                mNext = element;
14242            }
14243
14244            public InvalidateInfo getNextPoolable() {
14245                return mNext;
14246            }
14247
14248            static InvalidateInfo acquire() {
14249                return sPool.acquire();
14250            }
14251
14252            void release() {
14253                sPool.release(this);
14254            }
14255
14256            public boolean isPooled() {
14257                return mIsPooled;
14258            }
14259
14260            public void setPooled(boolean isPooled) {
14261                mIsPooled = isPooled;
14262            }
14263        }
14264
14265        final IWindowSession mSession;
14266
14267        final IWindow mWindow;
14268
14269        final IBinder mWindowToken;
14270
14271        final Callbacks mRootCallbacks;
14272
14273        HardwareCanvas mHardwareCanvas;
14274
14275        /**
14276         * The top view of the hierarchy.
14277         */
14278        View mRootView;
14279
14280        IBinder mPanelParentWindowToken;
14281        Surface mSurface;
14282
14283        boolean mHardwareAccelerated;
14284        boolean mHardwareAccelerationRequested;
14285        HardwareRenderer mHardwareRenderer;
14286
14287        /**
14288         * Scale factor used by the compatibility mode
14289         */
14290        float mApplicationScale;
14291
14292        /**
14293         * Indicates whether the application is in compatibility mode
14294         */
14295        boolean mScalingRequired;
14296
14297        /**
14298         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
14299         */
14300        boolean mTurnOffWindowResizeAnim;
14301
14302        /**
14303         * Left position of this view's window
14304         */
14305        int mWindowLeft;
14306
14307        /**
14308         * Top position of this view's window
14309         */
14310        int mWindowTop;
14311
14312        /**
14313         * Indicates whether views need to use 32-bit drawing caches
14314         */
14315        boolean mUse32BitDrawingCache;
14316
14317        /**
14318         * For windows that are full-screen but using insets to layout inside
14319         * of the screen decorations, these are the current insets for the
14320         * content of the window.
14321         */
14322        final Rect mContentInsets = new Rect();
14323
14324        /**
14325         * For windows that are full-screen but using insets to layout inside
14326         * of the screen decorations, these are the current insets for the
14327         * actual visible parts of the window.
14328         */
14329        final Rect mVisibleInsets = new Rect();
14330
14331        /**
14332         * The internal insets given by this window.  This value is
14333         * supplied by the client (through
14334         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14335         * be given to the window manager when changed to be used in laying
14336         * out windows behind it.
14337         */
14338        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14339                = new ViewTreeObserver.InternalInsetsInfo();
14340
14341        /**
14342         * All views in the window's hierarchy that serve as scroll containers,
14343         * used to determine if the window can be resized or must be panned
14344         * to adjust for a soft input area.
14345         */
14346        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14347
14348        final KeyEvent.DispatcherState mKeyDispatchState
14349                = new KeyEvent.DispatcherState();
14350
14351        /**
14352         * Indicates whether the view's window currently has the focus.
14353         */
14354        boolean mHasWindowFocus;
14355
14356        /**
14357         * The current visibility of the window.
14358         */
14359        int mWindowVisibility;
14360
14361        /**
14362         * Indicates the time at which drawing started to occur.
14363         */
14364        long mDrawingTime;
14365
14366        /**
14367         * Indicates whether or not ignoring the DIRTY_MASK flags.
14368         */
14369        boolean mIgnoreDirtyState;
14370
14371        /**
14372         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14373         * to avoid clearing that flag prematurely.
14374         */
14375        boolean mSetIgnoreDirtyState = false;
14376
14377        /**
14378         * Indicates whether the view's window is currently in touch mode.
14379         */
14380        boolean mInTouchMode;
14381
14382        /**
14383         * Indicates that ViewAncestor should trigger a global layout change
14384         * the next time it performs a traversal
14385         */
14386        boolean mRecomputeGlobalAttributes;
14387
14388        /**
14389         * Set during a traveral if any views want to keep the screen on.
14390         */
14391        boolean mKeepScreenOn;
14392
14393        /**
14394         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14395         */
14396        int mSystemUiVisibility;
14397
14398        /**
14399         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14400         * attached.
14401         */
14402        boolean mHasSystemUiListeners;
14403
14404        /**
14405         * Set if the visibility of any views has changed.
14406         */
14407        boolean mViewVisibilityChanged;
14408
14409        /**
14410         * Set to true if a view has been scrolled.
14411         */
14412        boolean mViewScrollChanged;
14413
14414        /**
14415         * Global to the view hierarchy used as a temporary for dealing with
14416         * x/y points in the transparent region computations.
14417         */
14418        final int[] mTransparentLocation = new int[2];
14419
14420        /**
14421         * Global to the view hierarchy used as a temporary for dealing with
14422         * x/y points in the ViewGroup.invalidateChild implementation.
14423         */
14424        final int[] mInvalidateChildLocation = new int[2];
14425
14426
14427        /**
14428         * Global to the view hierarchy used as a temporary for dealing with
14429         * x/y location when view is transformed.
14430         */
14431        final float[] mTmpTransformLocation = new float[2];
14432
14433        /**
14434         * The view tree observer used to dispatch global events like
14435         * layout, pre-draw, touch mode change, etc.
14436         */
14437        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14438
14439        /**
14440         * A Canvas used by the view hierarchy to perform bitmap caching.
14441         */
14442        Canvas mCanvas;
14443
14444        /**
14445         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14446         * handler can be used to pump events in the UI events queue.
14447         */
14448        final Handler mHandler;
14449
14450        /**
14451         * Identifier for messages requesting the view to be invalidated.
14452         * Such messages should be sent to {@link #mHandler}.
14453         */
14454        static final int INVALIDATE_MSG = 0x1;
14455
14456        /**
14457         * Identifier for messages requesting the view to invalidate a region.
14458         * Such messages should be sent to {@link #mHandler}.
14459         */
14460        static final int INVALIDATE_RECT_MSG = 0x2;
14461
14462        /**
14463         * Temporary for use in computing invalidate rectangles while
14464         * calling up the hierarchy.
14465         */
14466        final Rect mTmpInvalRect = new Rect();
14467
14468        /**
14469         * Temporary for use in computing hit areas with transformed views
14470         */
14471        final RectF mTmpTransformRect = new RectF();
14472
14473        /**
14474         * Temporary list for use in collecting focusable descendents of a view.
14475         */
14476        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14477
14478        /**
14479         * The id of the window for accessibility purposes.
14480         */
14481        int mAccessibilityWindowId = View.NO_ID;
14482
14483        /**
14484         * Creates a new set of attachment information with the specified
14485         * events handler and thread.
14486         *
14487         * @param handler the events handler the view must use
14488         */
14489        AttachInfo(IWindowSession session, IWindow window,
14490                Handler handler, Callbacks effectPlayer) {
14491            mSession = session;
14492            mWindow = window;
14493            mWindowToken = window.asBinder();
14494            mHandler = handler;
14495            mRootCallbacks = effectPlayer;
14496        }
14497    }
14498
14499    /**
14500     * <p>ScrollabilityCache holds various fields used by a View when scrolling
14501     * is supported. This avoids keeping too many unused fields in most
14502     * instances of View.</p>
14503     */
14504    private static class ScrollabilityCache implements Runnable {
14505
14506        /**
14507         * Scrollbars are not visible
14508         */
14509        public static final int OFF = 0;
14510
14511        /**
14512         * Scrollbars are visible
14513         */
14514        public static final int ON = 1;
14515
14516        /**
14517         * Scrollbars are fading away
14518         */
14519        public static final int FADING = 2;
14520
14521        public boolean fadeScrollBars;
14522
14523        public int fadingEdgeLength;
14524        public int scrollBarDefaultDelayBeforeFade;
14525        public int scrollBarFadeDuration;
14526
14527        public int scrollBarSize;
14528        public ScrollBarDrawable scrollBar;
14529        public float[] interpolatorValues;
14530        public View host;
14531
14532        public final Paint paint;
14533        public final Matrix matrix;
14534        public Shader shader;
14535
14536        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
14537
14538        private static final float[] OPAQUE = { 255 };
14539        private static final float[] TRANSPARENT = { 0.0f };
14540
14541        /**
14542         * When fading should start. This time moves into the future every time
14543         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
14544         */
14545        public long fadeStartTime;
14546
14547
14548        /**
14549         * The current state of the scrollbars: ON, OFF, or FADING
14550         */
14551        public int state = OFF;
14552
14553        private int mLastColor;
14554
14555        public ScrollabilityCache(ViewConfiguration configuration, View host) {
14556            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
14557            scrollBarSize = configuration.getScaledScrollBarSize();
14558            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
14559            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
14560
14561            paint = new Paint();
14562            matrix = new Matrix();
14563            // use use a height of 1, and then wack the matrix each time we
14564            // actually use it.
14565            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
14566
14567            paint.setShader(shader);
14568            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
14569            this.host = host;
14570        }
14571
14572        public void setFadeColor(int color) {
14573            if (color != 0 && color != mLastColor) {
14574                mLastColor = color;
14575                color |= 0xFF000000;
14576
14577                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
14578                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
14579
14580                paint.setShader(shader);
14581                // Restore the default transfer mode (src_over)
14582                paint.setXfermode(null);
14583            }
14584        }
14585
14586        public void run() {
14587            long now = AnimationUtils.currentAnimationTimeMillis();
14588            if (now >= fadeStartTime) {
14589
14590                // the animation fades the scrollbars out by changing
14591                // the opacity (alpha) from fully opaque to fully
14592                // transparent
14593                int nextFrame = (int) now;
14594                int framesCount = 0;
14595
14596                Interpolator interpolator = scrollBarInterpolator;
14597
14598                // Start opaque
14599                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
14600
14601                // End transparent
14602                nextFrame += scrollBarFadeDuration;
14603                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
14604
14605                state = FADING;
14606
14607                // Kick off the fade animation
14608                host.invalidate(true);
14609            }
14610        }
14611    }
14612
14613    /**
14614     * Resuable callback for sending
14615     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
14616     */
14617    private class SendViewScrolledAccessibilityEvent implements Runnable {
14618        public volatile boolean mIsPending;
14619
14620        public void run() {
14621            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
14622            mIsPending = false;
14623        }
14624    }
14625
14626    /**
14627     * <p>
14628     * This class represents a delegate that can be registered in a {@link View}
14629     * to enhance accessibility support via composition rather via inheritance.
14630     * It is specifically targeted to widget developers that extend basic View
14631     * classes i.e. classes in package android.view, that would like their
14632     * applications to be backwards compatible.
14633     * </p>
14634     * <p>
14635     * A scenario in which a developer would like to use an accessibility delegate
14636     * is overriding a method introduced in a later API version then the minimal API
14637     * version supported by the application. For example, the method
14638     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
14639     * in API version 4 when the accessibility APIs were first introduced. If a
14640     * developer would like his application to run on API version 4 devices (assuming
14641     * all other APIs used by the application are version 4 or lower) and take advantage
14642     * of this method, instead of overriding the method which would break the application's
14643     * backwards compatibility, he can override the corresponding method in this
14644     * delegate and register the delegate in the target View if the API version of
14645     * the system is high enough i.e. the API version is same or higher to the API
14646     * version that introduced
14647     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
14648     * </p>
14649     * <p>
14650     * Here is an example implementation:
14651     * </p>
14652     * <code><pre><p>
14653     * if (Build.VERSION.SDK_INT >= 14) {
14654     *     // If the API version is equal of higher than the version in
14655     *     // which onInitializeAccessibilityNodeInfo was introduced we
14656     *     // register a delegate with a customized implementation.
14657     *     View view = findViewById(R.id.view_id);
14658     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
14659     *         public void onInitializeAccessibilityNodeInfo(View host,
14660     *                 AccessibilityNodeInfo info) {
14661     *             // Let the default implementation populate the info.
14662     *             super.onInitializeAccessibilityNodeInfo(host, info);
14663     *             // Set some other information.
14664     *             info.setEnabled(host.isEnabled());
14665     *         }
14666     *     });
14667     * }
14668     * </code></pre></p>
14669     * <p>
14670     * This delegate contains methods that correspond to the accessibility methods
14671     * in View. If a delegate has been specified the implementation in View hands
14672     * off handling to the corresponding method in this delegate. The default
14673     * implementation the delegate methods behaves exactly as the corresponding
14674     * method in View for the case of no accessibility delegate been set. Hence,
14675     * to customize the behavior of a View method, clients can override only the
14676     * corresponding delegate method without altering the behavior of the rest
14677     * accessibility related methods of the host view.
14678     * </p>
14679     */
14680    public static class AccessibilityDelegate {
14681
14682        /**
14683         * Sends an accessibility event of the given type. If accessibility is not
14684         * enabled this method has no effect.
14685         * <p>
14686         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
14687         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
14688         * been set.
14689         * </p>
14690         *
14691         * @param host The View hosting the delegate.
14692         * @param eventType The type of the event to send.
14693         *
14694         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
14695         */
14696        public void sendAccessibilityEvent(View host, int eventType) {
14697            host.sendAccessibilityEventInternal(eventType);
14698        }
14699
14700        /**
14701         * Sends an accessibility event. This method behaves exactly as
14702         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
14703         * empty {@link AccessibilityEvent} and does not perform a check whether
14704         * accessibility is enabled.
14705         * <p>
14706         * The default implementation behaves as
14707         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14708         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
14709         * the case of no accessibility delegate been set.
14710         * </p>
14711         *
14712         * @param host The View hosting the delegate.
14713         * @param event The event to send.
14714         *
14715         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14716         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
14717         */
14718        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
14719            host.sendAccessibilityEventUncheckedInternal(event);
14720        }
14721
14722        /**
14723         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
14724         * to its children for adding their text content to the event.
14725         * <p>
14726         * The default implementation behaves as
14727         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14728         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
14729         * the case of no accessibility delegate been set.
14730         * </p>
14731         *
14732         * @param host The View hosting the delegate.
14733         * @param event The event.
14734         * @return True if the event population was completed.
14735         *
14736         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14737         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
14738         */
14739        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14740            return host.dispatchPopulateAccessibilityEventInternal(event);
14741        }
14742
14743        /**
14744         * Gives a chance to the host View to populate the accessibility event with its
14745         * text content.
14746         * <p>
14747         * The default implementation behaves as
14748         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
14749         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
14750         * the case of no accessibility delegate been set.
14751         * </p>
14752         *
14753         * @param host The View hosting the delegate.
14754         * @param event The accessibility event which to populate.
14755         *
14756         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
14757         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
14758         */
14759        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
14760            host.onPopulateAccessibilityEventInternal(event);
14761        }
14762
14763        /**
14764         * Initializes an {@link AccessibilityEvent} with information about the
14765         * the host View which is the event source.
14766         * <p>
14767         * The default implementation behaves as
14768         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
14769         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
14770         * the case of no accessibility delegate been set.
14771         * </p>
14772         *
14773         * @param host The View hosting the delegate.
14774         * @param event The event to initialize.
14775         *
14776         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
14777         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
14778         */
14779        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
14780            host.onInitializeAccessibilityEventInternal(event);
14781        }
14782
14783        /**
14784         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
14785         * <p>
14786         * The default implementation behaves as
14787         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14788         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
14789         * the case of no accessibility delegate been set.
14790         * </p>
14791         *
14792         * @param host The View hosting the delegate.
14793         * @param info The instance to initialize.
14794         *
14795         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14796         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
14797         */
14798        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
14799            host.onInitializeAccessibilityNodeInfoInternal(info);
14800        }
14801
14802        /**
14803         * Called when a child of the host View has requested sending an
14804         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
14805         * to augment the event.
14806         * <p>
14807         * The default implementation behaves as
14808         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14809         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
14810         * the case of no accessibility delegate been set.
14811         * </p>
14812         *
14813         * @param host The View hosting the delegate.
14814         * @param child The child which requests sending the event.
14815         * @param event The event to be sent.
14816         * @return True if the event should be sent
14817         *
14818         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14819         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
14820         */
14821        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
14822                AccessibilityEvent event) {
14823            return host.onRequestSendAccessibilityEventInternal(child, event);
14824        }
14825    }
14826}
14827