View.java revision f7280ccbfe6d71686a4e609ee7628f84e514a32d
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.accessibility.AccessibilityNodeProvider;
66import android.view.animation.Animation;
67import android.view.animation.AnimationUtils;
68import android.view.animation.Transformation;
69import android.view.inputmethod.EditorInfo;
70import android.view.inputmethod.InputConnection;
71import android.view.inputmethod.InputMethodManager;
72import android.widget.ScrollBarDrawable;
73
74import static android.os.Build.VERSION_CODES.*;
75
76import com.android.internal.R;
77import com.android.internal.util.Predicate;
78import com.android.internal.view.menu.MenuBuilder;
79
80import java.lang.ref.WeakReference;
81import java.lang.reflect.InvocationTargetException;
82import java.lang.reflect.Method;
83import java.util.ArrayList;
84import java.util.Arrays;
85import java.util.Locale;
86import java.util.concurrent.CopyOnWriteArrayList;
87
88/**
89 * <p>
90 * This class represents the basic building block for user interface components. A View
91 * occupies a rectangular area on the screen and is responsible for drawing and
92 * event handling. View is the base class for <em>widgets</em>, which are
93 * used to create interactive UI components (buttons, text fields, etc.). The
94 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
95 * are invisible containers that hold other Views (or other ViewGroups) and define
96 * their layout properties.
97 * </p>
98 *
99 * <div class="special reference">
100 * <h3>Developer Guides</h3>
101 * <p>For information about using this class to develop your application's user interface,
102 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
103 * </div>
104 *
105 * <a name="Using"></a>
106 * <h3>Using Views</h3>
107 * <p>
108 * All of the views in a window are arranged in a single tree. You can add views
109 * either from code or by specifying a tree of views in one or more XML layout
110 * files. There are many specialized subclasses of views that act as controls or
111 * are capable of displaying text, images, or other content.
112 * </p>
113 * <p>
114 * Once you have created a tree of views, there are typically a few types of
115 * common operations you may wish to perform:
116 * <ul>
117 * <li><strong>Set properties:</strong> for example setting the text of a
118 * {@link android.widget.TextView}. The available properties and the methods
119 * that set them will vary among the different subclasses of views. Note that
120 * properties that are known at build time can be set in the XML layout
121 * files.</li>
122 * <li><strong>Set focus:</strong> The framework will handled moving focus in
123 * response to user input. To force focus to a specific view, call
124 * {@link #requestFocus}.</li>
125 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
126 * that will be notified when something interesting happens to the view. For
127 * example, all views will let you set a listener to be notified when the view
128 * gains or loses focus. You can register such a listener using
129 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
130 * Other view subclasses offer more specialized listeners. For example, a Button
131 * exposes a listener to notify clients when the button is clicked.</li>
132 * <li><strong>Set visibility:</strong> You can hide or show views using
133 * {@link #setVisibility(int)}.</li>
134 * </ul>
135 * </p>
136 * <p><em>
137 * Note: The Android framework is responsible for measuring, laying out and
138 * drawing views. You should not call methods that perform these actions on
139 * views yourself unless you are actually implementing a
140 * {@link android.view.ViewGroup}.
141 * </em></p>
142 *
143 * <a name="Lifecycle"></a>
144 * <h3>Implementing a Custom View</h3>
145 *
146 * <p>
147 * To implement a custom view, you will usually begin by providing overrides for
148 * some of the standard methods that the framework calls on all views. You do
149 * not need to override all of these methods. In fact, you can start by just
150 * overriding {@link #onDraw(android.graphics.Canvas)}.
151 * <table border="2" width="85%" align="center" cellpadding="5">
152 *     <thead>
153 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
154 *     </thead>
155 *
156 *     <tbody>
157 *     <tr>
158 *         <td rowspan="2">Creation</td>
159 *         <td>Constructors</td>
160 *         <td>There is a form of the constructor that are called when the view
161 *         is created from code and a form that is called when the view is
162 *         inflated from a layout file. The second form should parse and apply
163 *         any attributes defined in the layout file.
164 *         </td>
165 *     </tr>
166 *     <tr>
167 *         <td><code>{@link #onFinishInflate()}</code></td>
168 *         <td>Called after a view and all of its children has been inflated
169 *         from XML.</td>
170 *     </tr>
171 *
172 *     <tr>
173 *         <td rowspan="3">Layout</td>
174 *         <td><code>{@link #onMeasure(int, int)}</code></td>
175 *         <td>Called to determine the size requirements for this view and all
176 *         of its children.
177 *         </td>
178 *     </tr>
179 *     <tr>
180 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
181 *         <td>Called when this view should assign a size and position to all
182 *         of its children.
183 *         </td>
184 *     </tr>
185 *     <tr>
186 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
187 *         <td>Called when the size of this view has changed.
188 *         </td>
189 *     </tr>
190 *
191 *     <tr>
192 *         <td>Drawing</td>
193 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
194 *         <td>Called when the view should render its content.
195 *         </td>
196 *     </tr>
197 *
198 *     <tr>
199 *         <td rowspan="4">Event processing</td>
200 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
201 *         <td>Called when a new key event occurs.
202 *         </td>
203 *     </tr>
204 *     <tr>
205 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
206 *         <td>Called when a key up event occurs.
207 *         </td>
208 *     </tr>
209 *     <tr>
210 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
211 *         <td>Called when a trackball motion event occurs.
212 *         </td>
213 *     </tr>
214 *     <tr>
215 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
216 *         <td>Called when a touch screen motion event occurs.
217 *         </td>
218 *     </tr>
219 *
220 *     <tr>
221 *         <td rowspan="2">Focus</td>
222 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
223 *         <td>Called when the view gains or loses focus.
224 *         </td>
225 *     </tr>
226 *
227 *     <tr>
228 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
229 *         <td>Called when the window containing the view gains or loses focus.
230 *         </td>
231 *     </tr>
232 *
233 *     <tr>
234 *         <td rowspan="3">Attaching</td>
235 *         <td><code>{@link #onAttachedToWindow()}</code></td>
236 *         <td>Called when the view is attached to a window.
237 *         </td>
238 *     </tr>
239 *
240 *     <tr>
241 *         <td><code>{@link #onDetachedFromWindow}</code></td>
242 *         <td>Called when the view is detached from its window.
243 *         </td>
244 *     </tr>
245 *
246 *     <tr>
247 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
248 *         <td>Called when the visibility of the window containing the view
249 *         has changed.
250 *         </td>
251 *     </tr>
252 *     </tbody>
253 *
254 * </table>
255 * </p>
256 *
257 * <a name="IDs"></a>
258 * <h3>IDs</h3>
259 * Views may have an integer id associated with them. These ids are typically
260 * assigned in the layout XML files, and are used to find specific views within
261 * the view tree. A common pattern is to:
262 * <ul>
263 * <li>Define a Button in the layout file and assign it a unique ID.
264 * <pre>
265 * &lt;Button
266 *     android:id="@+id/my_button"
267 *     android:layout_width="wrap_content"
268 *     android:layout_height="wrap_content"
269 *     android:text="@string/my_button_text"/&gt;
270 * </pre></li>
271 * <li>From the onCreate method of an Activity, find the Button
272 * <pre class="prettyprint">
273 *      Button myButton = (Button) findViewById(R.id.my_button);
274 * </pre></li>
275 * </ul>
276 * <p>
277 * View IDs need not be unique throughout the tree, but it is good practice to
278 * ensure that they are at least unique within the part of the tree you are
279 * searching.
280 * </p>
281 *
282 * <a name="Position"></a>
283 * <h3>Position</h3>
284 * <p>
285 * The geometry of a view is that of a rectangle. A view has a location,
286 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
287 * two dimensions, expressed as a width and a height. The unit for location
288 * and dimensions is the pixel.
289 * </p>
290 *
291 * <p>
292 * It is possible to retrieve the location of a view by invoking the methods
293 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
294 * coordinate of the rectangle representing the view. The latter returns the
295 * top, or Y, coordinate of the rectangle representing the view. These methods
296 * both return the location of the view relative to its parent. For instance,
297 * when getLeft() returns 20, that means the view is located 20 pixels to the
298 * right of the left edge of its direct parent.
299 * </p>
300 *
301 * <p>
302 * In addition, several convenience methods are offered to avoid unnecessary
303 * computations, namely {@link #getRight()} and {@link #getBottom()}.
304 * These methods return the coordinates of the right and bottom edges of the
305 * rectangle representing the view. For instance, calling {@link #getRight()}
306 * is similar to the following computation: <code>getLeft() + getWidth()</code>
307 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
308 * </p>
309 *
310 * <a name="SizePaddingMargins"></a>
311 * <h3>Size, padding and margins</h3>
312 * <p>
313 * The size of a view is expressed with a width and a height. A view actually
314 * possess two pairs of width and height values.
315 * </p>
316 *
317 * <p>
318 * The first pair is known as <em>measured width</em> and
319 * <em>measured height</em>. These dimensions define how big a view wants to be
320 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
321 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
322 * and {@link #getMeasuredHeight()}.
323 * </p>
324 *
325 * <p>
326 * The second pair is simply known as <em>width</em> and <em>height</em>, or
327 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
328 * dimensions define the actual size of the view on screen, at drawing time and
329 * after layout. These values may, but do not have to, be different from the
330 * measured width and height. The width and height can be obtained by calling
331 * {@link #getWidth()} and {@link #getHeight()}.
332 * </p>
333 *
334 * <p>
335 * To measure its dimensions, a view takes into account its padding. The padding
336 * is expressed in pixels for the left, top, right and bottom parts of the view.
337 * Padding can be used to offset the content of the view by a specific amount of
338 * pixels. For instance, a left padding of 2 will push the view's content by
339 * 2 pixels to the right of the left edge. Padding can be set using the
340 * {@link #setPadding(int, int, int, int)} method and queried by calling
341 * {@link #getPaddingLeft()}, {@link #getPaddingTop()},
342 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}.
343 * </p>
344 *
345 * <p>
346 * Even though a view can define a padding, it does not provide any support for
347 * margins. However, view groups provide such a support. Refer to
348 * {@link android.view.ViewGroup} and
349 * {@link android.view.ViewGroup.MarginLayoutParams} for further information.
350 * </p>
351 *
352 * <a name="Layout"></a>
353 * <h3>Layout</h3>
354 * <p>
355 * Layout is a two pass process: a measure pass and a layout pass. The measuring
356 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal
357 * of the view tree. Each view pushes dimension specifications down the tree
358 * during the recursion. At the end of the measure pass, every view has stored
359 * its measurements. The second pass happens in
360 * {@link #layout(int,int,int,int)} and is also top-down. During
361 * this pass each parent is responsible for positioning all of its children
362 * using the sizes computed in the measure pass.
363 * </p>
364 *
365 * <p>
366 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and
367 * {@link #getMeasuredHeight()} values must be set, along with those for all of
368 * that view's descendants. A view's measured width and measured height values
369 * must respect the constraints imposed by the view's parents. This guarantees
370 * that at the end of the measure pass, all parents accept all of their
371 * children's measurements. A parent view may call measure() more than once on
372 * its children. For example, the parent may measure each child once with
373 * unspecified dimensions to find out how big they want to be, then call
374 * measure() on them again with actual numbers if the sum of all the children's
375 * unconstrained sizes is too big or too small.
376 * </p>
377 *
378 * <p>
379 * The measure pass uses two classes to communicate dimensions. The
380 * {@link MeasureSpec} class is used by views to tell their parents how they
381 * want to be measured and positioned. The base LayoutParams class just
382 * describes how big the view wants to be for both width and height. For each
383 * dimension, it can specify one of:
384 * <ul>
385 * <li> an exact number
386 * <li>MATCH_PARENT, which means the view wants to be as big as its parent
387 * (minus padding)
388 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to
389 * enclose its content (plus padding).
390 * </ul>
391 * There are subclasses of LayoutParams for different subclasses of ViewGroup.
392 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds
393 * an X and Y value.
394 * </p>
395 *
396 * <p>
397 * MeasureSpecs are used to push requirements down the tree from parent to
398 * child. A MeasureSpec can be in one of three modes:
399 * <ul>
400 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
401 * of a child view. For example, a LinearLayout may call measure() on its child
402 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
403 * tall the child view wants to be given a width of 240 pixels.
404 * <li>EXACTLY: This is used by the parent to impose an exact size on the
405 * child. The child must use this size, and guarantee that all of its
406 * descendants will fit within this size.
407 * <li>AT_MOST: This is used by the parent to impose a maximum size on the
408 * child. The child must gurantee that it and all of its descendants will fit
409 * within this size.
410 * </ul>
411 * </p>
412 *
413 * <p>
414 * To intiate a layout, call {@link #requestLayout}. This method is typically
415 * called by a view on itself when it believes that is can no longer fit within
416 * its current bounds.
417 * </p>
418 *
419 * <a name="Drawing"></a>
420 * <h3>Drawing</h3>
421 * <p>
422 * Drawing is handled by walking the tree and rendering each view that
423 * intersects the invalid region. Because the tree is traversed in-order,
424 * this means that parents will draw before (i.e., behind) their children, with
425 * siblings drawn in the order they appear in the tree.
426 * If you set a background drawable for a View, then the View will draw it for you
427 * before calling back to its <code>onDraw()</code> method.
428 * </p>
429 *
430 * <p>
431 * Note that the framework will not draw views that are not in the invalid region.
432 * </p>
433 *
434 * <p>
435 * To force a view to draw, call {@link #invalidate()}.
436 * </p>
437 *
438 * <a name="EventHandlingThreading"></a>
439 * <h3>Event Handling and Threading</h3>
440 * <p>
441 * The basic cycle of a view is as follows:
442 * <ol>
443 * <li>An event comes in and is dispatched to the appropriate view. The view
444 * handles the event and notifies any listeners.</li>
445 * <li>If in the course of processing the event, the view's bounds may need
446 * to be changed, the view will call {@link #requestLayout()}.</li>
447 * <li>Similarly, if in the course of processing the event the view's appearance
448 * may need to be changed, the view will call {@link #invalidate()}.</li>
449 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
450 * the framework will take care of measuring, laying out, and drawing the tree
451 * as appropriate.</li>
452 * </ol>
453 * </p>
454 *
455 * <p><em>Note: The entire view tree is single threaded. You must always be on
456 * the UI thread when calling any method on any view.</em>
457 * If you are doing work on other threads and want to update the state of a view
458 * from that thread, you should use a {@link Handler}.
459 * </p>
460 *
461 * <a name="FocusHandling"></a>
462 * <h3>Focus Handling</h3>
463 * <p>
464 * The framework will handle routine focus movement in response to user input.
465 * This includes changing the focus as views are removed or hidden, or as new
466 * views become available. Views indicate their willingness to take focus
467 * through the {@link #isFocusable} method. To change whether a view can take
468 * focus, call {@link #setFocusable(boolean)}.  When in touch mode (see notes below)
469 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
470 * and can change this via {@link #setFocusableInTouchMode(boolean)}.
471 * </p>
472 * <p>
473 * Focus movement is based on an algorithm which finds the nearest neighbor in a
474 * given direction. In rare cases, the default algorithm may not match the
475 * intended behavior of the developer. In these situations, you can provide
476 * explicit overrides by using these XML attributes in the layout file:
477 * <pre>
478 * nextFocusDown
479 * nextFocusLeft
480 * nextFocusRight
481 * nextFocusUp
482 * </pre>
483 * </p>
484 *
485 *
486 * <p>
487 * To get a particular view to take focus, call {@link #requestFocus()}.
488 * </p>
489 *
490 * <a name="TouchMode"></a>
491 * <h3>Touch Mode</h3>
492 * <p>
493 * When a user is navigating a user interface via directional keys such as a D-pad, it is
494 * necessary to give focus to actionable items such as buttons so the user can see
495 * what will take input.  If the device has touch capabilities, however, and the user
496 * begins interacting with the interface by touching it, it is no longer necessary to
497 * always highlight, or give focus to, a particular view.  This motivates a mode
498 * for interaction named 'touch mode'.
499 * </p>
500 * <p>
501 * For a touch capable device, once the user touches the screen, the device
502 * will enter touch mode.  From this point onward, only views for which
503 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
504 * Other views that are touchable, like buttons, will not take focus when touched; they will
505 * only fire the on click listeners.
506 * </p>
507 * <p>
508 * Any time a user hits a directional key, such as a D-pad direction, the view device will
509 * exit touch mode, and find a view to take focus, so that the user may resume interacting
510 * with the user interface without touching the screen again.
511 * </p>
512 * <p>
513 * The touch mode state is maintained across {@link android.app.Activity}s.  Call
514 * {@link #isInTouchMode} to see whether the device is currently in touch mode.
515 * </p>
516 *
517 * <a name="Scrolling"></a>
518 * <h3>Scrolling</h3>
519 * <p>
520 * The framework provides basic support for views that wish to internally
521 * scroll their content. This includes keeping track of the X and Y scroll
522 * offset as well as mechanisms for drawing scrollbars. See
523 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and
524 * {@link #awakenScrollBars()} for more details.
525 * </p>
526 *
527 * <a name="Tags"></a>
528 * <h3>Tags</h3>
529 * <p>
530 * Unlike IDs, tags are not used to identify views. Tags are essentially an
531 * extra piece of information that can be associated with a view. They are most
532 * often used as a convenience to store data related to views in the views
533 * themselves rather than by putting them in a separate structure.
534 * </p>
535 *
536 * <a name="Animation"></a>
537 * <h3>Animation</h3>
538 * <p>
539 * You can attach an {@link Animation} object to a view using
540 * {@link #setAnimation(Animation)} or
541 * {@link #startAnimation(Animation)}. The animation can alter the scale,
542 * rotation, translation and alpha of a view over time. If the animation is
543 * attached to a view that has children, the animation will affect the entire
544 * subtree rooted by that node. When an animation is started, the framework will
545 * take care of redrawing the appropriate views until the animation completes.
546 * </p>
547 * <p>
548 * Starting with Android 3.0, the preferred way of animating views is to use the
549 * {@link android.animation} package APIs.
550 * </p>
551 *
552 * <a name="Security"></a>
553 * <h3>Security</h3>
554 * <p>
555 * Sometimes it is essential that an application be able to verify that an action
556 * is being performed with the full knowledge and consent of the user, such as
557 * granting a permission request, making a purchase or clicking on an advertisement.
558 * Unfortunately, a malicious application could try to spoof the user into
559 * performing these actions, unaware, by concealing the intended purpose of the view.
560 * As a remedy, the framework offers a touch filtering mechanism that can be used to
561 * improve the security of views that provide access to sensitive functionality.
562 * </p><p>
563 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the
564 * android:filterTouchesWhenObscured layout attribute to true.  When enabled, the framework
565 * will discard touches that are received whenever the view's window is obscured by
566 * another visible window.  As a result, the view will not receive touches whenever a
567 * toast, dialog or other window appears above the view's window.
568 * </p><p>
569 * For more fine-grained control over security, consider overriding the
570 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own
571 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
572 * </p>
573 *
574 * @attr ref android.R.styleable#View_alpha
575 * @attr ref android.R.styleable#View_background
576 * @attr ref android.R.styleable#View_clickable
577 * @attr ref android.R.styleable#View_contentDescription
578 * @attr ref android.R.styleable#View_drawingCacheQuality
579 * @attr ref android.R.styleable#View_duplicateParentState
580 * @attr ref android.R.styleable#View_id
581 * @attr ref android.R.styleable#View_requiresFadingEdge
582 * @attr ref android.R.styleable#View_fadingEdgeLength
583 * @attr ref android.R.styleable#View_filterTouchesWhenObscured
584 * @attr ref android.R.styleable#View_fitsSystemWindows
585 * @attr ref android.R.styleable#View_isScrollContainer
586 * @attr ref android.R.styleable#View_focusable
587 * @attr ref android.R.styleable#View_focusableInTouchMode
588 * @attr ref android.R.styleable#View_hapticFeedbackEnabled
589 * @attr ref android.R.styleable#View_keepScreenOn
590 * @attr ref android.R.styleable#View_layerType
591 * @attr ref android.R.styleable#View_longClickable
592 * @attr ref android.R.styleable#View_minHeight
593 * @attr ref android.R.styleable#View_minWidth
594 * @attr ref android.R.styleable#View_nextFocusDown
595 * @attr ref android.R.styleable#View_nextFocusLeft
596 * @attr ref android.R.styleable#View_nextFocusRight
597 * @attr ref android.R.styleable#View_nextFocusUp
598 * @attr ref android.R.styleable#View_onClick
599 * @attr ref android.R.styleable#View_padding
600 * @attr ref android.R.styleable#View_paddingBottom
601 * @attr ref android.R.styleable#View_paddingLeft
602 * @attr ref android.R.styleable#View_paddingRight
603 * @attr ref android.R.styleable#View_paddingTop
604 * @attr ref android.R.styleable#View_saveEnabled
605 * @attr ref android.R.styleable#View_rotation
606 * @attr ref android.R.styleable#View_rotationX
607 * @attr ref android.R.styleable#View_rotationY
608 * @attr ref android.R.styleable#View_scaleX
609 * @attr ref android.R.styleable#View_scaleY
610 * @attr ref android.R.styleable#View_scrollX
611 * @attr ref android.R.styleable#View_scrollY
612 * @attr ref android.R.styleable#View_scrollbarSize
613 * @attr ref android.R.styleable#View_scrollbarStyle
614 * @attr ref android.R.styleable#View_scrollbars
615 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
616 * @attr ref android.R.styleable#View_scrollbarFadeDuration
617 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
618 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
619 * @attr ref android.R.styleable#View_scrollbarThumbVertical
620 * @attr ref android.R.styleable#View_scrollbarTrackVertical
621 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
622 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
623 * @attr ref android.R.styleable#View_soundEffectsEnabled
624 * @attr ref android.R.styleable#View_tag
625 * @attr ref android.R.styleable#View_transformPivotX
626 * @attr ref android.R.styleable#View_transformPivotY
627 * @attr ref android.R.styleable#View_translationX
628 * @attr ref android.R.styleable#View_translationY
629 * @attr ref android.R.styleable#View_visibility
630 *
631 * @see android.view.ViewGroup
632 */
633public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
634        AccessibilityEventSource {
635    private static final boolean DBG = false;
636
637    /**
638     * The logging tag used by this class with android.util.Log.
639     */
640    protected static final String VIEW_LOG_TAG = "View";
641
642    /**
643     * Used to mark a View that has no ID.
644     */
645    public static final int NO_ID = -1;
646
647    /**
648     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
649     * calling setFlags.
650     */
651    private static final int NOT_FOCUSABLE = 0x00000000;
652
653    /**
654     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
655     * setFlags.
656     */
657    private static final int FOCUSABLE = 0x00000001;
658
659    /**
660     * Mask for use with setFlags indicating bits used for focus.
661     */
662    private static final int FOCUSABLE_MASK = 0x00000001;
663
664    /**
665     * This view will adjust its padding to fit sytem windows (e.g. status bar)
666     */
667    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
668
669    /**
670     * This view is visible.
671     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
672     * android:visibility}.
673     */
674    public static final int VISIBLE = 0x00000000;
675
676    /**
677     * This view is invisible, but it still takes up space for layout purposes.
678     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
679     * android:visibility}.
680     */
681    public static final int INVISIBLE = 0x00000004;
682
683    /**
684     * This view is invisible, and it doesn't take any space for layout
685     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
686     * android:visibility}.
687     */
688    public static final int GONE = 0x00000008;
689
690    /**
691     * Mask for use with setFlags indicating bits used for visibility.
692     * {@hide}
693     */
694    static final int VISIBILITY_MASK = 0x0000000C;
695
696    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
697
698    /**
699     * This view is enabled. Intrepretation varies by subclass.
700     * Use with ENABLED_MASK when calling setFlags.
701     * {@hide}
702     */
703    static final int ENABLED = 0x00000000;
704
705    /**
706     * This view is disabled. Intrepretation varies by subclass.
707     * Use with ENABLED_MASK when calling setFlags.
708     * {@hide}
709     */
710    static final int DISABLED = 0x00000020;
711
712   /**
713    * Mask for use with setFlags indicating bits used for indicating whether
714    * this view is enabled
715    * {@hide}
716    */
717    static final int ENABLED_MASK = 0x00000020;
718
719    /**
720     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
721     * called and further optimizations will be performed. It is okay to have
722     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
723     * {@hide}
724     */
725    static final int WILL_NOT_DRAW = 0x00000080;
726
727    /**
728     * Mask for use with setFlags indicating bits used for indicating whether
729     * this view is will draw
730     * {@hide}
731     */
732    static final int DRAW_MASK = 0x00000080;
733
734    /**
735     * <p>This view doesn't show scrollbars.</p>
736     * {@hide}
737     */
738    static final int SCROLLBARS_NONE = 0x00000000;
739
740    /**
741     * <p>This view shows horizontal scrollbars.</p>
742     * {@hide}
743     */
744    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
745
746    /**
747     * <p>This view shows vertical scrollbars.</p>
748     * {@hide}
749     */
750    static final int SCROLLBARS_VERTICAL = 0x00000200;
751
752    /**
753     * <p>Mask for use with setFlags indicating bits used for indicating which
754     * scrollbars are enabled.</p>
755     * {@hide}
756     */
757    static final int SCROLLBARS_MASK = 0x00000300;
758
759    /**
760     * Indicates that the view should filter touches when its window is obscured.
761     * Refer to the class comments for more information about this security feature.
762     * {@hide}
763     */
764    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
765
766    // note flag value 0x00000800 is now available for next flags...
767
768    /**
769     * <p>This view doesn't show fading edges.</p>
770     * {@hide}
771     */
772    static final int FADING_EDGE_NONE = 0x00000000;
773
774    /**
775     * <p>This view shows horizontal fading edges.</p>
776     * {@hide}
777     */
778    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
779
780    /**
781     * <p>This view shows vertical fading edges.</p>
782     * {@hide}
783     */
784    static final int FADING_EDGE_VERTICAL = 0x00002000;
785
786    /**
787     * <p>Mask for use with setFlags indicating bits used for indicating which
788     * fading edges are enabled.</p>
789     * {@hide}
790     */
791    static final int FADING_EDGE_MASK = 0x00003000;
792
793    /**
794     * <p>Indicates this view can be clicked. When clickable, a View reacts
795     * to clicks by notifying the OnClickListener.<p>
796     * {@hide}
797     */
798    static final int CLICKABLE = 0x00004000;
799
800    /**
801     * <p>Indicates this view is caching its drawing into a bitmap.</p>
802     * {@hide}
803     */
804    static final int DRAWING_CACHE_ENABLED = 0x00008000;
805
806    /**
807     * <p>Indicates that no icicle should be saved for this view.<p>
808     * {@hide}
809     */
810    static final int SAVE_DISABLED = 0x000010000;
811
812    /**
813     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
814     * property.</p>
815     * {@hide}
816     */
817    static final int SAVE_DISABLED_MASK = 0x000010000;
818
819    /**
820     * <p>Indicates that no drawing cache should ever be created for this view.<p>
821     * {@hide}
822     */
823    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
824
825    /**
826     * <p>Indicates this view can take / keep focus when int touch mode.</p>
827     * {@hide}
828     */
829    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
830
831    /**
832     * <p>Enables low quality mode for the drawing cache.</p>
833     */
834    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
835
836    /**
837     * <p>Enables high quality mode for the drawing cache.</p>
838     */
839    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
840
841    /**
842     * <p>Enables automatic quality mode for the drawing cache.</p>
843     */
844    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
845
846    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
847            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
848    };
849
850    /**
851     * <p>Mask for use with setFlags indicating bits used for the cache
852     * quality property.</p>
853     * {@hide}
854     */
855    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
856
857    /**
858     * <p>
859     * Indicates this view can be long clicked. When long clickable, a View
860     * reacts to long clicks by notifying the OnLongClickListener or showing a
861     * context menu.
862     * </p>
863     * {@hide}
864     */
865    static final int LONG_CLICKABLE = 0x00200000;
866
867    /**
868     * <p>Indicates that this view gets its drawable states from its direct parent
869     * and ignores its original internal states.</p>
870     *
871     * @hide
872     */
873    static final int DUPLICATE_PARENT_STATE = 0x00400000;
874
875    /**
876     * The scrollbar style to display the scrollbars inside the content area,
877     * without increasing the padding. The scrollbars will be overlaid with
878     * translucency on the view's content.
879     */
880    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
881
882    /**
883     * The scrollbar style to display the scrollbars inside the padded area,
884     * increasing the padding of the view. The scrollbars will not overlap the
885     * content area of the view.
886     */
887    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
888
889    /**
890     * The scrollbar style to display the scrollbars at the edge of the view,
891     * without increasing the padding. The scrollbars will be overlaid with
892     * translucency.
893     */
894    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
895
896    /**
897     * The scrollbar style to display the scrollbars at the edge of the view,
898     * increasing the padding of the view. The scrollbars will only overlap the
899     * background, if any.
900     */
901    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
902
903    /**
904     * Mask to check if the scrollbar style is overlay or inset.
905     * {@hide}
906     */
907    static final int SCROLLBARS_INSET_MASK = 0x01000000;
908
909    /**
910     * Mask to check if the scrollbar style is inside or outside.
911     * {@hide}
912     */
913    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
914
915    /**
916     * Mask for scrollbar style.
917     * {@hide}
918     */
919    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
920
921    /**
922     * View flag indicating that the screen should remain on while the
923     * window containing this view is visible to the user.  This effectively
924     * takes care of automatically setting the WindowManager's
925     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
926     */
927    public static final int KEEP_SCREEN_ON = 0x04000000;
928
929    /**
930     * View flag indicating whether this view should have sound effects enabled
931     * for events such as clicking and touching.
932     */
933    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
934
935    /**
936     * View flag indicating whether this view should have haptic feedback
937     * enabled for events such as long presses.
938     */
939    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
940
941    /**
942     * <p>Indicates that the view hierarchy should stop saving state when
943     * it reaches this view.  If state saving is initiated immediately at
944     * the view, it will be allowed.
945     * {@hide}
946     */
947    static final int PARENT_SAVE_DISABLED = 0x20000000;
948
949    /**
950     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
951     * {@hide}
952     */
953    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
954
955    /**
956     * Horizontal direction of this view is from Left to Right.
957     * Use with {@link #setLayoutDirection}.
958     * {@hide}
959     */
960    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
961
962    /**
963     * Horizontal direction of this view is from Right to Left.
964     * Use with {@link #setLayoutDirection}.
965     * {@hide}
966     */
967    public static final int LAYOUT_DIRECTION_RTL = 0x40000000;
968
969    /**
970     * Horizontal direction of this view is inherited from its parent.
971     * Use with {@link #setLayoutDirection}.
972     * {@hide}
973     */
974    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
975
976    /**
977     * Horizontal direction of this view is from deduced from the default language
978     * script for the locale. Use with {@link #setLayoutDirection}.
979     * {@hide}
980     */
981    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
982
983    /**
984     * Mask for use with setFlags indicating bits used for horizontalDirection.
985     * {@hide}
986     */
987    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
988
989    /*
990     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
991     * flag value.
992     * {@hide}
993     */
994    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
995        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
996
997    /**
998     * Default horizontalDirection.
999     * {@hide}
1000     */
1001    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1002
1003    /**
1004     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1005     * should add all focusable Views regardless if they are focusable in touch mode.
1006     */
1007    public static final int FOCUSABLES_ALL = 0x00000000;
1008
1009    /**
1010     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1011     * should add only Views focusable in touch mode.
1012     */
1013    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1014
1015    /**
1016     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1017     * item.
1018     */
1019    public static final int FOCUS_BACKWARD = 0x00000001;
1020
1021    /**
1022     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1023     * item.
1024     */
1025    public static final int FOCUS_FORWARD = 0x00000002;
1026
1027    /**
1028     * Use with {@link #focusSearch(int)}. Move focus to the left.
1029     */
1030    public static final int FOCUS_LEFT = 0x00000011;
1031
1032    /**
1033     * Use with {@link #focusSearch(int)}. Move focus up.
1034     */
1035    public static final int FOCUS_UP = 0x00000021;
1036
1037    /**
1038     * Use with {@link #focusSearch(int)}. Move focus to the right.
1039     */
1040    public static final int FOCUS_RIGHT = 0x00000042;
1041
1042    /**
1043     * Use with {@link #focusSearch(int)}. Move focus down.
1044     */
1045    public static final int FOCUS_DOWN = 0x00000082;
1046
1047    /**
1048     * Bits of {@link #getMeasuredWidthAndState()} and
1049     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1050     */
1051    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1052
1053    /**
1054     * Bits of {@link #getMeasuredWidthAndState()} and
1055     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1056     */
1057    public static final int MEASURED_STATE_MASK = 0xff000000;
1058
1059    /**
1060     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1061     * for functions that combine both width and height into a single int,
1062     * such as {@link #getMeasuredState()} and the childState argument of
1063     * {@link #resolveSizeAndState(int, int, int)}.
1064     */
1065    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1066
1067    /**
1068     * Bit of {@link #getMeasuredWidthAndState()} and
1069     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1070     * is smaller that the space the view would like to have.
1071     */
1072    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1073
1074    /**
1075     * Base View state sets
1076     */
1077    // Singles
1078    /**
1079     * Indicates the view has no states set. States are used with
1080     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1081     * view depending on its state.
1082     *
1083     * @see android.graphics.drawable.Drawable
1084     * @see #getDrawableState()
1085     */
1086    protected static final int[] EMPTY_STATE_SET;
1087    /**
1088     * Indicates the view is enabled. States are used with
1089     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1090     * view depending on its state.
1091     *
1092     * @see android.graphics.drawable.Drawable
1093     * @see #getDrawableState()
1094     */
1095    protected static final int[] ENABLED_STATE_SET;
1096    /**
1097     * Indicates the view is focused. States are used with
1098     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1099     * view depending on its state.
1100     *
1101     * @see android.graphics.drawable.Drawable
1102     * @see #getDrawableState()
1103     */
1104    protected static final int[] FOCUSED_STATE_SET;
1105    /**
1106     * Indicates the view is selected. States are used with
1107     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1108     * view depending on its state.
1109     *
1110     * @see android.graphics.drawable.Drawable
1111     * @see #getDrawableState()
1112     */
1113    protected static final int[] SELECTED_STATE_SET;
1114    /**
1115     * Indicates the view is pressed. States are used with
1116     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1117     * view depending on its state.
1118     *
1119     * @see android.graphics.drawable.Drawable
1120     * @see #getDrawableState()
1121     * @hide
1122     */
1123    protected static final int[] PRESSED_STATE_SET;
1124    /**
1125     * Indicates the view's window has focus. States are used with
1126     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1127     * view depending on its state.
1128     *
1129     * @see android.graphics.drawable.Drawable
1130     * @see #getDrawableState()
1131     */
1132    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1133    // Doubles
1134    /**
1135     * Indicates the view is enabled and has the focus.
1136     *
1137     * @see #ENABLED_STATE_SET
1138     * @see #FOCUSED_STATE_SET
1139     */
1140    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1141    /**
1142     * Indicates the view is enabled and selected.
1143     *
1144     * @see #ENABLED_STATE_SET
1145     * @see #SELECTED_STATE_SET
1146     */
1147    protected static final int[] ENABLED_SELECTED_STATE_SET;
1148    /**
1149     * Indicates the view is enabled and that its window has focus.
1150     *
1151     * @see #ENABLED_STATE_SET
1152     * @see #WINDOW_FOCUSED_STATE_SET
1153     */
1154    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1155    /**
1156     * Indicates the view is focused and selected.
1157     *
1158     * @see #FOCUSED_STATE_SET
1159     * @see #SELECTED_STATE_SET
1160     */
1161    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1162    /**
1163     * Indicates the view has the focus and that its window has the focus.
1164     *
1165     * @see #FOCUSED_STATE_SET
1166     * @see #WINDOW_FOCUSED_STATE_SET
1167     */
1168    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1169    /**
1170     * Indicates the view is selected and that its window has the focus.
1171     *
1172     * @see #SELECTED_STATE_SET
1173     * @see #WINDOW_FOCUSED_STATE_SET
1174     */
1175    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1176    // Triples
1177    /**
1178     * Indicates the view is enabled, focused and selected.
1179     *
1180     * @see #ENABLED_STATE_SET
1181     * @see #FOCUSED_STATE_SET
1182     * @see #SELECTED_STATE_SET
1183     */
1184    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1185    /**
1186     * Indicates the view is enabled, focused and its window has the focus.
1187     *
1188     * @see #ENABLED_STATE_SET
1189     * @see #FOCUSED_STATE_SET
1190     * @see #WINDOW_FOCUSED_STATE_SET
1191     */
1192    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1193    /**
1194     * Indicates the view is enabled, selected and its window has the focus.
1195     *
1196     * @see #ENABLED_STATE_SET
1197     * @see #SELECTED_STATE_SET
1198     * @see #WINDOW_FOCUSED_STATE_SET
1199     */
1200    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1201    /**
1202     * Indicates the view is focused, selected and its window has the focus.
1203     *
1204     * @see #FOCUSED_STATE_SET
1205     * @see #SELECTED_STATE_SET
1206     * @see #WINDOW_FOCUSED_STATE_SET
1207     */
1208    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1209    /**
1210     * Indicates the view is enabled, focused, selected and its window
1211     * has the focus.
1212     *
1213     * @see #ENABLED_STATE_SET
1214     * @see #FOCUSED_STATE_SET
1215     * @see #SELECTED_STATE_SET
1216     * @see #WINDOW_FOCUSED_STATE_SET
1217     */
1218    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1219    /**
1220     * Indicates the view is pressed and its window has the focus.
1221     *
1222     * @see #PRESSED_STATE_SET
1223     * @see #WINDOW_FOCUSED_STATE_SET
1224     */
1225    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1226    /**
1227     * Indicates the view is pressed and selected.
1228     *
1229     * @see #PRESSED_STATE_SET
1230     * @see #SELECTED_STATE_SET
1231     */
1232    protected static final int[] PRESSED_SELECTED_STATE_SET;
1233    /**
1234     * Indicates the view is pressed, selected and its window has the focus.
1235     *
1236     * @see #PRESSED_STATE_SET
1237     * @see #SELECTED_STATE_SET
1238     * @see #WINDOW_FOCUSED_STATE_SET
1239     */
1240    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1241    /**
1242     * Indicates the view is pressed and focused.
1243     *
1244     * @see #PRESSED_STATE_SET
1245     * @see #FOCUSED_STATE_SET
1246     */
1247    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1248    /**
1249     * Indicates the view is pressed, focused and its window has the focus.
1250     *
1251     * @see #PRESSED_STATE_SET
1252     * @see #FOCUSED_STATE_SET
1253     * @see #WINDOW_FOCUSED_STATE_SET
1254     */
1255    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1256    /**
1257     * Indicates the view is pressed, focused and selected.
1258     *
1259     * @see #PRESSED_STATE_SET
1260     * @see #SELECTED_STATE_SET
1261     * @see #FOCUSED_STATE_SET
1262     */
1263    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1264    /**
1265     * Indicates the view is pressed, focused, selected and its window has the focus.
1266     *
1267     * @see #PRESSED_STATE_SET
1268     * @see #FOCUSED_STATE_SET
1269     * @see #SELECTED_STATE_SET
1270     * @see #WINDOW_FOCUSED_STATE_SET
1271     */
1272    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1273    /**
1274     * Indicates the view is pressed and enabled.
1275     *
1276     * @see #PRESSED_STATE_SET
1277     * @see #ENABLED_STATE_SET
1278     */
1279    protected static final int[] PRESSED_ENABLED_STATE_SET;
1280    /**
1281     * Indicates the view is pressed, enabled and its window has the focus.
1282     *
1283     * @see #PRESSED_STATE_SET
1284     * @see #ENABLED_STATE_SET
1285     * @see #WINDOW_FOCUSED_STATE_SET
1286     */
1287    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1288    /**
1289     * Indicates the view is pressed, enabled and selected.
1290     *
1291     * @see #PRESSED_STATE_SET
1292     * @see #ENABLED_STATE_SET
1293     * @see #SELECTED_STATE_SET
1294     */
1295    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1296    /**
1297     * Indicates the view is pressed, enabled, selected and its window has the
1298     * focus.
1299     *
1300     * @see #PRESSED_STATE_SET
1301     * @see #ENABLED_STATE_SET
1302     * @see #SELECTED_STATE_SET
1303     * @see #WINDOW_FOCUSED_STATE_SET
1304     */
1305    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1306    /**
1307     * Indicates the view is pressed, enabled and focused.
1308     *
1309     * @see #PRESSED_STATE_SET
1310     * @see #ENABLED_STATE_SET
1311     * @see #FOCUSED_STATE_SET
1312     */
1313    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1314    /**
1315     * Indicates the view is pressed, enabled, focused and its window has the
1316     * focus.
1317     *
1318     * @see #PRESSED_STATE_SET
1319     * @see #ENABLED_STATE_SET
1320     * @see #FOCUSED_STATE_SET
1321     * @see #WINDOW_FOCUSED_STATE_SET
1322     */
1323    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1324    /**
1325     * Indicates the view is pressed, enabled, focused and selected.
1326     *
1327     * @see #PRESSED_STATE_SET
1328     * @see #ENABLED_STATE_SET
1329     * @see #SELECTED_STATE_SET
1330     * @see #FOCUSED_STATE_SET
1331     */
1332    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1333    /**
1334     * Indicates the view is pressed, enabled, focused, selected and its window
1335     * has the focus.
1336     *
1337     * @see #PRESSED_STATE_SET
1338     * @see #ENABLED_STATE_SET
1339     * @see #SELECTED_STATE_SET
1340     * @see #FOCUSED_STATE_SET
1341     * @see #WINDOW_FOCUSED_STATE_SET
1342     */
1343    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1344
1345    /**
1346     * The order here is very important to {@link #getDrawableState()}
1347     */
1348    private static final int[][] VIEW_STATE_SETS;
1349
1350    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1351    static final int VIEW_STATE_SELECTED = 1 << 1;
1352    static final int VIEW_STATE_FOCUSED = 1 << 2;
1353    static final int VIEW_STATE_ENABLED = 1 << 3;
1354    static final int VIEW_STATE_PRESSED = 1 << 4;
1355    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1356    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1357    static final int VIEW_STATE_HOVERED = 1 << 7;
1358    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1359    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1360
1361    static final int[] VIEW_STATE_IDS = new int[] {
1362        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1363        R.attr.state_selected,          VIEW_STATE_SELECTED,
1364        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1365        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1366        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1367        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1368        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1369        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1370        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1371        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1372    };
1373
1374    static {
1375        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1376            throw new IllegalStateException(
1377                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1378        }
1379        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1380        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1381            int viewState = R.styleable.ViewDrawableStates[i];
1382            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1383                if (VIEW_STATE_IDS[j] == viewState) {
1384                    orderedIds[i * 2] = viewState;
1385                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1386                }
1387            }
1388        }
1389        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1390        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1391        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1392            int numBits = Integer.bitCount(i);
1393            int[] set = new int[numBits];
1394            int pos = 0;
1395            for (int j = 0; j < orderedIds.length; j += 2) {
1396                if ((i & orderedIds[j+1]) != 0) {
1397                    set[pos++] = orderedIds[j];
1398                }
1399            }
1400            VIEW_STATE_SETS[i] = set;
1401        }
1402
1403        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1404        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1405        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1406        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1407                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1408        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1409        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1410                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1411        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1413        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1414                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1415                | VIEW_STATE_FOCUSED];
1416        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1417        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1419        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1421        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1422                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1423                | VIEW_STATE_ENABLED];
1424        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1426        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1427                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1428                | VIEW_STATE_ENABLED];
1429        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1430                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1431                | VIEW_STATE_ENABLED];
1432        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1433                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1434                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1435
1436        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1437        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1439        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1441        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1442                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1443                | VIEW_STATE_PRESSED];
1444        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1446        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1447                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1448                | VIEW_STATE_PRESSED];
1449        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1450                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1451                | VIEW_STATE_PRESSED];
1452        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1453                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1454                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1455        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1457        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1458                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1459                | VIEW_STATE_PRESSED];
1460        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1461                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1462                | VIEW_STATE_PRESSED];
1463        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1464                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1465                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1466        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1467                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1468                | VIEW_STATE_PRESSED];
1469        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1470                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1471                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1472        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1473                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1474                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1475        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1476                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1477                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1478                | VIEW_STATE_PRESSED];
1479    }
1480
1481    /**
1482     * Accessibility event types that are dispatched for text population.
1483     */
1484    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1485            AccessibilityEvent.TYPE_VIEW_CLICKED
1486            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1487            | AccessibilityEvent.TYPE_VIEW_SELECTED
1488            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1489            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1490            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1491            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1492            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1493            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1494
1495    /**
1496     * Temporary Rect currently for use in setBackground().  This will probably
1497     * be extended in the future to hold our own class with more than just
1498     * a Rect. :)
1499     */
1500    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1501
1502    /**
1503     * Map used to store views' tags.
1504     */
1505    private SparseArray<Object> mKeyedTags;
1506
1507    /**
1508     * The next available accessiiblity id.
1509     */
1510    private static int sNextAccessibilityViewId;
1511
1512    /**
1513     * The animation currently associated with this view.
1514     * @hide
1515     */
1516    protected Animation mCurrentAnimation = null;
1517
1518    /**
1519     * Width as measured during measure pass.
1520     * {@hide}
1521     */
1522    @ViewDebug.ExportedProperty(category = "measurement")
1523    int mMeasuredWidth;
1524
1525    /**
1526     * Height as measured during measure pass.
1527     * {@hide}
1528     */
1529    @ViewDebug.ExportedProperty(category = "measurement")
1530    int mMeasuredHeight;
1531
1532    /**
1533     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1534     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1535     * its display list. This flag, used only when hw accelerated, allows us to clear the
1536     * flag while retaining this information until it's needed (at getDisplayList() time and
1537     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1538     *
1539     * {@hide}
1540     */
1541    boolean mRecreateDisplayList = false;
1542
1543    /**
1544     * The view's identifier.
1545     * {@hide}
1546     *
1547     * @see #setId(int)
1548     * @see #getId()
1549     */
1550    @ViewDebug.ExportedProperty(resolveId = true)
1551    int mID = NO_ID;
1552
1553    /**
1554     * The stable ID of this view for accessibility purposes.
1555     */
1556    int mAccessibilityViewId = NO_ID;
1557
1558    /**
1559     * The view's tag.
1560     * {@hide}
1561     *
1562     * @see #setTag(Object)
1563     * @see #getTag()
1564     */
1565    protected Object mTag;
1566
1567    // for mPrivateFlags:
1568    /** {@hide} */
1569    static final int WANTS_FOCUS                    = 0x00000001;
1570    /** {@hide} */
1571    static final int FOCUSED                        = 0x00000002;
1572    /** {@hide} */
1573    static final int SELECTED                       = 0x00000004;
1574    /** {@hide} */
1575    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1576    /** {@hide} */
1577    static final int HAS_BOUNDS                     = 0x00000010;
1578    /** {@hide} */
1579    static final int DRAWN                          = 0x00000020;
1580    /**
1581     * When this flag is set, this view is running an animation on behalf of its
1582     * children and should therefore not cancel invalidate requests, even if they
1583     * lie outside of this view's bounds.
1584     *
1585     * {@hide}
1586     */
1587    static final int DRAW_ANIMATION                 = 0x00000040;
1588    /** {@hide} */
1589    static final int SKIP_DRAW                      = 0x00000080;
1590    /** {@hide} */
1591    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1592    /** {@hide} */
1593    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1594    /** {@hide} */
1595    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1596    /** {@hide} */
1597    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1598    /** {@hide} */
1599    static final int FORCE_LAYOUT                   = 0x00001000;
1600    /** {@hide} */
1601    static final int LAYOUT_REQUIRED                = 0x00002000;
1602
1603    private static final int PRESSED                = 0x00004000;
1604
1605    /** {@hide} */
1606    static final int DRAWING_CACHE_VALID            = 0x00008000;
1607    /**
1608     * Flag used to indicate that this view should be drawn once more (and only once
1609     * more) after its animation has completed.
1610     * {@hide}
1611     */
1612    static final int ANIMATION_STARTED              = 0x00010000;
1613
1614    private static final int SAVE_STATE_CALLED      = 0x00020000;
1615
1616    /**
1617     * Indicates that the View returned true when onSetAlpha() was called and that
1618     * the alpha must be restored.
1619     * {@hide}
1620     */
1621    static final int ALPHA_SET                      = 0x00040000;
1622
1623    /**
1624     * Set by {@link #setScrollContainer(boolean)}.
1625     */
1626    static final int SCROLL_CONTAINER               = 0x00080000;
1627
1628    /**
1629     * Set by {@link #setScrollContainer(boolean)}.
1630     */
1631    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1632
1633    /**
1634     * View flag indicating whether this view was invalidated (fully or partially.)
1635     *
1636     * @hide
1637     */
1638    static final int DIRTY                          = 0x00200000;
1639
1640    /**
1641     * View flag indicating whether this view was invalidated by an opaque
1642     * invalidate request.
1643     *
1644     * @hide
1645     */
1646    static final int DIRTY_OPAQUE                   = 0x00400000;
1647
1648    /**
1649     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1650     *
1651     * @hide
1652     */
1653    static final int DIRTY_MASK                     = 0x00600000;
1654
1655    /**
1656     * Indicates whether the background is opaque.
1657     *
1658     * @hide
1659     */
1660    static final int OPAQUE_BACKGROUND              = 0x00800000;
1661
1662    /**
1663     * Indicates whether the scrollbars are opaque.
1664     *
1665     * @hide
1666     */
1667    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1668
1669    /**
1670     * Indicates whether the view is opaque.
1671     *
1672     * @hide
1673     */
1674    static final int OPAQUE_MASK                    = 0x01800000;
1675
1676    /**
1677     * Indicates a prepressed state;
1678     * the short time between ACTION_DOWN and recognizing
1679     * a 'real' press. Prepressed is used to recognize quick taps
1680     * even when they are shorter than ViewConfiguration.getTapTimeout().
1681     *
1682     * @hide
1683     */
1684    private static final int PREPRESSED             = 0x02000000;
1685
1686    /**
1687     * Indicates whether the view is temporarily detached.
1688     *
1689     * @hide
1690     */
1691    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1692
1693    /**
1694     * Indicates that we should awaken scroll bars once attached
1695     *
1696     * @hide
1697     */
1698    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1699
1700    /**
1701     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1702     * @hide
1703     */
1704    private static final int HOVERED              = 0x10000000;
1705
1706    /**
1707     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1708     * for transform operations
1709     *
1710     * @hide
1711     */
1712    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1713
1714    /** {@hide} */
1715    static final int ACTIVATED                    = 0x40000000;
1716
1717    /**
1718     * Indicates that this view was specifically invalidated, not just dirtied because some
1719     * child view was invalidated. The flag is used to determine when we need to recreate
1720     * a view's display list (as opposed to just returning a reference to its existing
1721     * display list).
1722     *
1723     * @hide
1724     */
1725    static final int INVALIDATED                  = 0x80000000;
1726
1727    /* Masks for mPrivateFlags2 */
1728
1729    /**
1730     * Indicates that this view has reported that it can accept the current drag's content.
1731     * Cleared when the drag operation concludes.
1732     * @hide
1733     */
1734    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1735
1736    /**
1737     * Indicates that this view is currently directly under the drag location in a
1738     * drag-and-drop operation involving content that it can accept.  Cleared when
1739     * the drag exits the view, or when the drag operation concludes.
1740     * @hide
1741     */
1742    static final int DRAG_HOVERED                 = 0x00000002;
1743
1744    /**
1745     * Indicates whether the view layout direction has been resolved and drawn to the
1746     * right-to-left direction.
1747     *
1748     * @hide
1749     */
1750    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1751
1752    /**
1753     * Indicates whether the view layout direction has been resolved.
1754     *
1755     * @hide
1756     */
1757    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1758
1759
1760    /* End of masks for mPrivateFlags2 */
1761
1762    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1763
1764    /**
1765     * Always allow a user to over-scroll this view, provided it is a
1766     * view that can scroll.
1767     *
1768     * @see #getOverScrollMode()
1769     * @see #setOverScrollMode(int)
1770     */
1771    public static final int OVER_SCROLL_ALWAYS = 0;
1772
1773    /**
1774     * Allow a user to over-scroll this view only if the content is large
1775     * enough to meaningfully scroll, provided it is a view that can scroll.
1776     *
1777     * @see #getOverScrollMode()
1778     * @see #setOverScrollMode(int)
1779     */
1780    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1781
1782    /**
1783     * Never allow a user to over-scroll this view.
1784     *
1785     * @see #getOverScrollMode()
1786     * @see #setOverScrollMode(int)
1787     */
1788    public static final int OVER_SCROLL_NEVER = 2;
1789
1790    /**
1791     * View has requested the system UI (status bar) to be visible (the default).
1792     *
1793     * @see #setSystemUiVisibility(int)
1794     */
1795    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1796
1797    /**
1798     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1799     *
1800     * This is for use in games, book readers, video players, or any other "immersive" application
1801     * where the usual system chrome is deemed too distracting.
1802     *
1803     * In low profile mode, the status bar and/or navigation icons may dim.
1804     *
1805     * @see #setSystemUiVisibility(int)
1806     */
1807    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1808
1809    /**
1810     * View has requested that the system navigation be temporarily hidden.
1811     *
1812     * This is an even less obtrusive state than that called for by
1813     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1814     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1815     * those to disappear. This is useful (in conjunction with the
1816     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1817     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1818     * window flags) for displaying content using every last pixel on the display.
1819     *
1820     * There is a limitation: because navigation controls are so important, the least user
1821     * interaction will cause them to reappear immediately.
1822     *
1823     * @see #setSystemUiVisibility(int)
1824     */
1825    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1826
1827    /**
1828     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1829     */
1830    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1831
1832    /**
1833     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1834     */
1835    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1836
1837    /**
1838     * @hide
1839     *
1840     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1841     * out of the public fields to keep the undefined bits out of the developer's way.
1842     *
1843     * Flag to make the status bar not expandable.  Unless you also
1844     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1845     */
1846    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1847
1848    /**
1849     * @hide
1850     *
1851     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1852     * out of the public fields to keep the undefined bits out of the developer's way.
1853     *
1854     * Flag to hide notification icons and scrolling ticker text.
1855     */
1856    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1857
1858    /**
1859     * @hide
1860     *
1861     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1862     * out of the public fields to keep the undefined bits out of the developer's way.
1863     *
1864     * Flag to disable incoming notification alerts.  This will not block
1865     * icons, but it will block sound, vibrating and other visual or aural notifications.
1866     */
1867    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1868
1869    /**
1870     * @hide
1871     *
1872     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1873     * out of the public fields to keep the undefined bits out of the developer's way.
1874     *
1875     * Flag to hide only the scrolling ticker.  Note that
1876     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1877     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1878     */
1879    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1880
1881    /**
1882     * @hide
1883     *
1884     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1885     * out of the public fields to keep the undefined bits out of the developer's way.
1886     *
1887     * Flag to hide the center system info area.
1888     */
1889    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1890
1891    /**
1892     * @hide
1893     *
1894     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1895     * out of the public fields to keep the undefined bits out of the developer's way.
1896     *
1897     * Flag to hide only the home button.  Don't use this
1898     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1899     */
1900    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
1901
1902    /**
1903     * @hide
1904     *
1905     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1906     * out of the public fields to keep the undefined bits out of the developer's way.
1907     *
1908     * Flag to hide only the back button. Don't use this
1909     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1910     */
1911    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1912
1913    /**
1914     * @hide
1915     *
1916     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1917     * out of the public fields to keep the undefined bits out of the developer's way.
1918     *
1919     * Flag to hide only the clock.  You might use this if your activity has
1920     * its own clock making the status bar's clock redundant.
1921     */
1922    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1923
1924    /**
1925     * @hide
1926     *
1927     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1928     * out of the public fields to keep the undefined bits out of the developer's way.
1929     *
1930     * Flag to hide only the recent apps button. Don't use this
1931     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1932     */
1933    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
1934
1935    /**
1936     * @hide
1937     *
1938     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
1939     *
1940     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
1941     */
1942    @Deprecated
1943    public static final int STATUS_BAR_DISABLE_NAVIGATION =
1944            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
1945
1946    /**
1947     * @hide
1948     */
1949    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1950
1951    /**
1952     * These are the system UI flags that can be cleared by events outside
1953     * of an application.  Currently this is just the ability to tap on the
1954     * screen while hiding the navigation bar to have it return.
1955     * @hide
1956     */
1957    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
1958            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
1959
1960    /**
1961     * Find views that render the specified text.
1962     *
1963     * @see #findViewsWithText(ArrayList, CharSequence, int)
1964     */
1965    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1966
1967    /**
1968     * Find find views that contain the specified content description.
1969     *
1970     * @see #findViewsWithText(ArrayList, CharSequence, int)
1971     */
1972    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1973
1974    /**
1975     * Find views that contain {@link AccessibilityNodeProvider}. Such
1976     * a View is a root of virtual view hierarchy and may contain the searched
1977     * text. If this flag is set Views with providers are automatically
1978     * added and it is a responsibility of the client to call the APIs of
1979     * the provider to determine whether the virtual tree rooted at this View
1980     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
1981     * represeting the virtual views with this text.
1982     *
1983     * @see #findViewsWithText(ArrayList, CharSequence, int)
1984     *
1985     * @hide
1986     */
1987    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
1988
1989    /**
1990     * Controls the over-scroll mode for this view.
1991     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
1992     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
1993     * and {@link #OVER_SCROLL_NEVER}.
1994     */
1995    private int mOverScrollMode;
1996
1997    /**
1998     * The parent this view is attached to.
1999     * {@hide}
2000     *
2001     * @see #getParent()
2002     */
2003    protected ViewParent mParent;
2004
2005    /**
2006     * {@hide}
2007     */
2008    AttachInfo mAttachInfo;
2009
2010    /**
2011     * {@hide}
2012     */
2013    @ViewDebug.ExportedProperty(flagMapping = {
2014        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2015                name = "FORCE_LAYOUT"),
2016        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2017                name = "LAYOUT_REQUIRED"),
2018        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2019            name = "DRAWING_CACHE_INVALID", outputIf = false),
2020        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2021        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2022        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2023        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2024    })
2025    int mPrivateFlags;
2026    int mPrivateFlags2;
2027
2028    /**
2029     * This view's request for the visibility of the status bar.
2030     * @hide
2031     */
2032    @ViewDebug.ExportedProperty(flagMapping = {
2033        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2034                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2035                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2036        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2037                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2038                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2039        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2040                                equals = SYSTEM_UI_FLAG_VISIBLE,
2041                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2042    })
2043    int mSystemUiVisibility;
2044
2045    /**
2046     * Count of how many windows this view has been attached to.
2047     */
2048    int mWindowAttachCount;
2049
2050    /**
2051     * The layout parameters associated with this view and used by the parent
2052     * {@link android.view.ViewGroup} to determine how this view should be
2053     * laid out.
2054     * {@hide}
2055     */
2056    protected ViewGroup.LayoutParams mLayoutParams;
2057
2058    /**
2059     * The view flags hold various views states.
2060     * {@hide}
2061     */
2062    @ViewDebug.ExportedProperty
2063    int mViewFlags;
2064
2065    static class TransformationInfo {
2066        /**
2067         * The transform matrix for the View. This transform is calculated internally
2068         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2069         * is used by default. Do *not* use this variable directly; instead call
2070         * getMatrix(), which will automatically recalculate the matrix if necessary
2071         * to get the correct matrix based on the latest rotation and scale properties.
2072         */
2073        private final Matrix mMatrix = new Matrix();
2074
2075        /**
2076         * The transform matrix for the View. This transform is calculated internally
2077         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2078         * is used by default. Do *not* use this variable directly; instead call
2079         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2080         * to get the correct matrix based on the latest rotation and scale properties.
2081         */
2082        private Matrix mInverseMatrix;
2083
2084        /**
2085         * An internal variable that tracks whether we need to recalculate the
2086         * transform matrix, based on whether the rotation or scaleX/Y properties
2087         * have changed since the matrix was last calculated.
2088         */
2089        boolean mMatrixDirty = false;
2090
2091        /**
2092         * An internal variable that tracks whether we need to recalculate the
2093         * transform matrix, based on whether the rotation or scaleX/Y properties
2094         * have changed since the matrix was last calculated.
2095         */
2096        private boolean mInverseMatrixDirty = true;
2097
2098        /**
2099         * A variable that tracks whether we need to recalculate the
2100         * transform matrix, based on whether the rotation or scaleX/Y properties
2101         * have changed since the matrix was last calculated. This variable
2102         * is only valid after a call to updateMatrix() or to a function that
2103         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2104         */
2105        private boolean mMatrixIsIdentity = true;
2106
2107        /**
2108         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2109         */
2110        private Camera mCamera = null;
2111
2112        /**
2113         * This matrix is used when computing the matrix for 3D rotations.
2114         */
2115        private Matrix matrix3D = null;
2116
2117        /**
2118         * These prev values are used to recalculate a centered pivot point when necessary. The
2119         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2120         * set), so thes values are only used then as well.
2121         */
2122        private int mPrevWidth = -1;
2123        private int mPrevHeight = -1;
2124
2125        /**
2126         * The degrees rotation around the vertical axis through the pivot point.
2127         */
2128        @ViewDebug.ExportedProperty
2129        float mRotationY = 0f;
2130
2131        /**
2132         * The degrees rotation around the horizontal axis through the pivot point.
2133         */
2134        @ViewDebug.ExportedProperty
2135        float mRotationX = 0f;
2136
2137        /**
2138         * The degrees rotation around the pivot point.
2139         */
2140        @ViewDebug.ExportedProperty
2141        float mRotation = 0f;
2142
2143        /**
2144         * The amount of translation of the object away from its left property (post-layout).
2145         */
2146        @ViewDebug.ExportedProperty
2147        float mTranslationX = 0f;
2148
2149        /**
2150         * The amount of translation of the object away from its top property (post-layout).
2151         */
2152        @ViewDebug.ExportedProperty
2153        float mTranslationY = 0f;
2154
2155        /**
2156         * The amount of scale in the x direction around the pivot point. A
2157         * value of 1 means no scaling is applied.
2158         */
2159        @ViewDebug.ExportedProperty
2160        float mScaleX = 1f;
2161
2162        /**
2163         * The amount of scale in the y direction around the pivot point. A
2164         * value of 1 means no scaling is applied.
2165         */
2166        @ViewDebug.ExportedProperty
2167        float mScaleY = 1f;
2168
2169        /**
2170         * The x location of the point around which the view is rotated and scaled.
2171         */
2172        @ViewDebug.ExportedProperty
2173        float mPivotX = 0f;
2174
2175        /**
2176         * The y location of the point around which the view is rotated and scaled.
2177         */
2178        @ViewDebug.ExportedProperty
2179        float mPivotY = 0f;
2180
2181        /**
2182         * The opacity of the View. This is a value from 0 to 1, where 0 means
2183         * completely transparent and 1 means completely opaque.
2184         */
2185        @ViewDebug.ExportedProperty
2186        float mAlpha = 1f;
2187    }
2188
2189    TransformationInfo mTransformationInfo;
2190
2191    private boolean mLastIsOpaque;
2192
2193    /**
2194     * Convenience value to check for float values that are close enough to zero to be considered
2195     * zero.
2196     */
2197    private static final float NONZERO_EPSILON = .001f;
2198
2199    /**
2200     * The distance in pixels from the left edge of this view's parent
2201     * to the left edge of this view.
2202     * {@hide}
2203     */
2204    @ViewDebug.ExportedProperty(category = "layout")
2205    protected int mLeft;
2206    /**
2207     * The distance in pixels from the left edge of this view's parent
2208     * to the right edge of this view.
2209     * {@hide}
2210     */
2211    @ViewDebug.ExportedProperty(category = "layout")
2212    protected int mRight;
2213    /**
2214     * The distance in pixels from the top edge of this view's parent
2215     * to the top edge of this view.
2216     * {@hide}
2217     */
2218    @ViewDebug.ExportedProperty(category = "layout")
2219    protected int mTop;
2220    /**
2221     * The distance in pixels from the top edge of this view's parent
2222     * to the bottom edge of this view.
2223     * {@hide}
2224     */
2225    @ViewDebug.ExportedProperty(category = "layout")
2226    protected int mBottom;
2227
2228    /**
2229     * The offset, in pixels, by which the content of this view is scrolled
2230     * horizontally.
2231     * {@hide}
2232     */
2233    @ViewDebug.ExportedProperty(category = "scrolling")
2234    protected int mScrollX;
2235    /**
2236     * The offset, in pixels, by which the content of this view is scrolled
2237     * vertically.
2238     * {@hide}
2239     */
2240    @ViewDebug.ExportedProperty(category = "scrolling")
2241    protected int mScrollY;
2242
2243    /**
2244     * The left padding in pixels, that is the distance in pixels between the
2245     * left edge of this view and the left edge of its content.
2246     * {@hide}
2247     */
2248    @ViewDebug.ExportedProperty(category = "padding")
2249    protected int mPaddingLeft;
2250    /**
2251     * The right padding in pixels, that is the distance in pixels between the
2252     * right edge of this view and the right edge of its content.
2253     * {@hide}
2254     */
2255    @ViewDebug.ExportedProperty(category = "padding")
2256    protected int mPaddingRight;
2257    /**
2258     * The top padding in pixels, that is the distance in pixels between the
2259     * top edge of this view and the top edge of its content.
2260     * {@hide}
2261     */
2262    @ViewDebug.ExportedProperty(category = "padding")
2263    protected int mPaddingTop;
2264    /**
2265     * The bottom padding in pixels, that is the distance in pixels between the
2266     * bottom edge of this view and the bottom edge of its content.
2267     * {@hide}
2268     */
2269    @ViewDebug.ExportedProperty(category = "padding")
2270    protected int mPaddingBottom;
2271
2272    /**
2273     * Briefly describes the view and is primarily used for accessibility support.
2274     */
2275    private CharSequence mContentDescription;
2276
2277    /**
2278     * Cache the paddingRight set by the user to append to the scrollbar's size.
2279     *
2280     * @hide
2281     */
2282    @ViewDebug.ExportedProperty(category = "padding")
2283    protected int mUserPaddingRight;
2284
2285    /**
2286     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2287     *
2288     * @hide
2289     */
2290    @ViewDebug.ExportedProperty(category = "padding")
2291    protected int mUserPaddingBottom;
2292
2293    /**
2294     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2295     *
2296     * @hide
2297     */
2298    @ViewDebug.ExportedProperty(category = "padding")
2299    protected int mUserPaddingLeft;
2300
2301    /**
2302     * Cache if the user padding is relative.
2303     *
2304     */
2305    @ViewDebug.ExportedProperty(category = "padding")
2306    boolean mUserPaddingRelative;
2307
2308    /**
2309     * Cache the paddingStart set by the user to append to the scrollbar's size.
2310     *
2311     */
2312    @ViewDebug.ExportedProperty(category = "padding")
2313    int mUserPaddingStart;
2314
2315    /**
2316     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2317     *
2318     */
2319    @ViewDebug.ExportedProperty(category = "padding")
2320    int mUserPaddingEnd;
2321
2322    /**
2323     * @hide
2324     */
2325    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2326    /**
2327     * @hide
2328     */
2329    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2330
2331    private Drawable mBGDrawable;
2332
2333    private int mBackgroundResource;
2334    private boolean mBackgroundSizeChanged;
2335
2336    static class ListenerInfo {
2337        /**
2338         * Listener used to dispatch focus change events.
2339         * This field should be made private, so it is hidden from the SDK.
2340         * {@hide}
2341         */
2342        protected OnFocusChangeListener mOnFocusChangeListener;
2343
2344        /**
2345         * Listeners for layout change events.
2346         */
2347        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2348
2349        /**
2350         * Listeners for attach events.
2351         */
2352        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2353
2354        /**
2355         * Listener used to dispatch click events.
2356         * This field should be made private, so it is hidden from the SDK.
2357         * {@hide}
2358         */
2359        public OnClickListener mOnClickListener;
2360
2361        /**
2362         * Listener used to dispatch long click events.
2363         * This field should be made private, so it is hidden from the SDK.
2364         * {@hide}
2365         */
2366        protected OnLongClickListener mOnLongClickListener;
2367
2368        /**
2369         * Listener used to build the context menu.
2370         * This field should be made private, so it is hidden from the SDK.
2371         * {@hide}
2372         */
2373        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2374
2375        private OnKeyListener mOnKeyListener;
2376
2377        private OnTouchListener mOnTouchListener;
2378
2379        private OnHoverListener mOnHoverListener;
2380
2381        private OnGenericMotionListener mOnGenericMotionListener;
2382
2383        private OnDragListener mOnDragListener;
2384
2385        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2386    }
2387
2388    ListenerInfo mListenerInfo;
2389
2390    /**
2391     * The application environment this view lives in.
2392     * This field should be made private, so it is hidden from the SDK.
2393     * {@hide}
2394     */
2395    protected Context mContext;
2396
2397    private final Resources mResources;
2398
2399    private ScrollabilityCache mScrollCache;
2400
2401    private int[] mDrawableState = null;
2402
2403    /**
2404     * Set to true when drawing cache is enabled and cannot be created.
2405     *
2406     * @hide
2407     */
2408    public boolean mCachingFailed;
2409
2410    private Bitmap mDrawingCache;
2411    private Bitmap mUnscaledDrawingCache;
2412    private HardwareLayer mHardwareLayer;
2413    DisplayList mDisplayList;
2414
2415    /**
2416     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2417     * the user may specify which view to go to next.
2418     */
2419    private int mNextFocusLeftId = View.NO_ID;
2420
2421    /**
2422     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2423     * the user may specify which view to go to next.
2424     */
2425    private int mNextFocusRightId = View.NO_ID;
2426
2427    /**
2428     * When this view has focus and the next focus is {@link #FOCUS_UP},
2429     * the user may specify which view to go to next.
2430     */
2431    private int mNextFocusUpId = View.NO_ID;
2432
2433    /**
2434     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2435     * the user may specify which view to go to next.
2436     */
2437    private int mNextFocusDownId = View.NO_ID;
2438
2439    /**
2440     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2441     * the user may specify which view to go to next.
2442     */
2443    int mNextFocusForwardId = View.NO_ID;
2444
2445    private CheckForLongPress mPendingCheckForLongPress;
2446    private CheckForTap mPendingCheckForTap = null;
2447    private PerformClick mPerformClick;
2448    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2449
2450    private UnsetPressedState mUnsetPressedState;
2451
2452    /**
2453     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2454     * up event while a long press is invoked as soon as the long press duration is reached, so
2455     * a long press could be performed before the tap is checked, in which case the tap's action
2456     * should not be invoked.
2457     */
2458    private boolean mHasPerformedLongPress;
2459
2460    /**
2461     * The minimum height of the view. We'll try our best to have the height
2462     * of this view to at least this amount.
2463     */
2464    @ViewDebug.ExportedProperty(category = "measurement")
2465    private int mMinHeight;
2466
2467    /**
2468     * The minimum width of the view. We'll try our best to have the width
2469     * of this view to at least this amount.
2470     */
2471    @ViewDebug.ExportedProperty(category = "measurement")
2472    private int mMinWidth;
2473
2474    /**
2475     * The delegate to handle touch events that are physically in this view
2476     * but should be handled by another view.
2477     */
2478    private TouchDelegate mTouchDelegate = null;
2479
2480    /**
2481     * Solid color to use as a background when creating the drawing cache. Enables
2482     * the cache to use 16 bit bitmaps instead of 32 bit.
2483     */
2484    private int mDrawingCacheBackgroundColor = 0;
2485
2486    /**
2487     * Special tree observer used when mAttachInfo is null.
2488     */
2489    private ViewTreeObserver mFloatingTreeObserver;
2490
2491    /**
2492     * Cache the touch slop from the context that created the view.
2493     */
2494    private int mTouchSlop;
2495
2496    /**
2497     * Object that handles automatic animation of view properties.
2498     */
2499    private ViewPropertyAnimator mAnimator = null;
2500
2501    /**
2502     * Flag indicating that a drag can cross window boundaries.  When
2503     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2504     * with this flag set, all visible applications will be able to participate
2505     * in the drag operation and receive the dragged content.
2506     *
2507     * @hide
2508     */
2509    public static final int DRAG_FLAG_GLOBAL = 1;
2510
2511    /**
2512     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2513     */
2514    private float mVerticalScrollFactor;
2515
2516    /**
2517     * Position of the vertical scroll bar.
2518     */
2519    private int mVerticalScrollbarPosition;
2520
2521    /**
2522     * Position the scroll bar at the default position as determined by the system.
2523     */
2524    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2525
2526    /**
2527     * Position the scroll bar along the left edge.
2528     */
2529    public static final int SCROLLBAR_POSITION_LEFT = 1;
2530
2531    /**
2532     * Position the scroll bar along the right edge.
2533     */
2534    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2535
2536    /**
2537     * Indicates that the view does not have a layer.
2538     *
2539     * @see #getLayerType()
2540     * @see #setLayerType(int, android.graphics.Paint)
2541     * @see #LAYER_TYPE_SOFTWARE
2542     * @see #LAYER_TYPE_HARDWARE
2543     */
2544    public static final int LAYER_TYPE_NONE = 0;
2545
2546    /**
2547     * <p>Indicates that the view has a software layer. A software layer is backed
2548     * by a bitmap and causes the view to be rendered using Android's software
2549     * rendering pipeline, even if hardware acceleration is enabled.</p>
2550     *
2551     * <p>Software layers have various usages:</p>
2552     * <p>When the application is not using hardware acceleration, a software layer
2553     * is useful to apply a specific color filter and/or blending mode and/or
2554     * translucency to a view and all its children.</p>
2555     * <p>When the application is using hardware acceleration, a software layer
2556     * is useful to render drawing primitives not supported by the hardware
2557     * accelerated pipeline. It can also be used to cache a complex view tree
2558     * into a texture and reduce the complexity of drawing operations. For instance,
2559     * when animating a complex view tree with a translation, a software layer can
2560     * be used to render the view tree only once.</p>
2561     * <p>Software layers should be avoided when the affected view tree updates
2562     * often. Every update will require to re-render the software layer, which can
2563     * potentially be slow (particularly when hardware acceleration is turned on
2564     * since the layer will have to be uploaded into a hardware texture after every
2565     * update.)</p>
2566     *
2567     * @see #getLayerType()
2568     * @see #setLayerType(int, android.graphics.Paint)
2569     * @see #LAYER_TYPE_NONE
2570     * @see #LAYER_TYPE_HARDWARE
2571     */
2572    public static final int LAYER_TYPE_SOFTWARE = 1;
2573
2574    /**
2575     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2576     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2577     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2578     * rendering pipeline, but only if hardware acceleration is turned on for the
2579     * view hierarchy. When hardware acceleration is turned off, hardware layers
2580     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2581     *
2582     * <p>A hardware layer is useful to apply a specific color filter and/or
2583     * blending mode and/or translucency to a view and all its children.</p>
2584     * <p>A hardware layer can be used to cache a complex view tree into a
2585     * texture and reduce the complexity of drawing operations. For instance,
2586     * when animating a complex view tree with a translation, a hardware layer can
2587     * be used to render the view tree only once.</p>
2588     * <p>A hardware layer can also be used to increase the rendering quality when
2589     * rotation transformations are applied on a view. It can also be used to
2590     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2591     *
2592     * @see #getLayerType()
2593     * @see #setLayerType(int, android.graphics.Paint)
2594     * @see #LAYER_TYPE_NONE
2595     * @see #LAYER_TYPE_SOFTWARE
2596     */
2597    public static final int LAYER_TYPE_HARDWARE = 2;
2598
2599    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2600            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2601            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2602            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2603    })
2604    int mLayerType = LAYER_TYPE_NONE;
2605    Paint mLayerPaint;
2606    Rect mLocalDirtyRect;
2607
2608    /**
2609     * Set to true when the view is sending hover accessibility events because it
2610     * is the innermost hovered view.
2611     */
2612    private boolean mSendingHoverAccessibilityEvents;
2613
2614    /**
2615     * Delegate for injecting accessiblity functionality.
2616     */
2617    AccessibilityDelegate mAccessibilityDelegate;
2618
2619    /**
2620     * Text direction is inherited thru {@link ViewGroup}
2621     */
2622    public static final int TEXT_DIRECTION_INHERIT = 0;
2623
2624    /**
2625     * Text direction is using "first strong algorithm". The first strong directional character
2626     * determines the paragraph direction. If there is no strong directional character, the
2627     * paragraph direction is the view's resolved layout direction.
2628     *
2629     */
2630    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2631
2632    /**
2633     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2634     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2635     * If there are neither, the paragraph direction is the view's resolved layout direction.
2636     *
2637     */
2638    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2639
2640    /**
2641     * Text direction is forced to LTR.
2642     *
2643     */
2644    public static final int TEXT_DIRECTION_LTR = 3;
2645
2646    /**
2647     * Text direction is forced to RTL.
2648     *
2649     */
2650    public static final int TEXT_DIRECTION_RTL = 4;
2651
2652    /**
2653     * Text direction is coming from the system Locale.
2654     *
2655     */
2656    public static final int TEXT_DIRECTION_LOCALE = 5;
2657
2658    /**
2659     * Default text direction is inherited
2660     *
2661     */
2662    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2663
2664    /**
2665     * The text direction that has been defined by {@link #setTextDirection(int)}.
2666     *
2667     */
2668    @ViewDebug.ExportedProperty(category = "text", mapping = {
2669            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2670            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2671            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2672            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2673            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2674            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2675    })
2676    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2677
2678    /**
2679     * The resolved text direction.  This needs resolution if the value is
2680     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if it is
2681     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2682     * chain of the view.
2683     *
2684     */
2685    @ViewDebug.ExportedProperty(category = "text", mapping = {
2686            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2687            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2688            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2689            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2690            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2691            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2692    })
2693    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2694
2695    /**
2696     * Consistency verifier for debugging purposes.
2697     * @hide
2698     */
2699    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2700            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2701                    new InputEventConsistencyVerifier(this, 0) : null;
2702
2703    /**
2704     * Simple constructor to use when creating a view from code.
2705     *
2706     * @param context The Context the view is running in, through which it can
2707     *        access the current theme, resources, etc.
2708     */
2709    public View(Context context) {
2710        mContext = context;
2711        mResources = context != null ? context.getResources() : null;
2712        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2713        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2714        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2715        mUserPaddingStart = -1;
2716        mUserPaddingEnd = -1;
2717        mUserPaddingRelative = false;
2718    }
2719
2720    /**
2721     * Constructor that is called when inflating a view from XML. This is called
2722     * when a view is being constructed from an XML file, supplying attributes
2723     * that were specified in the XML file. This version uses a default style of
2724     * 0, so the only attribute values applied are those in the Context's Theme
2725     * and the given AttributeSet.
2726     *
2727     * <p>
2728     * The method onFinishInflate() will be called after all children have been
2729     * added.
2730     *
2731     * @param context The Context the view is running in, through which it can
2732     *        access the current theme, resources, etc.
2733     * @param attrs The attributes of the XML tag that is inflating the view.
2734     * @see #View(Context, AttributeSet, int)
2735     */
2736    public View(Context context, AttributeSet attrs) {
2737        this(context, attrs, 0);
2738    }
2739
2740    /**
2741     * Perform inflation from XML and apply a class-specific base style. This
2742     * constructor of View allows subclasses to use their own base style when
2743     * they are inflating. For example, a Button class's constructor would call
2744     * this version of the super class constructor and supply
2745     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2746     * the theme's button style to modify all of the base view attributes (in
2747     * particular its background) as well as the Button class's attributes.
2748     *
2749     * @param context The Context the view is running in, through which it can
2750     *        access the current theme, resources, etc.
2751     * @param attrs The attributes of the XML tag that is inflating the view.
2752     * @param defStyle The default style to apply to this view. If 0, no style
2753     *        will be applied (beyond what is included in the theme). This may
2754     *        either be an attribute resource, whose value will be retrieved
2755     *        from the current theme, or an explicit style resource.
2756     * @see #View(Context, AttributeSet)
2757     */
2758    public View(Context context, AttributeSet attrs, int defStyle) {
2759        this(context);
2760
2761        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2762                defStyle, 0);
2763
2764        Drawable background = null;
2765
2766        int leftPadding = -1;
2767        int topPadding = -1;
2768        int rightPadding = -1;
2769        int bottomPadding = -1;
2770        int startPadding = -1;
2771        int endPadding = -1;
2772
2773        int padding = -1;
2774
2775        int viewFlagValues = 0;
2776        int viewFlagMasks = 0;
2777
2778        boolean setScrollContainer = false;
2779
2780        int x = 0;
2781        int y = 0;
2782
2783        float tx = 0;
2784        float ty = 0;
2785        float rotation = 0;
2786        float rotationX = 0;
2787        float rotationY = 0;
2788        float sx = 1f;
2789        float sy = 1f;
2790        boolean transformSet = false;
2791
2792        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2793
2794        int overScrollMode = mOverScrollMode;
2795        final int N = a.getIndexCount();
2796        for (int i = 0; i < N; i++) {
2797            int attr = a.getIndex(i);
2798            switch (attr) {
2799                case com.android.internal.R.styleable.View_background:
2800                    background = a.getDrawable(attr);
2801                    break;
2802                case com.android.internal.R.styleable.View_padding:
2803                    padding = a.getDimensionPixelSize(attr, -1);
2804                    break;
2805                 case com.android.internal.R.styleable.View_paddingLeft:
2806                    leftPadding = a.getDimensionPixelSize(attr, -1);
2807                    break;
2808                case com.android.internal.R.styleable.View_paddingTop:
2809                    topPadding = a.getDimensionPixelSize(attr, -1);
2810                    break;
2811                case com.android.internal.R.styleable.View_paddingRight:
2812                    rightPadding = a.getDimensionPixelSize(attr, -1);
2813                    break;
2814                case com.android.internal.R.styleable.View_paddingBottom:
2815                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2816                    break;
2817                case com.android.internal.R.styleable.View_paddingStart:
2818                    startPadding = a.getDimensionPixelSize(attr, -1);
2819                    break;
2820                case com.android.internal.R.styleable.View_paddingEnd:
2821                    endPadding = a.getDimensionPixelSize(attr, -1);
2822                    break;
2823                case com.android.internal.R.styleable.View_scrollX:
2824                    x = a.getDimensionPixelOffset(attr, 0);
2825                    break;
2826                case com.android.internal.R.styleable.View_scrollY:
2827                    y = a.getDimensionPixelOffset(attr, 0);
2828                    break;
2829                case com.android.internal.R.styleable.View_alpha:
2830                    setAlpha(a.getFloat(attr, 1f));
2831                    break;
2832                case com.android.internal.R.styleable.View_transformPivotX:
2833                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2834                    break;
2835                case com.android.internal.R.styleable.View_transformPivotY:
2836                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2837                    break;
2838                case com.android.internal.R.styleable.View_translationX:
2839                    tx = a.getDimensionPixelOffset(attr, 0);
2840                    transformSet = true;
2841                    break;
2842                case com.android.internal.R.styleable.View_translationY:
2843                    ty = a.getDimensionPixelOffset(attr, 0);
2844                    transformSet = true;
2845                    break;
2846                case com.android.internal.R.styleable.View_rotation:
2847                    rotation = a.getFloat(attr, 0);
2848                    transformSet = true;
2849                    break;
2850                case com.android.internal.R.styleable.View_rotationX:
2851                    rotationX = a.getFloat(attr, 0);
2852                    transformSet = true;
2853                    break;
2854                case com.android.internal.R.styleable.View_rotationY:
2855                    rotationY = a.getFloat(attr, 0);
2856                    transformSet = true;
2857                    break;
2858                case com.android.internal.R.styleable.View_scaleX:
2859                    sx = a.getFloat(attr, 1f);
2860                    transformSet = true;
2861                    break;
2862                case com.android.internal.R.styleable.View_scaleY:
2863                    sy = a.getFloat(attr, 1f);
2864                    transformSet = true;
2865                    break;
2866                case com.android.internal.R.styleable.View_id:
2867                    mID = a.getResourceId(attr, NO_ID);
2868                    break;
2869                case com.android.internal.R.styleable.View_tag:
2870                    mTag = a.getText(attr);
2871                    break;
2872                case com.android.internal.R.styleable.View_fitsSystemWindows:
2873                    if (a.getBoolean(attr, false)) {
2874                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2875                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2876                    }
2877                    break;
2878                case com.android.internal.R.styleable.View_focusable:
2879                    if (a.getBoolean(attr, false)) {
2880                        viewFlagValues |= FOCUSABLE;
2881                        viewFlagMasks |= FOCUSABLE_MASK;
2882                    }
2883                    break;
2884                case com.android.internal.R.styleable.View_focusableInTouchMode:
2885                    if (a.getBoolean(attr, false)) {
2886                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2887                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2888                    }
2889                    break;
2890                case com.android.internal.R.styleable.View_clickable:
2891                    if (a.getBoolean(attr, false)) {
2892                        viewFlagValues |= CLICKABLE;
2893                        viewFlagMasks |= CLICKABLE;
2894                    }
2895                    break;
2896                case com.android.internal.R.styleable.View_longClickable:
2897                    if (a.getBoolean(attr, false)) {
2898                        viewFlagValues |= LONG_CLICKABLE;
2899                        viewFlagMasks |= LONG_CLICKABLE;
2900                    }
2901                    break;
2902                case com.android.internal.R.styleable.View_saveEnabled:
2903                    if (!a.getBoolean(attr, true)) {
2904                        viewFlagValues |= SAVE_DISABLED;
2905                        viewFlagMasks |= SAVE_DISABLED_MASK;
2906                    }
2907                    break;
2908                case com.android.internal.R.styleable.View_duplicateParentState:
2909                    if (a.getBoolean(attr, false)) {
2910                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2911                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2912                    }
2913                    break;
2914                case com.android.internal.R.styleable.View_visibility:
2915                    final int visibility = a.getInt(attr, 0);
2916                    if (visibility != 0) {
2917                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2918                        viewFlagMasks |= VISIBILITY_MASK;
2919                    }
2920                    break;
2921                case com.android.internal.R.styleable.View_layoutDirection:
2922                    // Clear any HORIZONTAL_DIRECTION flag already set
2923                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2924                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2925                    final int layoutDirection = a.getInt(attr, -1);
2926                    if (layoutDirection != -1) {
2927                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2928                    } else {
2929                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2930                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2931                    }
2932                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2933                    break;
2934                case com.android.internal.R.styleable.View_drawingCacheQuality:
2935                    final int cacheQuality = a.getInt(attr, 0);
2936                    if (cacheQuality != 0) {
2937                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2938                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2939                    }
2940                    break;
2941                case com.android.internal.R.styleable.View_contentDescription:
2942                    mContentDescription = a.getString(attr);
2943                    break;
2944                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2945                    if (!a.getBoolean(attr, true)) {
2946                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2947                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2948                    }
2949                    break;
2950                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2951                    if (!a.getBoolean(attr, true)) {
2952                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2953                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2954                    }
2955                    break;
2956                case R.styleable.View_scrollbars:
2957                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2958                    if (scrollbars != SCROLLBARS_NONE) {
2959                        viewFlagValues |= scrollbars;
2960                        viewFlagMasks |= SCROLLBARS_MASK;
2961                        initializeScrollbars(a);
2962                    }
2963                    break;
2964                //noinspection deprecation
2965                case R.styleable.View_fadingEdge:
2966                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2967                        // Ignore the attribute starting with ICS
2968                        break;
2969                    }
2970                    // With builds < ICS, fall through and apply fading edges
2971                case R.styleable.View_requiresFadingEdge:
2972                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
2973                    if (fadingEdge != FADING_EDGE_NONE) {
2974                        viewFlagValues |= fadingEdge;
2975                        viewFlagMasks |= FADING_EDGE_MASK;
2976                        initializeFadingEdge(a);
2977                    }
2978                    break;
2979                case R.styleable.View_scrollbarStyle:
2980                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
2981                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
2982                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
2983                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
2984                    }
2985                    break;
2986                case R.styleable.View_isScrollContainer:
2987                    setScrollContainer = true;
2988                    if (a.getBoolean(attr, false)) {
2989                        setScrollContainer(true);
2990                    }
2991                    break;
2992                case com.android.internal.R.styleable.View_keepScreenOn:
2993                    if (a.getBoolean(attr, false)) {
2994                        viewFlagValues |= KEEP_SCREEN_ON;
2995                        viewFlagMasks |= KEEP_SCREEN_ON;
2996                    }
2997                    break;
2998                case R.styleable.View_filterTouchesWhenObscured:
2999                    if (a.getBoolean(attr, false)) {
3000                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3001                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3002                    }
3003                    break;
3004                case R.styleable.View_nextFocusLeft:
3005                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3006                    break;
3007                case R.styleable.View_nextFocusRight:
3008                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3009                    break;
3010                case R.styleable.View_nextFocusUp:
3011                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3012                    break;
3013                case R.styleable.View_nextFocusDown:
3014                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3015                    break;
3016                case R.styleable.View_nextFocusForward:
3017                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3018                    break;
3019                case R.styleable.View_minWidth:
3020                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3021                    break;
3022                case R.styleable.View_minHeight:
3023                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3024                    break;
3025                case R.styleable.View_onClick:
3026                    if (context.isRestricted()) {
3027                        throw new IllegalStateException("The android:onClick attribute cannot "
3028                                + "be used within a restricted context");
3029                    }
3030
3031                    final String handlerName = a.getString(attr);
3032                    if (handlerName != null) {
3033                        setOnClickListener(new OnClickListener() {
3034                            private Method mHandler;
3035
3036                            public void onClick(View v) {
3037                                if (mHandler == null) {
3038                                    try {
3039                                        mHandler = getContext().getClass().getMethod(handlerName,
3040                                                View.class);
3041                                    } catch (NoSuchMethodException e) {
3042                                        int id = getId();
3043                                        String idText = id == NO_ID ? "" : " with id '"
3044                                                + getContext().getResources().getResourceEntryName(
3045                                                    id) + "'";
3046                                        throw new IllegalStateException("Could not find a method " +
3047                                                handlerName + "(View) in the activity "
3048                                                + getContext().getClass() + " for onClick handler"
3049                                                + " on view " + View.this.getClass() + idText, e);
3050                                    }
3051                                }
3052
3053                                try {
3054                                    mHandler.invoke(getContext(), View.this);
3055                                } catch (IllegalAccessException e) {
3056                                    throw new IllegalStateException("Could not execute non "
3057                                            + "public method of the activity", e);
3058                                } catch (InvocationTargetException e) {
3059                                    throw new IllegalStateException("Could not execute "
3060                                            + "method of the activity", e);
3061                                }
3062                            }
3063                        });
3064                    }
3065                    break;
3066                case R.styleable.View_overScrollMode:
3067                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3068                    break;
3069                case R.styleable.View_verticalScrollbarPosition:
3070                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3071                    break;
3072                case R.styleable.View_layerType:
3073                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3074                    break;
3075                case R.styleable.View_textDirection:
3076                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3077                    break;
3078            }
3079        }
3080
3081        a.recycle();
3082
3083        setOverScrollMode(overScrollMode);
3084
3085        if (background != null) {
3086            setBackgroundDrawable(background);
3087        }
3088
3089        mUserPaddingRelative = (startPadding >= 0 || endPadding >= 0);
3090
3091        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3092        // layout direction). Those cached values will be used later during padding resolution.
3093        mUserPaddingStart = startPadding;
3094        mUserPaddingEnd = endPadding;
3095
3096        if (padding >= 0) {
3097            leftPadding = padding;
3098            topPadding = padding;
3099            rightPadding = padding;
3100            bottomPadding = padding;
3101        }
3102
3103        // If the user specified the padding (either with android:padding or
3104        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3105        // use the default padding or the padding from the background drawable
3106        // (stored at this point in mPadding*)
3107        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3108                topPadding >= 0 ? topPadding : mPaddingTop,
3109                rightPadding >= 0 ? rightPadding : mPaddingRight,
3110                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3111
3112        if (viewFlagMasks != 0) {
3113            setFlags(viewFlagValues, viewFlagMasks);
3114        }
3115
3116        // Needs to be called after mViewFlags is set
3117        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3118            recomputePadding();
3119        }
3120
3121        if (x != 0 || y != 0) {
3122            scrollTo(x, y);
3123        }
3124
3125        if (transformSet) {
3126            setTranslationX(tx);
3127            setTranslationY(ty);
3128            setRotation(rotation);
3129            setRotationX(rotationX);
3130            setRotationY(rotationY);
3131            setScaleX(sx);
3132            setScaleY(sy);
3133        }
3134
3135        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3136            setScrollContainer(true);
3137        }
3138
3139        computeOpaqueFlags();
3140    }
3141
3142    /**
3143     * Non-public constructor for use in testing
3144     */
3145    View() {
3146        mResources = null;
3147    }
3148
3149    /**
3150     * <p>
3151     * Initializes the fading edges from a given set of styled attributes. This
3152     * method should be called by subclasses that need fading edges and when an
3153     * instance of these subclasses is created programmatically rather than
3154     * being inflated from XML. This method is automatically called when the XML
3155     * is inflated.
3156     * </p>
3157     *
3158     * @param a the styled attributes set to initialize the fading edges from
3159     */
3160    protected void initializeFadingEdge(TypedArray a) {
3161        initScrollCache();
3162
3163        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3164                R.styleable.View_fadingEdgeLength,
3165                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3166    }
3167
3168    /**
3169     * Returns the size of the vertical faded edges used to indicate that more
3170     * content in this view is visible.
3171     *
3172     * @return The size in pixels of the vertical faded edge or 0 if vertical
3173     *         faded edges are not enabled for this view.
3174     * @attr ref android.R.styleable#View_fadingEdgeLength
3175     */
3176    public int getVerticalFadingEdgeLength() {
3177        if (isVerticalFadingEdgeEnabled()) {
3178            ScrollabilityCache cache = mScrollCache;
3179            if (cache != null) {
3180                return cache.fadingEdgeLength;
3181            }
3182        }
3183        return 0;
3184    }
3185
3186    /**
3187     * Set the size of the faded edge used to indicate that more content in this
3188     * view is available.  Will not change whether the fading edge is enabled; use
3189     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3190     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3191     * for the vertical or horizontal fading edges.
3192     *
3193     * @param length The size in pixels of the faded edge used to indicate that more
3194     *        content in this view is visible.
3195     */
3196    public void setFadingEdgeLength(int length) {
3197        initScrollCache();
3198        mScrollCache.fadingEdgeLength = length;
3199    }
3200
3201    /**
3202     * Returns the size of the horizontal faded edges used to indicate that more
3203     * content in this view is visible.
3204     *
3205     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3206     *         faded edges are not enabled for this view.
3207     * @attr ref android.R.styleable#View_fadingEdgeLength
3208     */
3209    public int getHorizontalFadingEdgeLength() {
3210        if (isHorizontalFadingEdgeEnabled()) {
3211            ScrollabilityCache cache = mScrollCache;
3212            if (cache != null) {
3213                return cache.fadingEdgeLength;
3214            }
3215        }
3216        return 0;
3217    }
3218
3219    /**
3220     * Returns the width of the vertical scrollbar.
3221     *
3222     * @return The width in pixels of the vertical scrollbar or 0 if there
3223     *         is no vertical scrollbar.
3224     */
3225    public int getVerticalScrollbarWidth() {
3226        ScrollabilityCache cache = mScrollCache;
3227        if (cache != null) {
3228            ScrollBarDrawable scrollBar = cache.scrollBar;
3229            if (scrollBar != null) {
3230                int size = scrollBar.getSize(true);
3231                if (size <= 0) {
3232                    size = cache.scrollBarSize;
3233                }
3234                return size;
3235            }
3236            return 0;
3237        }
3238        return 0;
3239    }
3240
3241    /**
3242     * Returns the height of the horizontal scrollbar.
3243     *
3244     * @return The height in pixels of the horizontal scrollbar or 0 if
3245     *         there is no horizontal scrollbar.
3246     */
3247    protected int getHorizontalScrollbarHeight() {
3248        ScrollabilityCache cache = mScrollCache;
3249        if (cache != null) {
3250            ScrollBarDrawable scrollBar = cache.scrollBar;
3251            if (scrollBar != null) {
3252                int size = scrollBar.getSize(false);
3253                if (size <= 0) {
3254                    size = cache.scrollBarSize;
3255                }
3256                return size;
3257            }
3258            return 0;
3259        }
3260        return 0;
3261    }
3262
3263    /**
3264     * <p>
3265     * Initializes the scrollbars from a given set of styled attributes. This
3266     * method should be called by subclasses that need scrollbars and when an
3267     * instance of these subclasses is created programmatically rather than
3268     * being inflated from XML. This method is automatically called when the XML
3269     * is inflated.
3270     * </p>
3271     *
3272     * @param a the styled attributes set to initialize the scrollbars from
3273     */
3274    protected void initializeScrollbars(TypedArray a) {
3275        initScrollCache();
3276
3277        final ScrollabilityCache scrollabilityCache = mScrollCache;
3278
3279        if (scrollabilityCache.scrollBar == null) {
3280            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3281        }
3282
3283        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3284
3285        if (!fadeScrollbars) {
3286            scrollabilityCache.state = ScrollabilityCache.ON;
3287        }
3288        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3289
3290
3291        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3292                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3293                        .getScrollBarFadeDuration());
3294        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3295                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3296                ViewConfiguration.getScrollDefaultDelay());
3297
3298
3299        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3300                com.android.internal.R.styleable.View_scrollbarSize,
3301                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3302
3303        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3304        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3305
3306        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3307        if (thumb != null) {
3308            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3309        }
3310
3311        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3312                false);
3313        if (alwaysDraw) {
3314            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3315        }
3316
3317        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3318        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3319
3320        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3321        if (thumb != null) {
3322            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3323        }
3324
3325        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3326                false);
3327        if (alwaysDraw) {
3328            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3329        }
3330
3331        // Re-apply user/background padding so that scrollbar(s) get added
3332        resolvePadding();
3333    }
3334
3335    /**
3336     * <p>
3337     * Initalizes the scrollability cache if necessary.
3338     * </p>
3339     */
3340    private void initScrollCache() {
3341        if (mScrollCache == null) {
3342            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3343        }
3344    }
3345
3346    /**
3347     * Set the position of the vertical scroll bar. Should be one of
3348     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3349     * {@link #SCROLLBAR_POSITION_RIGHT}.
3350     *
3351     * @param position Where the vertical scroll bar should be positioned.
3352     */
3353    public void setVerticalScrollbarPosition(int position) {
3354        if (mVerticalScrollbarPosition != position) {
3355            mVerticalScrollbarPosition = position;
3356            computeOpaqueFlags();
3357            resolvePadding();
3358        }
3359    }
3360
3361    /**
3362     * @return The position where the vertical scroll bar will show, if applicable.
3363     * @see #setVerticalScrollbarPosition(int)
3364     */
3365    public int getVerticalScrollbarPosition() {
3366        return mVerticalScrollbarPosition;
3367    }
3368
3369    ListenerInfo getListenerInfo() {
3370        if (mListenerInfo != null) {
3371            return mListenerInfo;
3372        }
3373        mListenerInfo = new ListenerInfo();
3374        return mListenerInfo;
3375    }
3376
3377    /**
3378     * Register a callback to be invoked when focus of this view changed.
3379     *
3380     * @param l The callback that will run.
3381     */
3382    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3383        getListenerInfo().mOnFocusChangeListener = l;
3384    }
3385
3386    /**
3387     * Add a listener that will be called when the bounds of the view change due to
3388     * layout processing.
3389     *
3390     * @param listener The listener that will be called when layout bounds change.
3391     */
3392    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3393        ListenerInfo li = getListenerInfo();
3394        if (li.mOnLayoutChangeListeners == null) {
3395            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3396        }
3397        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3398            li.mOnLayoutChangeListeners.add(listener);
3399        }
3400    }
3401
3402    /**
3403     * Remove a listener for layout changes.
3404     *
3405     * @param listener The listener for layout bounds change.
3406     */
3407    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3408        ListenerInfo li = mListenerInfo;
3409        if (li == null || li.mOnLayoutChangeListeners == null) {
3410            return;
3411        }
3412        li.mOnLayoutChangeListeners.remove(listener);
3413    }
3414
3415    /**
3416     * Add a listener for attach state changes.
3417     *
3418     * This listener will be called whenever this view is attached or detached
3419     * from a window. Remove the listener using
3420     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3421     *
3422     * @param listener Listener to attach
3423     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3424     */
3425    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3426        ListenerInfo li = getListenerInfo();
3427        if (li.mOnAttachStateChangeListeners == null) {
3428            li.mOnAttachStateChangeListeners
3429                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3430        }
3431        li.mOnAttachStateChangeListeners.add(listener);
3432    }
3433
3434    /**
3435     * Remove a listener for attach state changes. The listener will receive no further
3436     * notification of window attach/detach events.
3437     *
3438     * @param listener Listener to remove
3439     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3440     */
3441    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3442        ListenerInfo li = mListenerInfo;
3443        if (li == null || li.mOnAttachStateChangeListeners == null) {
3444            return;
3445        }
3446        li.mOnAttachStateChangeListeners.remove(listener);
3447    }
3448
3449    /**
3450     * Returns the focus-change callback registered for this view.
3451     *
3452     * @return The callback, or null if one is not registered.
3453     */
3454    public OnFocusChangeListener getOnFocusChangeListener() {
3455        ListenerInfo li = mListenerInfo;
3456        return li != null ? li.mOnFocusChangeListener : null;
3457    }
3458
3459    /**
3460     * Register a callback to be invoked when this view is clicked. If this view is not
3461     * clickable, it becomes clickable.
3462     *
3463     * @param l The callback that will run
3464     *
3465     * @see #setClickable(boolean)
3466     */
3467    public void setOnClickListener(OnClickListener l) {
3468        if (!isClickable()) {
3469            setClickable(true);
3470        }
3471        getListenerInfo().mOnClickListener = l;
3472    }
3473
3474    /**
3475     * Return whether this view has an attached OnClickListener.  Returns
3476     * true if there is a listener, false if there is none.
3477     */
3478    public boolean hasOnClickListeners() {
3479        ListenerInfo li = mListenerInfo;
3480        return (li != null && li.mOnClickListener != null);
3481    }
3482
3483    /**
3484     * Register a callback to be invoked when this view is clicked and held. If this view is not
3485     * long clickable, it becomes long clickable.
3486     *
3487     * @param l The callback that will run
3488     *
3489     * @see #setLongClickable(boolean)
3490     */
3491    public void setOnLongClickListener(OnLongClickListener l) {
3492        if (!isLongClickable()) {
3493            setLongClickable(true);
3494        }
3495        getListenerInfo().mOnLongClickListener = l;
3496    }
3497
3498    /**
3499     * Register a callback to be invoked when the context menu for this view is
3500     * being built. If this view is not long clickable, it becomes long clickable.
3501     *
3502     * @param l The callback that will run
3503     *
3504     */
3505    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3506        if (!isLongClickable()) {
3507            setLongClickable(true);
3508        }
3509        getListenerInfo().mOnCreateContextMenuListener = l;
3510    }
3511
3512    /**
3513     * Call this view's OnClickListener, if it is defined.  Performs all normal
3514     * actions associated with clicking: reporting accessibility event, playing
3515     * a sound, etc.
3516     *
3517     * @return True there was an assigned OnClickListener that was called, false
3518     *         otherwise is returned.
3519     */
3520    public boolean performClick() {
3521        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3522
3523        ListenerInfo li = mListenerInfo;
3524        if (li != null && li.mOnClickListener != null) {
3525            playSoundEffect(SoundEffectConstants.CLICK);
3526            li.mOnClickListener.onClick(this);
3527            return true;
3528        }
3529
3530        return false;
3531    }
3532
3533    /**
3534     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3535     * this only calls the listener, and does not do any associated clicking
3536     * actions like reporting an accessibility event.
3537     *
3538     * @return True there was an assigned OnClickListener that was called, false
3539     *         otherwise is returned.
3540     */
3541    public boolean callOnClick() {
3542        ListenerInfo li = mListenerInfo;
3543        if (li != null && li.mOnClickListener != null) {
3544            li.mOnClickListener.onClick(this);
3545            return true;
3546        }
3547        return false;
3548    }
3549
3550    /**
3551     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3552     * OnLongClickListener did not consume the event.
3553     *
3554     * @return True if one of the above receivers consumed the event, false otherwise.
3555     */
3556    public boolean performLongClick() {
3557        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3558
3559        boolean handled = false;
3560        ListenerInfo li = mListenerInfo;
3561        if (li != null && li.mOnLongClickListener != null) {
3562            handled = li.mOnLongClickListener.onLongClick(View.this);
3563        }
3564        if (!handled) {
3565            handled = showContextMenu();
3566        }
3567        if (handled) {
3568            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3569        }
3570        return handled;
3571    }
3572
3573    /**
3574     * Performs button-related actions during a touch down event.
3575     *
3576     * @param event The event.
3577     * @return True if the down was consumed.
3578     *
3579     * @hide
3580     */
3581    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3582        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3583            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3584                return true;
3585            }
3586        }
3587        return false;
3588    }
3589
3590    /**
3591     * Bring up the context menu for this view.
3592     *
3593     * @return Whether a context menu was displayed.
3594     */
3595    public boolean showContextMenu() {
3596        return getParent().showContextMenuForChild(this);
3597    }
3598
3599    /**
3600     * Bring up the context menu for this view, referring to the item under the specified point.
3601     *
3602     * @param x The referenced x coordinate.
3603     * @param y The referenced y coordinate.
3604     * @param metaState The keyboard modifiers that were pressed.
3605     * @return Whether a context menu was displayed.
3606     *
3607     * @hide
3608     */
3609    public boolean showContextMenu(float x, float y, int metaState) {
3610        return showContextMenu();
3611    }
3612
3613    /**
3614     * Start an action mode.
3615     *
3616     * @param callback Callback that will control the lifecycle of the action mode
3617     * @return The new action mode if it is started, null otherwise
3618     *
3619     * @see ActionMode
3620     */
3621    public ActionMode startActionMode(ActionMode.Callback callback) {
3622        return getParent().startActionModeForChild(this, callback);
3623    }
3624
3625    /**
3626     * Register a callback to be invoked when a key is pressed in this view.
3627     * @param l the key listener to attach to this view
3628     */
3629    public void setOnKeyListener(OnKeyListener l) {
3630        getListenerInfo().mOnKeyListener = l;
3631    }
3632
3633    /**
3634     * Register a callback to be invoked when a touch event is sent to this view.
3635     * @param l the touch listener to attach to this view
3636     */
3637    public void setOnTouchListener(OnTouchListener l) {
3638        getListenerInfo().mOnTouchListener = l;
3639    }
3640
3641    /**
3642     * Register a callback to be invoked when a generic motion event is sent to this view.
3643     * @param l the generic motion listener to attach to this view
3644     */
3645    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3646        getListenerInfo().mOnGenericMotionListener = l;
3647    }
3648
3649    /**
3650     * Register a callback to be invoked when a hover event is sent to this view.
3651     * @param l the hover listener to attach to this view
3652     */
3653    public void setOnHoverListener(OnHoverListener l) {
3654        getListenerInfo().mOnHoverListener = l;
3655    }
3656
3657    /**
3658     * Register a drag event listener callback object for this View. The parameter is
3659     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3660     * View, the system calls the
3661     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3662     * @param l An implementation of {@link android.view.View.OnDragListener}.
3663     */
3664    public void setOnDragListener(OnDragListener l) {
3665        getListenerInfo().mOnDragListener = l;
3666    }
3667
3668    /**
3669     * Give this view focus. This will cause
3670     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3671     *
3672     * Note: this does not check whether this {@link View} should get focus, it just
3673     * gives it focus no matter what.  It should only be called internally by framework
3674     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3675     *
3676     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3677     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3678     *        focus moved when requestFocus() is called. It may not always
3679     *        apply, in which case use the default View.FOCUS_DOWN.
3680     * @param previouslyFocusedRect The rectangle of the view that had focus
3681     *        prior in this View's coordinate system.
3682     */
3683    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3684        if (DBG) {
3685            System.out.println(this + " requestFocus()");
3686        }
3687
3688        if ((mPrivateFlags & FOCUSED) == 0) {
3689            mPrivateFlags |= FOCUSED;
3690
3691            if (mParent != null) {
3692                mParent.requestChildFocus(this, this);
3693            }
3694
3695            onFocusChanged(true, direction, previouslyFocusedRect);
3696            refreshDrawableState();
3697        }
3698    }
3699
3700    /**
3701     * Request that a rectangle of this view be visible on the screen,
3702     * scrolling if necessary just enough.
3703     *
3704     * <p>A View should call this if it maintains some notion of which part
3705     * of its content is interesting.  For example, a text editing view
3706     * should call this when its cursor moves.
3707     *
3708     * @param rectangle The rectangle.
3709     * @return Whether any parent scrolled.
3710     */
3711    public boolean requestRectangleOnScreen(Rect rectangle) {
3712        return requestRectangleOnScreen(rectangle, false);
3713    }
3714
3715    /**
3716     * Request that a rectangle of this view be visible on the screen,
3717     * scrolling if necessary just enough.
3718     *
3719     * <p>A View should call this if it maintains some notion of which part
3720     * of its content is interesting.  For example, a text editing view
3721     * should call this when its cursor moves.
3722     *
3723     * <p>When <code>immediate</code> is set to true, scrolling will not be
3724     * animated.
3725     *
3726     * @param rectangle The rectangle.
3727     * @param immediate True to forbid animated scrolling, false otherwise
3728     * @return Whether any parent scrolled.
3729     */
3730    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3731        View child = this;
3732        ViewParent parent = mParent;
3733        boolean scrolled = false;
3734        while (parent != null) {
3735            scrolled |= parent.requestChildRectangleOnScreen(child,
3736                    rectangle, immediate);
3737
3738            // offset rect so next call has the rectangle in the
3739            // coordinate system of its direct child.
3740            rectangle.offset(child.getLeft(), child.getTop());
3741            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3742
3743            if (!(parent instanceof View)) {
3744                break;
3745            }
3746
3747            child = (View) parent;
3748            parent = child.getParent();
3749        }
3750        return scrolled;
3751    }
3752
3753    /**
3754     * Called when this view wants to give up focus. If focus is cleared
3755     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
3756     * <p>
3757     * <strong>Note:</strong> When a View clears focus the framework is trying
3758     * to give focus to the first focusable View from the top. Hence, if this
3759     * View is the first from the top that can take focus, then its focus will
3760     * not be cleared nor will the focus change callback be invoked.
3761     * </p>
3762     */
3763    public void clearFocus() {
3764        if (DBG) {
3765            System.out.println(this + " clearFocus()");
3766        }
3767
3768        if ((mPrivateFlags & FOCUSED) != 0) {
3769            mPrivateFlags &= ~FOCUSED;
3770
3771            if (mParent != null) {
3772                mParent.clearChildFocus(this);
3773            }
3774
3775            onFocusChanged(false, 0, null);
3776            refreshDrawableState();
3777        }
3778    }
3779
3780    /**
3781     * Called to clear the focus of a view that is about to be removed.
3782     * Doesn't call clearChildFocus, which prevents this view from taking
3783     * focus again before it has been removed from the parent
3784     */
3785    void clearFocusForRemoval() {
3786        if ((mPrivateFlags & FOCUSED) != 0) {
3787            mPrivateFlags &= ~FOCUSED;
3788
3789            onFocusChanged(false, 0, null);
3790            refreshDrawableState();
3791
3792            // The view cleared focus and invoked the callbacks, so  now is the
3793            // time to give focus to the the first focusable from the top to
3794            // ensure that the gain focus is announced after clear focus.
3795            getRootView().requestFocus(FOCUS_FORWARD);
3796        }
3797    }
3798
3799    /**
3800     * Called internally by the view system when a new view is getting focus.
3801     * This is what clears the old focus.
3802     */
3803    void unFocus() {
3804        if (DBG) {
3805            System.out.println(this + " unFocus()");
3806        }
3807
3808        if ((mPrivateFlags & FOCUSED) != 0) {
3809            mPrivateFlags &= ~FOCUSED;
3810
3811            onFocusChanged(false, 0, null);
3812            refreshDrawableState();
3813        }
3814    }
3815
3816    /**
3817     * Returns true if this view has focus iteself, or is the ancestor of the
3818     * view that has focus.
3819     *
3820     * @return True if this view has or contains focus, false otherwise.
3821     */
3822    @ViewDebug.ExportedProperty(category = "focus")
3823    public boolean hasFocus() {
3824        return (mPrivateFlags & FOCUSED) != 0;
3825    }
3826
3827    /**
3828     * Returns true if this view is focusable or if it contains a reachable View
3829     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3830     * is a View whose parents do not block descendants focus.
3831     *
3832     * Only {@link #VISIBLE} views are considered focusable.
3833     *
3834     * @return True if the view is focusable or if the view contains a focusable
3835     *         View, false otherwise.
3836     *
3837     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3838     */
3839    public boolean hasFocusable() {
3840        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3841    }
3842
3843    /**
3844     * Called by the view system when the focus state of this view changes.
3845     * When the focus change event is caused by directional navigation, direction
3846     * and previouslyFocusedRect provide insight into where the focus is coming from.
3847     * When overriding, be sure to call up through to the super class so that
3848     * the standard focus handling will occur.
3849     *
3850     * @param gainFocus True if the View has focus; false otherwise.
3851     * @param direction The direction focus has moved when requestFocus()
3852     *                  is called to give this view focus. Values are
3853     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3854     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3855     *                  It may not always apply, in which case use the default.
3856     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3857     *        system, of the previously focused view.  If applicable, this will be
3858     *        passed in as finer grained information about where the focus is coming
3859     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3860     */
3861    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3862        if (gainFocus) {
3863            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3864        }
3865
3866        InputMethodManager imm = InputMethodManager.peekInstance();
3867        if (!gainFocus) {
3868            if (isPressed()) {
3869                setPressed(false);
3870            }
3871            if (imm != null && mAttachInfo != null
3872                    && mAttachInfo.mHasWindowFocus) {
3873                imm.focusOut(this);
3874            }
3875            onFocusLost();
3876        } else if (imm != null && mAttachInfo != null
3877                && mAttachInfo.mHasWindowFocus) {
3878            imm.focusIn(this);
3879        }
3880
3881        invalidate(true);
3882        ListenerInfo li = mListenerInfo;
3883        if (li != null && li.mOnFocusChangeListener != null) {
3884            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
3885        }
3886
3887        if (mAttachInfo != null) {
3888            mAttachInfo.mKeyDispatchState.reset(this);
3889        }
3890    }
3891
3892    /**
3893     * Sends an accessibility event of the given type. If accessiiblity is
3894     * not enabled this method has no effect. The default implementation calls
3895     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3896     * to populate information about the event source (this View), then calls
3897     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3898     * populate the text content of the event source including its descendants,
3899     * and last calls
3900     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3901     * on its parent to resuest sending of the event to interested parties.
3902     * <p>
3903     * If an {@link AccessibilityDelegate} has been specified via calling
3904     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3905     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3906     * responsible for handling this call.
3907     * </p>
3908     *
3909     * @param eventType The type of the event to send, as defined by several types from
3910     * {@link android.view.accessibility.AccessibilityEvent}, such as
3911     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
3912     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
3913     *
3914     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3915     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3916     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3917     * @see AccessibilityDelegate
3918     */
3919    public void sendAccessibilityEvent(int eventType) {
3920        if (mAccessibilityDelegate != null) {
3921            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3922        } else {
3923            sendAccessibilityEventInternal(eventType);
3924        }
3925    }
3926
3927    /**
3928     * @see #sendAccessibilityEvent(int)
3929     *
3930     * Note: Called from the default {@link AccessibilityDelegate}.
3931     */
3932    void sendAccessibilityEventInternal(int eventType) {
3933        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3934            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3935        }
3936    }
3937
3938    /**
3939     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3940     * takes as an argument an empty {@link AccessibilityEvent} and does not
3941     * perform a check whether accessibility is enabled.
3942     * <p>
3943     * If an {@link AccessibilityDelegate} has been specified via calling
3944     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3945     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
3946     * is responsible for handling this call.
3947     * </p>
3948     *
3949     * @param event The event to send.
3950     *
3951     * @see #sendAccessibilityEvent(int)
3952     */
3953    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
3954        if (mAccessibilityDelegate != null) {
3955           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
3956        } else {
3957            sendAccessibilityEventUncheckedInternal(event);
3958        }
3959    }
3960
3961    /**
3962     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
3963     *
3964     * Note: Called from the default {@link AccessibilityDelegate}.
3965     */
3966    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
3967        if (!isShown()) {
3968            return;
3969        }
3970        onInitializeAccessibilityEvent(event);
3971        // Only a subset of accessibility events populates text content.
3972        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
3973            dispatchPopulateAccessibilityEvent(event);
3974        }
3975        // In the beginning we called #isShown(), so we know that getParent() is not null.
3976        getParent().requestSendAccessibilityEvent(this, event);
3977    }
3978
3979    /**
3980     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
3981     * to its children for adding their text content to the event. Note that the
3982     * event text is populated in a separate dispatch path since we add to the
3983     * event not only the text of the source but also the text of all its descendants.
3984     * A typical implementation will call
3985     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
3986     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
3987     * on each child. Override this method if custom population of the event text
3988     * content is required.
3989     * <p>
3990     * If an {@link AccessibilityDelegate} has been specified via calling
3991     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3992     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
3993     * is responsible for handling this call.
3994     * </p>
3995     * <p>
3996     * <em>Note:</em> Accessibility events of certain types are not dispatched for
3997     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
3998     * </p>
3999     *
4000     * @param event The event.
4001     *
4002     * @return True if the event population was completed.
4003     */
4004    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4005        if (mAccessibilityDelegate != null) {
4006            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4007        } else {
4008            return dispatchPopulateAccessibilityEventInternal(event);
4009        }
4010    }
4011
4012    /**
4013     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4014     *
4015     * Note: Called from the default {@link AccessibilityDelegate}.
4016     */
4017    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4018        onPopulateAccessibilityEvent(event);
4019        return false;
4020    }
4021
4022    /**
4023     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4024     * giving a chance to this View to populate the accessibility event with its
4025     * text content. While this method is free to modify event
4026     * attributes other than text content, doing so should normally be performed in
4027     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4028     * <p>
4029     * Example: Adding formatted date string to an accessibility event in addition
4030     *          to the text added by the super implementation:
4031     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4032     *     super.onPopulateAccessibilityEvent(event);
4033     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4034     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4035     *         mCurrentDate.getTimeInMillis(), flags);
4036     *     event.getText().add(selectedDateUtterance);
4037     * }</pre>
4038     * <p>
4039     * If an {@link AccessibilityDelegate} has been specified via calling
4040     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4041     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4042     * is responsible for handling this call.
4043     * </p>
4044     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4045     * information to the event, in case the default implementation has basic information to add.
4046     * </p>
4047     *
4048     * @param event The accessibility event which to populate.
4049     *
4050     * @see #sendAccessibilityEvent(int)
4051     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4052     */
4053    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4054        if (mAccessibilityDelegate != null) {
4055            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4056        } else {
4057            onPopulateAccessibilityEventInternal(event);
4058        }
4059    }
4060
4061    /**
4062     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4063     *
4064     * Note: Called from the default {@link AccessibilityDelegate}.
4065     */
4066    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4067
4068    }
4069
4070    /**
4071     * Initializes an {@link AccessibilityEvent} with information about
4072     * this View which is the event source. In other words, the source of
4073     * an accessibility event is the view whose state change triggered firing
4074     * the event.
4075     * <p>
4076     * Example: Setting the password property of an event in addition
4077     *          to properties set by the super implementation:
4078     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4079     *     super.onInitializeAccessibilityEvent(event);
4080     *     event.setPassword(true);
4081     * }</pre>
4082     * <p>
4083     * If an {@link AccessibilityDelegate} has been specified via calling
4084     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4085     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4086     * is responsible for handling this call.
4087     * </p>
4088     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4089     * information to the event, in case the default implementation has basic information to add.
4090     * </p>
4091     * @param event The event to initialize.
4092     *
4093     * @see #sendAccessibilityEvent(int)
4094     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4095     */
4096    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4097        if (mAccessibilityDelegate != null) {
4098            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4099        } else {
4100            onInitializeAccessibilityEventInternal(event);
4101        }
4102    }
4103
4104    /**
4105     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4106     *
4107     * Note: Called from the default {@link AccessibilityDelegate}.
4108     */
4109    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4110        event.setSource(this);
4111        event.setClassName(View.class.getName());
4112        event.setPackageName(getContext().getPackageName());
4113        event.setEnabled(isEnabled());
4114        event.setContentDescription(mContentDescription);
4115
4116        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4117            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4118            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4119                    FOCUSABLES_ALL);
4120            event.setItemCount(focusablesTempList.size());
4121            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4122            focusablesTempList.clear();
4123        }
4124    }
4125
4126    /**
4127     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4128     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4129     * This method is responsible for obtaining an accessibility node info from a
4130     * pool of reusable instances and calling
4131     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4132     * initialize the former.
4133     * <p>
4134     * Note: The client is responsible for recycling the obtained instance by calling
4135     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4136     * </p>
4137     *
4138     * @return A populated {@link AccessibilityNodeInfo}.
4139     *
4140     * @see AccessibilityNodeInfo
4141     */
4142    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4143        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4144        if (provider != null) {
4145            return provider.createAccessibilityNodeInfo(View.NO_ID);
4146        } else {
4147            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4148            onInitializeAccessibilityNodeInfo(info);
4149            return info;
4150        }
4151    }
4152
4153    /**
4154     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4155     * The base implementation sets:
4156     * <ul>
4157     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4158     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4159     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4160     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4161     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4162     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4163     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4164     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4165     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4166     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4167     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4168     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4169     * </ul>
4170     * <p>
4171     * Subclasses should override this method, call the super implementation,
4172     * and set additional attributes.
4173     * </p>
4174     * <p>
4175     * If an {@link AccessibilityDelegate} has been specified via calling
4176     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4177     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4178     * is responsible for handling this call.
4179     * </p>
4180     *
4181     * @param info The instance to initialize.
4182     */
4183    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4184        if (mAccessibilityDelegate != null) {
4185            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4186        } else {
4187            onInitializeAccessibilityNodeInfoInternal(info);
4188        }
4189    }
4190
4191    /**
4192     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4193     *
4194     * Note: Called from the default {@link AccessibilityDelegate}.
4195     */
4196    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4197        Rect bounds = mAttachInfo.mTmpInvalRect;
4198        getDrawingRect(bounds);
4199        info.setBoundsInParent(bounds);
4200
4201        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4202        getLocationOnScreen(locationOnScreen);
4203        bounds.offsetTo(0, 0);
4204        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4205        info.setBoundsInScreen(bounds);
4206
4207        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4208            ViewParent parent = getParent();
4209            if (parent instanceof View) {
4210                View parentView = (View) parent;
4211                info.setParent(parentView);
4212            }
4213        }
4214
4215        info.setPackageName(mContext.getPackageName());
4216        info.setClassName(View.class.getName());
4217        info.setContentDescription(getContentDescription());
4218
4219        info.setEnabled(isEnabled());
4220        info.setClickable(isClickable());
4221        info.setFocusable(isFocusable());
4222        info.setFocused(isFocused());
4223        info.setSelected(isSelected());
4224        info.setLongClickable(isLongClickable());
4225
4226        // TODO: These make sense only if we are in an AdapterView but all
4227        // views can be selected. Maybe from accessiiblity perspective
4228        // we should report as selectable view in an AdapterView.
4229        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4230        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4231
4232        if (isFocusable()) {
4233            if (isFocused()) {
4234                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4235            } else {
4236                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4237            }
4238        }
4239    }
4240
4241    /**
4242     * Sets a delegate for implementing accessibility support via compositon as
4243     * opposed to inheritance. The delegate's primary use is for implementing
4244     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4245     *
4246     * @param delegate The delegate instance.
4247     *
4248     * @see AccessibilityDelegate
4249     */
4250    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4251        mAccessibilityDelegate = delegate;
4252    }
4253
4254    /**
4255     * Gets the provider for managing a virtual view hierarchy rooted at this View
4256     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4257     * that explore the window content.
4258     * <p>
4259     * If this method returns an instance, this instance is responsible for managing
4260     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4261     * View including the one representing the View itself. Similarly the returned
4262     * instance is responsible for performing accessibility actions on any virtual
4263     * view or the root view itself.
4264     * </p>
4265     * <p>
4266     * If an {@link AccessibilityDelegate} has been specified via calling
4267     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4268     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4269     * is responsible for handling this call.
4270     * </p>
4271     *
4272     * @return The provider.
4273     *
4274     * @see AccessibilityNodeProvider
4275     */
4276    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4277        if (mAccessibilityDelegate != null) {
4278            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4279        } else {
4280            return null;
4281        }
4282    }
4283
4284    /**
4285     * Gets the unique identifier of this view on the screen for accessibility purposes.
4286     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4287     *
4288     * @return The view accessibility id.
4289     *
4290     * @hide
4291     */
4292    public int getAccessibilityViewId() {
4293        if (mAccessibilityViewId == NO_ID) {
4294            mAccessibilityViewId = sNextAccessibilityViewId++;
4295        }
4296        return mAccessibilityViewId;
4297    }
4298
4299    /**
4300     * Gets the unique identifier of the window in which this View reseides.
4301     *
4302     * @return The window accessibility id.
4303     *
4304     * @hide
4305     */
4306    public int getAccessibilityWindowId() {
4307        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4308    }
4309
4310    /**
4311     * Gets the {@link View} description. It briefly describes the view and is
4312     * primarily used for accessibility support. Set this property to enable
4313     * better accessibility support for your application. This is especially
4314     * true for views that do not have textual representation (For example,
4315     * ImageButton).
4316     *
4317     * @return The content descriptiopn.
4318     *
4319     * @attr ref android.R.styleable#View_contentDescription
4320     */
4321    public CharSequence getContentDescription() {
4322        return mContentDescription;
4323    }
4324
4325    /**
4326     * Sets the {@link View} description. It briefly describes the view and is
4327     * primarily used for accessibility support. Set this property to enable
4328     * better accessibility support for your application. This is especially
4329     * true for views that do not have textual representation (For example,
4330     * ImageButton).
4331     *
4332     * @param contentDescription The content description.
4333     *
4334     * @attr ref android.R.styleable#View_contentDescription
4335     */
4336    @RemotableViewMethod
4337    public void setContentDescription(CharSequence contentDescription) {
4338        mContentDescription = contentDescription;
4339    }
4340
4341    /**
4342     * Invoked whenever this view loses focus, either by losing window focus or by losing
4343     * focus within its window. This method can be used to clear any state tied to the
4344     * focus. For instance, if a button is held pressed with the trackball and the window
4345     * loses focus, this method can be used to cancel the press.
4346     *
4347     * Subclasses of View overriding this method should always call super.onFocusLost().
4348     *
4349     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4350     * @see #onWindowFocusChanged(boolean)
4351     *
4352     * @hide pending API council approval
4353     */
4354    protected void onFocusLost() {
4355        resetPressedState();
4356    }
4357
4358    private void resetPressedState() {
4359        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4360            return;
4361        }
4362
4363        if (isPressed()) {
4364            setPressed(false);
4365
4366            if (!mHasPerformedLongPress) {
4367                removeLongPressCallback();
4368            }
4369        }
4370    }
4371
4372    /**
4373     * Returns true if this view has focus
4374     *
4375     * @return True if this view has focus, false otherwise.
4376     */
4377    @ViewDebug.ExportedProperty(category = "focus")
4378    public boolean isFocused() {
4379        return (mPrivateFlags & FOCUSED) != 0;
4380    }
4381
4382    /**
4383     * Find the view in the hierarchy rooted at this view that currently has
4384     * focus.
4385     *
4386     * @return The view that currently has focus, or null if no focused view can
4387     *         be found.
4388     */
4389    public View findFocus() {
4390        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4391    }
4392
4393    /**
4394     * Change whether this view is one of the set of scrollable containers in
4395     * its window.  This will be used to determine whether the window can
4396     * resize or must pan when a soft input area is open -- scrollable
4397     * containers allow the window to use resize mode since the container
4398     * will appropriately shrink.
4399     */
4400    public void setScrollContainer(boolean isScrollContainer) {
4401        if (isScrollContainer) {
4402            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4403                mAttachInfo.mScrollContainers.add(this);
4404                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4405            }
4406            mPrivateFlags |= SCROLL_CONTAINER;
4407        } else {
4408            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4409                mAttachInfo.mScrollContainers.remove(this);
4410            }
4411            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4412        }
4413    }
4414
4415    /**
4416     * Returns the quality of the drawing cache.
4417     *
4418     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4419     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4420     *
4421     * @see #setDrawingCacheQuality(int)
4422     * @see #setDrawingCacheEnabled(boolean)
4423     * @see #isDrawingCacheEnabled()
4424     *
4425     * @attr ref android.R.styleable#View_drawingCacheQuality
4426     */
4427    public int getDrawingCacheQuality() {
4428        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4429    }
4430
4431    /**
4432     * Set the drawing cache quality of this view. This value is used only when the
4433     * drawing cache is enabled
4434     *
4435     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4436     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4437     *
4438     * @see #getDrawingCacheQuality()
4439     * @see #setDrawingCacheEnabled(boolean)
4440     * @see #isDrawingCacheEnabled()
4441     *
4442     * @attr ref android.R.styleable#View_drawingCacheQuality
4443     */
4444    public void setDrawingCacheQuality(int quality) {
4445        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4446    }
4447
4448    /**
4449     * Returns whether the screen should remain on, corresponding to the current
4450     * value of {@link #KEEP_SCREEN_ON}.
4451     *
4452     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4453     *
4454     * @see #setKeepScreenOn(boolean)
4455     *
4456     * @attr ref android.R.styleable#View_keepScreenOn
4457     */
4458    public boolean getKeepScreenOn() {
4459        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4460    }
4461
4462    /**
4463     * Controls whether the screen should remain on, modifying the
4464     * value of {@link #KEEP_SCREEN_ON}.
4465     *
4466     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4467     *
4468     * @see #getKeepScreenOn()
4469     *
4470     * @attr ref android.R.styleable#View_keepScreenOn
4471     */
4472    public void setKeepScreenOn(boolean keepScreenOn) {
4473        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4474    }
4475
4476    /**
4477     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4478     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4479     *
4480     * @attr ref android.R.styleable#View_nextFocusLeft
4481     */
4482    public int getNextFocusLeftId() {
4483        return mNextFocusLeftId;
4484    }
4485
4486    /**
4487     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4488     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4489     * decide automatically.
4490     *
4491     * @attr ref android.R.styleable#View_nextFocusLeft
4492     */
4493    public void setNextFocusLeftId(int nextFocusLeftId) {
4494        mNextFocusLeftId = nextFocusLeftId;
4495    }
4496
4497    /**
4498     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4499     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4500     *
4501     * @attr ref android.R.styleable#View_nextFocusRight
4502     */
4503    public int getNextFocusRightId() {
4504        return mNextFocusRightId;
4505    }
4506
4507    /**
4508     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4509     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4510     * decide automatically.
4511     *
4512     * @attr ref android.R.styleable#View_nextFocusRight
4513     */
4514    public void setNextFocusRightId(int nextFocusRightId) {
4515        mNextFocusRightId = nextFocusRightId;
4516    }
4517
4518    /**
4519     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4520     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4521     *
4522     * @attr ref android.R.styleable#View_nextFocusUp
4523     */
4524    public int getNextFocusUpId() {
4525        return mNextFocusUpId;
4526    }
4527
4528    /**
4529     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4530     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4531     * decide automatically.
4532     *
4533     * @attr ref android.R.styleable#View_nextFocusUp
4534     */
4535    public void setNextFocusUpId(int nextFocusUpId) {
4536        mNextFocusUpId = nextFocusUpId;
4537    }
4538
4539    /**
4540     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4541     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4542     *
4543     * @attr ref android.R.styleable#View_nextFocusDown
4544     */
4545    public int getNextFocusDownId() {
4546        return mNextFocusDownId;
4547    }
4548
4549    /**
4550     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4551     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4552     * decide automatically.
4553     *
4554     * @attr ref android.R.styleable#View_nextFocusDown
4555     */
4556    public void setNextFocusDownId(int nextFocusDownId) {
4557        mNextFocusDownId = nextFocusDownId;
4558    }
4559
4560    /**
4561     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4562     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4563     *
4564     * @attr ref android.R.styleable#View_nextFocusForward
4565     */
4566    public int getNextFocusForwardId() {
4567        return mNextFocusForwardId;
4568    }
4569
4570    /**
4571     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4572     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4573     * decide automatically.
4574     *
4575     * @attr ref android.R.styleable#View_nextFocusForward
4576     */
4577    public void setNextFocusForwardId(int nextFocusForwardId) {
4578        mNextFocusForwardId = nextFocusForwardId;
4579    }
4580
4581    /**
4582     * Returns the visibility of this view and all of its ancestors
4583     *
4584     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4585     */
4586    public boolean isShown() {
4587        View current = this;
4588        //noinspection ConstantConditions
4589        do {
4590            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4591                return false;
4592            }
4593            ViewParent parent = current.mParent;
4594            if (parent == null) {
4595                return false; // We are not attached to the view root
4596            }
4597            if (!(parent instanceof View)) {
4598                return true;
4599            }
4600            current = (View) parent;
4601        } while (current != null);
4602
4603        return false;
4604    }
4605
4606    /**
4607     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4608     * is set
4609     *
4610     * @param insets Insets for system windows
4611     *
4612     * @return True if this view applied the insets, false otherwise
4613     */
4614    protected boolean fitSystemWindows(Rect insets) {
4615        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4616            mPaddingLeft = insets.left;
4617            mPaddingTop = insets.top;
4618            mPaddingRight = insets.right;
4619            mPaddingBottom = insets.bottom;
4620            requestLayout();
4621            return true;
4622        }
4623        return false;
4624    }
4625
4626    /**
4627     * Set whether or not this view should account for system screen decorations
4628     * such as the status bar and inset its content. This allows this view to be
4629     * positioned in absolute screen coordinates and remain visible to the user.
4630     *
4631     * <p>This should only be used by top-level window decor views.
4632     *
4633     * @param fitSystemWindows true to inset content for system screen decorations, false for
4634     *                         default behavior.
4635     *
4636     * @attr ref android.R.styleable#View_fitsSystemWindows
4637     */
4638    public void setFitsSystemWindows(boolean fitSystemWindows) {
4639        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4640    }
4641
4642    /**
4643     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4644     * will account for system screen decorations such as the status bar and inset its
4645     * content. This allows the view to be positioned in absolute screen coordinates
4646     * and remain visible to the user.
4647     *
4648     * @return true if this view will adjust its content bounds for system screen decorations.
4649     *
4650     * @attr ref android.R.styleable#View_fitsSystemWindows
4651     */
4652    public boolean fitsSystemWindows() {
4653        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4654    }
4655
4656    /**
4657     * Returns the visibility status for this view.
4658     *
4659     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4660     * @attr ref android.R.styleable#View_visibility
4661     */
4662    @ViewDebug.ExportedProperty(mapping = {
4663        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4664        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4665        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4666    })
4667    public int getVisibility() {
4668        return mViewFlags & VISIBILITY_MASK;
4669    }
4670
4671    /**
4672     * Set the enabled state of this view.
4673     *
4674     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4675     * @attr ref android.R.styleable#View_visibility
4676     */
4677    @RemotableViewMethod
4678    public void setVisibility(int visibility) {
4679        setFlags(visibility, VISIBILITY_MASK);
4680        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4681    }
4682
4683    /**
4684     * Returns the enabled status for this view. The interpretation of the
4685     * enabled state varies by subclass.
4686     *
4687     * @return True if this view is enabled, false otherwise.
4688     */
4689    @ViewDebug.ExportedProperty
4690    public boolean isEnabled() {
4691        return (mViewFlags & ENABLED_MASK) == ENABLED;
4692    }
4693
4694    /**
4695     * Set the enabled state of this view. The interpretation of the enabled
4696     * state varies by subclass.
4697     *
4698     * @param enabled True if this view is enabled, false otherwise.
4699     */
4700    @RemotableViewMethod
4701    public void setEnabled(boolean enabled) {
4702        if (enabled == isEnabled()) return;
4703
4704        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4705
4706        /*
4707         * The View most likely has to change its appearance, so refresh
4708         * the drawable state.
4709         */
4710        refreshDrawableState();
4711
4712        // Invalidate too, since the default behavior for views is to be
4713        // be drawn at 50% alpha rather than to change the drawable.
4714        invalidate(true);
4715    }
4716
4717    /**
4718     * Set whether this view can receive the focus.
4719     *
4720     * Setting this to false will also ensure that this view is not focusable
4721     * in touch mode.
4722     *
4723     * @param focusable If true, this view can receive the focus.
4724     *
4725     * @see #setFocusableInTouchMode(boolean)
4726     * @attr ref android.R.styleable#View_focusable
4727     */
4728    public void setFocusable(boolean focusable) {
4729        if (!focusable) {
4730            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4731        }
4732        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4733    }
4734
4735    /**
4736     * Set whether this view can receive focus while in touch mode.
4737     *
4738     * Setting this to true will also ensure that this view is focusable.
4739     *
4740     * @param focusableInTouchMode If true, this view can receive the focus while
4741     *   in touch mode.
4742     *
4743     * @see #setFocusable(boolean)
4744     * @attr ref android.R.styleable#View_focusableInTouchMode
4745     */
4746    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4747        // Focusable in touch mode should always be set before the focusable flag
4748        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4749        // which, in touch mode, will not successfully request focus on this view
4750        // because the focusable in touch mode flag is not set
4751        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4752        if (focusableInTouchMode) {
4753            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4754        }
4755    }
4756
4757    /**
4758     * Set whether this view should have sound effects enabled for events such as
4759     * clicking and touching.
4760     *
4761     * <p>You may wish to disable sound effects for a view if you already play sounds,
4762     * for instance, a dial key that plays dtmf tones.
4763     *
4764     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4765     * @see #isSoundEffectsEnabled()
4766     * @see #playSoundEffect(int)
4767     * @attr ref android.R.styleable#View_soundEffectsEnabled
4768     */
4769    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4770        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4771    }
4772
4773    /**
4774     * @return whether this view should have sound effects enabled for events such as
4775     *     clicking and touching.
4776     *
4777     * @see #setSoundEffectsEnabled(boolean)
4778     * @see #playSoundEffect(int)
4779     * @attr ref android.R.styleable#View_soundEffectsEnabled
4780     */
4781    @ViewDebug.ExportedProperty
4782    public boolean isSoundEffectsEnabled() {
4783        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4784    }
4785
4786    /**
4787     * Set whether this view should have haptic feedback for events such as
4788     * long presses.
4789     *
4790     * <p>You may wish to disable haptic feedback if your view already controls
4791     * its own haptic feedback.
4792     *
4793     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4794     * @see #isHapticFeedbackEnabled()
4795     * @see #performHapticFeedback(int)
4796     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4797     */
4798    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4799        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4800    }
4801
4802    /**
4803     * @return whether this view should have haptic feedback enabled for events
4804     * long presses.
4805     *
4806     * @see #setHapticFeedbackEnabled(boolean)
4807     * @see #performHapticFeedback(int)
4808     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4809     */
4810    @ViewDebug.ExportedProperty
4811    public boolean isHapticFeedbackEnabled() {
4812        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4813    }
4814
4815    /**
4816     * Returns the layout direction for this view.
4817     *
4818     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4819     *   {@link #LAYOUT_DIRECTION_RTL},
4820     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4821     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4822     * @attr ref android.R.styleable#View_layoutDirection
4823     *
4824     * @hide
4825     */
4826    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4827        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4828        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4829        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4830        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4831    })
4832    public int getLayoutDirection() {
4833        return mViewFlags & LAYOUT_DIRECTION_MASK;
4834    }
4835
4836    /**
4837     * Set the layout direction for this view. This will propagate a reset of layout direction
4838     * resolution to the view's children and resolve layout direction for this view.
4839     *
4840     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4841     *   {@link #LAYOUT_DIRECTION_RTL},
4842     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4843     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4844     *
4845     * @attr ref android.R.styleable#View_layoutDirection
4846     *
4847     * @hide
4848     */
4849    @RemotableViewMethod
4850    public void setLayoutDirection(int layoutDirection) {
4851        if (getLayoutDirection() != layoutDirection) {
4852            resetResolvedLayoutDirection();
4853            // Setting the flag will also request a layout.
4854            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4855        }
4856    }
4857
4858    /**
4859     * Returns the resolved layout direction for this view.
4860     *
4861     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4862     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4863     *
4864     * @hide
4865     */
4866    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4867        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4868        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4869    })
4870    public int getResolvedLayoutDirection() {
4871        resolveLayoutDirectionIfNeeded();
4872        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4873                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4874    }
4875
4876    /**
4877     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4878     * layout attribute and/or the inherited value from the parent.</p>
4879     *
4880     * @return true if the layout is right-to-left.
4881     *
4882     * @hide
4883     */
4884    @ViewDebug.ExportedProperty(category = "layout")
4885    public boolean isLayoutRtl() {
4886        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4887    }
4888
4889    /**
4890     * If this view doesn't do any drawing on its own, set this flag to
4891     * allow further optimizations. By default, this flag is not set on
4892     * View, but could be set on some View subclasses such as ViewGroup.
4893     *
4894     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4895     * you should clear this flag.
4896     *
4897     * @param willNotDraw whether or not this View draw on its own
4898     */
4899    public void setWillNotDraw(boolean willNotDraw) {
4900        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4901    }
4902
4903    /**
4904     * Returns whether or not this View draws on its own.
4905     *
4906     * @return true if this view has nothing to draw, false otherwise
4907     */
4908    @ViewDebug.ExportedProperty(category = "drawing")
4909    public boolean willNotDraw() {
4910        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4911    }
4912
4913    /**
4914     * When a View's drawing cache is enabled, drawing is redirected to an
4915     * offscreen bitmap. Some views, like an ImageView, must be able to
4916     * bypass this mechanism if they already draw a single bitmap, to avoid
4917     * unnecessary usage of the memory.
4918     *
4919     * @param willNotCacheDrawing true if this view does not cache its
4920     *        drawing, false otherwise
4921     */
4922    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
4923        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
4924    }
4925
4926    /**
4927     * Returns whether or not this View can cache its drawing or not.
4928     *
4929     * @return true if this view does not cache its drawing, false otherwise
4930     */
4931    @ViewDebug.ExportedProperty(category = "drawing")
4932    public boolean willNotCacheDrawing() {
4933        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
4934    }
4935
4936    /**
4937     * Indicates whether this view reacts to click events or not.
4938     *
4939     * @return true if the view is clickable, false otherwise
4940     *
4941     * @see #setClickable(boolean)
4942     * @attr ref android.R.styleable#View_clickable
4943     */
4944    @ViewDebug.ExportedProperty
4945    public boolean isClickable() {
4946        return (mViewFlags & CLICKABLE) == CLICKABLE;
4947    }
4948
4949    /**
4950     * Enables or disables click events for this view. When a view
4951     * is clickable it will change its state to "pressed" on every click.
4952     * Subclasses should set the view clickable to visually react to
4953     * user's clicks.
4954     *
4955     * @param clickable true to make the view clickable, false otherwise
4956     *
4957     * @see #isClickable()
4958     * @attr ref android.R.styleable#View_clickable
4959     */
4960    public void setClickable(boolean clickable) {
4961        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
4962    }
4963
4964    /**
4965     * Indicates whether this view reacts to long click events or not.
4966     *
4967     * @return true if the view is long clickable, false otherwise
4968     *
4969     * @see #setLongClickable(boolean)
4970     * @attr ref android.R.styleable#View_longClickable
4971     */
4972    public boolean isLongClickable() {
4973        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
4974    }
4975
4976    /**
4977     * Enables or disables long click events for this view. When a view is long
4978     * clickable it reacts to the user holding down the button for a longer
4979     * duration than a tap. This event can either launch the listener or a
4980     * context menu.
4981     *
4982     * @param longClickable true to make the view long clickable, false otherwise
4983     * @see #isLongClickable()
4984     * @attr ref android.R.styleable#View_longClickable
4985     */
4986    public void setLongClickable(boolean longClickable) {
4987        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
4988    }
4989
4990    /**
4991     * Sets the pressed state for this view.
4992     *
4993     * @see #isClickable()
4994     * @see #setClickable(boolean)
4995     *
4996     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
4997     *        the View's internal state from a previously set "pressed" state.
4998     */
4999    public void setPressed(boolean pressed) {
5000        if (pressed) {
5001            mPrivateFlags |= PRESSED;
5002        } else {
5003            mPrivateFlags &= ~PRESSED;
5004        }
5005        refreshDrawableState();
5006        dispatchSetPressed(pressed);
5007    }
5008
5009    /**
5010     * Dispatch setPressed to all of this View's children.
5011     *
5012     * @see #setPressed(boolean)
5013     *
5014     * @param pressed The new pressed state
5015     */
5016    protected void dispatchSetPressed(boolean pressed) {
5017    }
5018
5019    /**
5020     * Indicates whether the view is currently in pressed state. Unless
5021     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5022     * the pressed state.
5023     *
5024     * @see #setPressed(boolean)
5025     * @see #isClickable()
5026     * @see #setClickable(boolean)
5027     *
5028     * @return true if the view is currently pressed, false otherwise
5029     */
5030    public boolean isPressed() {
5031        return (mPrivateFlags & PRESSED) == PRESSED;
5032    }
5033
5034    /**
5035     * Indicates whether this view will save its state (that is,
5036     * whether its {@link #onSaveInstanceState} method will be called).
5037     *
5038     * @return Returns true if the view state saving is enabled, else false.
5039     *
5040     * @see #setSaveEnabled(boolean)
5041     * @attr ref android.R.styleable#View_saveEnabled
5042     */
5043    public boolean isSaveEnabled() {
5044        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5045    }
5046
5047    /**
5048     * Controls whether the saving of this view's state is
5049     * enabled (that is, whether its {@link #onSaveInstanceState} method
5050     * will be called).  Note that even if freezing is enabled, the
5051     * view still must have an id assigned to it (via {@link #setId(int)})
5052     * for its state to be saved.  This flag can only disable the
5053     * saving of this view; any child views may still have their state saved.
5054     *
5055     * @param enabled Set to false to <em>disable</em> state saving, or true
5056     * (the default) to allow it.
5057     *
5058     * @see #isSaveEnabled()
5059     * @see #setId(int)
5060     * @see #onSaveInstanceState()
5061     * @attr ref android.R.styleable#View_saveEnabled
5062     */
5063    public void setSaveEnabled(boolean enabled) {
5064        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5065    }
5066
5067    /**
5068     * Gets whether the framework should discard touches when the view's
5069     * window is obscured by another visible window.
5070     * Refer to the {@link View} security documentation for more details.
5071     *
5072     * @return True if touch filtering is enabled.
5073     *
5074     * @see #setFilterTouchesWhenObscured(boolean)
5075     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5076     */
5077    @ViewDebug.ExportedProperty
5078    public boolean getFilterTouchesWhenObscured() {
5079        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5080    }
5081
5082    /**
5083     * Sets whether the framework should discard touches when the view's
5084     * window is obscured by another visible window.
5085     * Refer to the {@link View} security documentation for more details.
5086     *
5087     * @param enabled True if touch filtering should be enabled.
5088     *
5089     * @see #getFilterTouchesWhenObscured
5090     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5091     */
5092    public void setFilterTouchesWhenObscured(boolean enabled) {
5093        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5094                FILTER_TOUCHES_WHEN_OBSCURED);
5095    }
5096
5097    /**
5098     * Indicates whether the entire hierarchy under this view will save its
5099     * state when a state saving traversal occurs from its parent.  The default
5100     * is true; if false, these views will not be saved unless
5101     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5102     *
5103     * @return Returns true if the view state saving from parent is enabled, else false.
5104     *
5105     * @see #setSaveFromParentEnabled(boolean)
5106     */
5107    public boolean isSaveFromParentEnabled() {
5108        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5109    }
5110
5111    /**
5112     * Controls whether the entire hierarchy under this view will save its
5113     * state when a state saving traversal occurs from its parent.  The default
5114     * is true; if false, these views will not be saved unless
5115     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5116     *
5117     * @param enabled Set to false to <em>disable</em> state saving, or true
5118     * (the default) to allow it.
5119     *
5120     * @see #isSaveFromParentEnabled()
5121     * @see #setId(int)
5122     * @see #onSaveInstanceState()
5123     */
5124    public void setSaveFromParentEnabled(boolean enabled) {
5125        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5126    }
5127
5128
5129    /**
5130     * Returns whether this View is able to take focus.
5131     *
5132     * @return True if this view can take focus, or false otherwise.
5133     * @attr ref android.R.styleable#View_focusable
5134     */
5135    @ViewDebug.ExportedProperty(category = "focus")
5136    public final boolean isFocusable() {
5137        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5138    }
5139
5140    /**
5141     * When a view is focusable, it may not want to take focus when in touch mode.
5142     * For example, a button would like focus when the user is navigating via a D-pad
5143     * so that the user can click on it, but once the user starts touching the screen,
5144     * the button shouldn't take focus
5145     * @return Whether the view is focusable in touch mode.
5146     * @attr ref android.R.styleable#View_focusableInTouchMode
5147     */
5148    @ViewDebug.ExportedProperty
5149    public final boolean isFocusableInTouchMode() {
5150        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5151    }
5152
5153    /**
5154     * Find the nearest view in the specified direction that can take focus.
5155     * This does not actually give focus to that view.
5156     *
5157     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5158     *
5159     * @return The nearest focusable in the specified direction, or null if none
5160     *         can be found.
5161     */
5162    public View focusSearch(int direction) {
5163        if (mParent != null) {
5164            return mParent.focusSearch(this, direction);
5165        } else {
5166            return null;
5167        }
5168    }
5169
5170    /**
5171     * This method is the last chance for the focused view and its ancestors to
5172     * respond to an arrow key. This is called when the focused view did not
5173     * consume the key internally, nor could the view system find a new view in
5174     * the requested direction to give focus to.
5175     *
5176     * @param focused The currently focused view.
5177     * @param direction The direction focus wants to move. One of FOCUS_UP,
5178     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5179     * @return True if the this view consumed this unhandled move.
5180     */
5181    public boolean dispatchUnhandledMove(View focused, int direction) {
5182        return false;
5183    }
5184
5185    /**
5186     * If a user manually specified the next view id for a particular direction,
5187     * use the root to look up the view.
5188     * @param root The root view of the hierarchy containing this view.
5189     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5190     * or FOCUS_BACKWARD.
5191     * @return The user specified next view, or null if there is none.
5192     */
5193    View findUserSetNextFocus(View root, int direction) {
5194        switch (direction) {
5195            case FOCUS_LEFT:
5196                if (mNextFocusLeftId == View.NO_ID) return null;
5197                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5198            case FOCUS_RIGHT:
5199                if (mNextFocusRightId == View.NO_ID) return null;
5200                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5201            case FOCUS_UP:
5202                if (mNextFocusUpId == View.NO_ID) return null;
5203                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5204            case FOCUS_DOWN:
5205                if (mNextFocusDownId == View.NO_ID) return null;
5206                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5207            case FOCUS_FORWARD:
5208                if (mNextFocusForwardId == View.NO_ID) return null;
5209                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5210            case FOCUS_BACKWARD: {
5211                final int id = mID;
5212                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5213                    @Override
5214                    public boolean apply(View t) {
5215                        return t.mNextFocusForwardId == id;
5216                    }
5217                });
5218            }
5219        }
5220        return null;
5221    }
5222
5223    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5224        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5225            @Override
5226            public boolean apply(View t) {
5227                return t.mID == childViewId;
5228            }
5229        });
5230
5231        if (result == null) {
5232            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5233                    + "by user for id " + childViewId);
5234        }
5235        return result;
5236    }
5237
5238    /**
5239     * Find and return all focusable views that are descendants of this view,
5240     * possibly including this view if it is focusable itself.
5241     *
5242     * @param direction The direction of the focus
5243     * @return A list of focusable views
5244     */
5245    public ArrayList<View> getFocusables(int direction) {
5246        ArrayList<View> result = new ArrayList<View>(24);
5247        addFocusables(result, direction);
5248        return result;
5249    }
5250
5251    /**
5252     * Add any focusable views that are descendants of this view (possibly
5253     * including this view if it is focusable itself) to views.  If we are in touch mode,
5254     * only add views that are also focusable in touch mode.
5255     *
5256     * @param views Focusable views found so far
5257     * @param direction The direction of the focus
5258     */
5259    public void addFocusables(ArrayList<View> views, int direction) {
5260        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5261    }
5262
5263    /**
5264     * Adds any focusable views that are descendants of this view (possibly
5265     * including this view if it is focusable itself) to views. This method
5266     * adds all focusable views regardless if we are in touch mode or
5267     * only views focusable in touch mode if we are in touch mode depending on
5268     * the focusable mode paramater.
5269     *
5270     * @param views Focusable views found so far or null if all we are interested is
5271     *        the number of focusables.
5272     * @param direction The direction of the focus.
5273     * @param focusableMode The type of focusables to be added.
5274     *
5275     * @see #FOCUSABLES_ALL
5276     * @see #FOCUSABLES_TOUCH_MODE
5277     */
5278    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5279        if (!isFocusable()) {
5280            return;
5281        }
5282
5283        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5284                isInTouchMode() && !isFocusableInTouchMode()) {
5285            return;
5286        }
5287
5288        if (views != null) {
5289            views.add(this);
5290        }
5291    }
5292
5293    /**
5294     * Finds the Views that contain given text. The containment is case insensitive.
5295     * The search is performed by either the text that the View renders or the content
5296     * description that describes the view for accessibility purposes and the view does
5297     * not render or both. Clients can specify how the search is to be performed via
5298     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5299     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5300     *
5301     * @param outViews The output list of matching Views.
5302     * @param searched The text to match against.
5303     *
5304     * @see #FIND_VIEWS_WITH_TEXT
5305     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5306     * @see #setContentDescription(CharSequence)
5307     */
5308    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5309        if (getAccessibilityNodeProvider() != null) {
5310            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5311                outViews.add(this);
5312            }
5313        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5314                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5315            String searchedLowerCase = searched.toString().toLowerCase();
5316            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5317            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5318                outViews.add(this);
5319            }
5320        }
5321    }
5322
5323    /**
5324     * Find and return all touchable views that are descendants of this view,
5325     * possibly including this view if it is touchable itself.
5326     *
5327     * @return A list of touchable views
5328     */
5329    public ArrayList<View> getTouchables() {
5330        ArrayList<View> result = new ArrayList<View>();
5331        addTouchables(result);
5332        return result;
5333    }
5334
5335    /**
5336     * Add any touchable views that are descendants of this view (possibly
5337     * including this view if it is touchable itself) to views.
5338     *
5339     * @param views Touchable views found so far
5340     */
5341    public void addTouchables(ArrayList<View> views) {
5342        final int viewFlags = mViewFlags;
5343
5344        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5345                && (viewFlags & ENABLED_MASK) == ENABLED) {
5346            views.add(this);
5347        }
5348    }
5349
5350    /**
5351     * Call this to try to give focus to a specific view or to one of its
5352     * descendants.
5353     *
5354     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5355     * false), or if it is focusable and it is not focusable in touch mode
5356     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5357     *
5358     * See also {@link #focusSearch(int)}, which is what you call to say that you
5359     * have focus, and you want your parent to look for the next one.
5360     *
5361     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5362     * {@link #FOCUS_DOWN} and <code>null</code>.
5363     *
5364     * @return Whether this view or one of its descendants actually took focus.
5365     */
5366    public final boolean requestFocus() {
5367        return requestFocus(View.FOCUS_DOWN);
5368    }
5369
5370
5371    /**
5372     * Call this to try to give focus to a specific view or to one of its
5373     * descendants and give it a hint about what direction focus is heading.
5374     *
5375     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5376     * false), or if it is focusable and it is not focusable in touch mode
5377     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5378     *
5379     * See also {@link #focusSearch(int)}, which is what you call to say that you
5380     * have focus, and you want your parent to look for the next one.
5381     *
5382     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5383     * <code>null</code> set for the previously focused rectangle.
5384     *
5385     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5386     * @return Whether this view or one of its descendants actually took focus.
5387     */
5388    public final boolean requestFocus(int direction) {
5389        return requestFocus(direction, null);
5390    }
5391
5392    /**
5393     * Call this to try to give focus to a specific view or to one of its descendants
5394     * and give it hints about the direction and a specific rectangle that the focus
5395     * is coming from.  The rectangle can help give larger views a finer grained hint
5396     * about where focus is coming from, and therefore, where to show selection, or
5397     * forward focus change internally.
5398     *
5399     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5400     * false), or if it is focusable and it is not focusable in touch mode
5401     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5402     *
5403     * A View will not take focus if it is not visible.
5404     *
5405     * A View will not take focus if one of its parents has
5406     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5407     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5408     *
5409     * See also {@link #focusSearch(int)}, which is what you call to say that you
5410     * have focus, and you want your parent to look for the next one.
5411     *
5412     * You may wish to override this method if your custom {@link View} has an internal
5413     * {@link View} that it wishes to forward the request to.
5414     *
5415     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5416     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5417     *        to give a finer grained hint about where focus is coming from.  May be null
5418     *        if there is no hint.
5419     * @return Whether this view or one of its descendants actually took focus.
5420     */
5421    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5422        // need to be focusable
5423        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5424                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5425            return false;
5426        }
5427
5428        // need to be focusable in touch mode if in touch mode
5429        if (isInTouchMode() &&
5430            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5431               return false;
5432        }
5433
5434        // need to not have any parents blocking us
5435        if (hasAncestorThatBlocksDescendantFocus()) {
5436            return false;
5437        }
5438
5439        handleFocusGainInternal(direction, previouslyFocusedRect);
5440        return true;
5441    }
5442
5443    /** Gets the ViewAncestor, or null if not attached. */
5444    /*package*/ ViewRootImpl getViewRootImpl() {
5445        View root = getRootView();
5446        return root != null ? (ViewRootImpl)root.getParent() : null;
5447    }
5448
5449    /**
5450     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5451     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5452     * touch mode to request focus when they are touched.
5453     *
5454     * @return Whether this view or one of its descendants actually took focus.
5455     *
5456     * @see #isInTouchMode()
5457     *
5458     */
5459    public final boolean requestFocusFromTouch() {
5460        // Leave touch mode if we need to
5461        if (isInTouchMode()) {
5462            ViewRootImpl viewRoot = getViewRootImpl();
5463            if (viewRoot != null) {
5464                viewRoot.ensureTouchMode(false);
5465            }
5466        }
5467        return requestFocus(View.FOCUS_DOWN);
5468    }
5469
5470    /**
5471     * @return Whether any ancestor of this view blocks descendant focus.
5472     */
5473    private boolean hasAncestorThatBlocksDescendantFocus() {
5474        ViewParent ancestor = mParent;
5475        while (ancestor instanceof ViewGroup) {
5476            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5477            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5478                return true;
5479            } else {
5480                ancestor = vgAncestor.getParent();
5481            }
5482        }
5483        return false;
5484    }
5485
5486    /**
5487     * @hide
5488     */
5489    public void dispatchStartTemporaryDetach() {
5490        onStartTemporaryDetach();
5491    }
5492
5493    /**
5494     * This is called when a container is going to temporarily detach a child, with
5495     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5496     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5497     * {@link #onDetachedFromWindow()} when the container is done.
5498     */
5499    public void onStartTemporaryDetach() {
5500        removeUnsetPressCallback();
5501        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5502    }
5503
5504    /**
5505     * @hide
5506     */
5507    public void dispatchFinishTemporaryDetach() {
5508        onFinishTemporaryDetach();
5509    }
5510
5511    /**
5512     * Called after {@link #onStartTemporaryDetach} when the container is done
5513     * changing the view.
5514     */
5515    public void onFinishTemporaryDetach() {
5516    }
5517
5518    /**
5519     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5520     * for this view's window.  Returns null if the view is not currently attached
5521     * to the window.  Normally you will not need to use this directly, but
5522     * just use the standard high-level event callbacks like
5523     * {@link #onKeyDown(int, KeyEvent)}.
5524     */
5525    public KeyEvent.DispatcherState getKeyDispatcherState() {
5526        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5527    }
5528
5529    /**
5530     * Dispatch a key event before it is processed by any input method
5531     * associated with the view hierarchy.  This can be used to intercept
5532     * key events in special situations before the IME consumes them; a
5533     * typical example would be handling the BACK key to update the application's
5534     * UI instead of allowing the IME to see it and close itself.
5535     *
5536     * @param event The key event to be dispatched.
5537     * @return True if the event was handled, false otherwise.
5538     */
5539    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5540        return onKeyPreIme(event.getKeyCode(), event);
5541    }
5542
5543    /**
5544     * Dispatch a key event to the next view on the focus path. This path runs
5545     * from the top of the view tree down to the currently focused view. If this
5546     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5547     * the next node down the focus path. This method also fires any key
5548     * listeners.
5549     *
5550     * @param event The key event to be dispatched.
5551     * @return True if the event was handled, false otherwise.
5552     */
5553    public boolean dispatchKeyEvent(KeyEvent event) {
5554        if (mInputEventConsistencyVerifier != null) {
5555            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5556        }
5557
5558        // Give any attached key listener a first crack at the event.
5559        //noinspection SimplifiableIfStatement
5560        ListenerInfo li = mListenerInfo;
5561        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5562                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5563            return true;
5564        }
5565
5566        if (event.dispatch(this, mAttachInfo != null
5567                ? mAttachInfo.mKeyDispatchState : null, this)) {
5568            return true;
5569        }
5570
5571        if (mInputEventConsistencyVerifier != null) {
5572            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5573        }
5574        return false;
5575    }
5576
5577    /**
5578     * Dispatches a key shortcut event.
5579     *
5580     * @param event The key event to be dispatched.
5581     * @return True if the event was handled by the view, false otherwise.
5582     */
5583    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5584        return onKeyShortcut(event.getKeyCode(), event);
5585    }
5586
5587    /**
5588     * Pass the touch screen motion event down to the target view, or this
5589     * view if it is the target.
5590     *
5591     * @param event The motion event to be dispatched.
5592     * @return True if the event was handled by the view, false otherwise.
5593     */
5594    public boolean dispatchTouchEvent(MotionEvent event) {
5595        if (mInputEventConsistencyVerifier != null) {
5596            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5597        }
5598
5599        if (onFilterTouchEventForSecurity(event)) {
5600            //noinspection SimplifiableIfStatement
5601            ListenerInfo li = mListenerInfo;
5602            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5603                    && li.mOnTouchListener.onTouch(this, event)) {
5604                return true;
5605            }
5606
5607            if (onTouchEvent(event)) {
5608                return true;
5609            }
5610        }
5611
5612        if (mInputEventConsistencyVerifier != null) {
5613            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5614        }
5615        return false;
5616    }
5617
5618    /**
5619     * Filter the touch event to apply security policies.
5620     *
5621     * @param event The motion event to be filtered.
5622     * @return True if the event should be dispatched, false if the event should be dropped.
5623     *
5624     * @see #getFilterTouchesWhenObscured
5625     */
5626    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5627        //noinspection RedundantIfStatement
5628        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5629                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5630            // Window is obscured, drop this touch.
5631            return false;
5632        }
5633        return true;
5634    }
5635
5636    /**
5637     * Pass a trackball motion event down to the focused view.
5638     *
5639     * @param event The motion event to be dispatched.
5640     * @return True if the event was handled by the view, false otherwise.
5641     */
5642    public boolean dispatchTrackballEvent(MotionEvent event) {
5643        if (mInputEventConsistencyVerifier != null) {
5644            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5645        }
5646
5647        return onTrackballEvent(event);
5648    }
5649
5650    /**
5651     * Dispatch a generic motion event.
5652     * <p>
5653     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5654     * are delivered to the view under the pointer.  All other generic motion events are
5655     * delivered to the focused view.  Hover events are handled specially and are delivered
5656     * to {@link #onHoverEvent(MotionEvent)}.
5657     * </p>
5658     *
5659     * @param event The motion event to be dispatched.
5660     * @return True if the event was handled by the view, false otherwise.
5661     */
5662    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5663        if (mInputEventConsistencyVerifier != null) {
5664            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5665        }
5666
5667        final int source = event.getSource();
5668        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5669            final int action = event.getAction();
5670            if (action == MotionEvent.ACTION_HOVER_ENTER
5671                    || action == MotionEvent.ACTION_HOVER_MOVE
5672                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5673                if (dispatchHoverEvent(event)) {
5674                    return true;
5675                }
5676            } else if (dispatchGenericPointerEvent(event)) {
5677                return true;
5678            }
5679        } else if (dispatchGenericFocusedEvent(event)) {
5680            return true;
5681        }
5682
5683        if (dispatchGenericMotionEventInternal(event)) {
5684            return true;
5685        }
5686
5687        if (mInputEventConsistencyVerifier != null) {
5688            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5689        }
5690        return false;
5691    }
5692
5693    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5694        //noinspection SimplifiableIfStatement
5695        ListenerInfo li = mListenerInfo;
5696        if (li != null && li.mOnGenericMotionListener != null
5697                && (mViewFlags & ENABLED_MASK) == ENABLED
5698                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5699            return true;
5700        }
5701
5702        if (onGenericMotionEvent(event)) {
5703            return true;
5704        }
5705
5706        if (mInputEventConsistencyVerifier != null) {
5707            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5708        }
5709        return false;
5710    }
5711
5712    /**
5713     * Dispatch a hover event.
5714     * <p>
5715     * Do not call this method directly.
5716     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5717     * </p>
5718     *
5719     * @param event The motion event to be dispatched.
5720     * @return True if the event was handled by the view, false otherwise.
5721     */
5722    protected boolean dispatchHoverEvent(MotionEvent event) {
5723        //noinspection SimplifiableIfStatement
5724        ListenerInfo li = mListenerInfo;
5725        if (li != null && li.mOnHoverListener != null
5726                && (mViewFlags & ENABLED_MASK) == ENABLED
5727                && li.mOnHoverListener.onHover(this, event)) {
5728            return true;
5729        }
5730
5731        return onHoverEvent(event);
5732    }
5733
5734    /**
5735     * Returns true if the view has a child to which it has recently sent
5736     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5737     * it does not have a hovered child, then it must be the innermost hovered view.
5738     * @hide
5739     */
5740    protected boolean hasHoveredChild() {
5741        return false;
5742    }
5743
5744    /**
5745     * Dispatch a generic motion event to the view under the first pointer.
5746     * <p>
5747     * Do not call this method directly.
5748     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5749     * </p>
5750     *
5751     * @param event The motion event to be dispatched.
5752     * @return True if the event was handled by the view, false otherwise.
5753     */
5754    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5755        return false;
5756    }
5757
5758    /**
5759     * Dispatch a generic motion event to the currently focused view.
5760     * <p>
5761     * Do not call this method directly.
5762     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5763     * </p>
5764     *
5765     * @param event The motion event to be dispatched.
5766     * @return True if the event was handled by the view, false otherwise.
5767     */
5768    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5769        return false;
5770    }
5771
5772    /**
5773     * Dispatch a pointer event.
5774     * <p>
5775     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5776     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5777     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5778     * and should not be expected to handle other pointing device features.
5779     * </p>
5780     *
5781     * @param event The motion event to be dispatched.
5782     * @return True if the event was handled by the view, false otherwise.
5783     * @hide
5784     */
5785    public final boolean dispatchPointerEvent(MotionEvent event) {
5786        if (event.isTouchEvent()) {
5787            return dispatchTouchEvent(event);
5788        } else {
5789            return dispatchGenericMotionEvent(event);
5790        }
5791    }
5792
5793    /**
5794     * Called when the window containing this view gains or loses window focus.
5795     * ViewGroups should override to route to their children.
5796     *
5797     * @param hasFocus True if the window containing this view now has focus,
5798     *        false otherwise.
5799     */
5800    public void dispatchWindowFocusChanged(boolean hasFocus) {
5801        onWindowFocusChanged(hasFocus);
5802    }
5803
5804    /**
5805     * Called when the window containing this view gains or loses focus.  Note
5806     * that this is separate from view focus: to receive key events, both
5807     * your view and its window must have focus.  If a window is displayed
5808     * on top of yours that takes input focus, then your own window will lose
5809     * focus but the view focus will remain unchanged.
5810     *
5811     * @param hasWindowFocus True if the window containing this view now has
5812     *        focus, false otherwise.
5813     */
5814    public void onWindowFocusChanged(boolean hasWindowFocus) {
5815        InputMethodManager imm = InputMethodManager.peekInstance();
5816        if (!hasWindowFocus) {
5817            if (isPressed()) {
5818                setPressed(false);
5819            }
5820            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5821                imm.focusOut(this);
5822            }
5823            removeLongPressCallback();
5824            removeTapCallback();
5825            onFocusLost();
5826        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5827            imm.focusIn(this);
5828        }
5829        refreshDrawableState();
5830    }
5831
5832    /**
5833     * Returns true if this view is in a window that currently has window focus.
5834     * Note that this is not the same as the view itself having focus.
5835     *
5836     * @return True if this view is in a window that currently has window focus.
5837     */
5838    public boolean hasWindowFocus() {
5839        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5840    }
5841
5842    /**
5843     * Dispatch a view visibility change down the view hierarchy.
5844     * ViewGroups should override to route to their children.
5845     * @param changedView The view whose visibility changed. Could be 'this' or
5846     * an ancestor view.
5847     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5848     * {@link #INVISIBLE} or {@link #GONE}.
5849     */
5850    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5851        onVisibilityChanged(changedView, visibility);
5852    }
5853
5854    /**
5855     * Called when the visibility of the view or an ancestor of the view is changed.
5856     * @param changedView The view whose visibility changed. Could be 'this' or
5857     * an ancestor view.
5858     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5859     * {@link #INVISIBLE} or {@link #GONE}.
5860     */
5861    protected void onVisibilityChanged(View changedView, int visibility) {
5862        if (visibility == VISIBLE) {
5863            if (mAttachInfo != null) {
5864                initialAwakenScrollBars();
5865            } else {
5866                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5867            }
5868        }
5869    }
5870
5871    /**
5872     * Dispatch a hint about whether this view is displayed. For instance, when
5873     * a View moves out of the screen, it might receives a display hint indicating
5874     * the view is not displayed. Applications should not <em>rely</em> on this hint
5875     * as there is no guarantee that they will receive one.
5876     *
5877     * @param hint A hint about whether or not this view is displayed:
5878     * {@link #VISIBLE} or {@link #INVISIBLE}.
5879     */
5880    public void dispatchDisplayHint(int hint) {
5881        onDisplayHint(hint);
5882    }
5883
5884    /**
5885     * Gives this view a hint about whether is displayed or not. For instance, when
5886     * a View moves out of the screen, it might receives a display hint indicating
5887     * the view is not displayed. Applications should not <em>rely</em> on this hint
5888     * as there is no guarantee that they will receive one.
5889     *
5890     * @param hint A hint about whether or not this view is displayed:
5891     * {@link #VISIBLE} or {@link #INVISIBLE}.
5892     */
5893    protected void onDisplayHint(int hint) {
5894    }
5895
5896    /**
5897     * Dispatch a window visibility change down the view hierarchy.
5898     * ViewGroups should override to route to their children.
5899     *
5900     * @param visibility The new visibility of the window.
5901     *
5902     * @see #onWindowVisibilityChanged(int)
5903     */
5904    public void dispatchWindowVisibilityChanged(int visibility) {
5905        onWindowVisibilityChanged(visibility);
5906    }
5907
5908    /**
5909     * Called when the window containing has change its visibility
5910     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5911     * that this tells you whether or not your window is being made visible
5912     * to the window manager; this does <em>not</em> tell you whether or not
5913     * your window is obscured by other windows on the screen, even if it
5914     * is itself visible.
5915     *
5916     * @param visibility The new visibility of the window.
5917     */
5918    protected void onWindowVisibilityChanged(int visibility) {
5919        if (visibility == VISIBLE) {
5920            initialAwakenScrollBars();
5921        }
5922    }
5923
5924    /**
5925     * Returns the current visibility of the window this view is attached to
5926     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
5927     *
5928     * @return Returns the current visibility of the view's window.
5929     */
5930    public int getWindowVisibility() {
5931        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
5932    }
5933
5934    /**
5935     * Retrieve the overall visible display size in which the window this view is
5936     * attached to has been positioned in.  This takes into account screen
5937     * decorations above the window, for both cases where the window itself
5938     * is being position inside of them or the window is being placed under
5939     * then and covered insets are used for the window to position its content
5940     * inside.  In effect, this tells you the available area where content can
5941     * be placed and remain visible to users.
5942     *
5943     * <p>This function requires an IPC back to the window manager to retrieve
5944     * the requested information, so should not be used in performance critical
5945     * code like drawing.
5946     *
5947     * @param outRect Filled in with the visible display frame.  If the view
5948     * is not attached to a window, this is simply the raw display size.
5949     */
5950    public void getWindowVisibleDisplayFrame(Rect outRect) {
5951        if (mAttachInfo != null) {
5952            try {
5953                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
5954            } catch (RemoteException e) {
5955                return;
5956            }
5957            // XXX This is really broken, and probably all needs to be done
5958            // in the window manager, and we need to know more about whether
5959            // we want the area behind or in front of the IME.
5960            final Rect insets = mAttachInfo.mVisibleInsets;
5961            outRect.left += insets.left;
5962            outRect.top += insets.top;
5963            outRect.right -= insets.right;
5964            outRect.bottom -= insets.bottom;
5965            return;
5966        }
5967        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
5968        d.getRectSize(outRect);
5969    }
5970
5971    /**
5972     * Dispatch a notification about a resource configuration change down
5973     * the view hierarchy.
5974     * ViewGroups should override to route to their children.
5975     *
5976     * @param newConfig The new resource configuration.
5977     *
5978     * @see #onConfigurationChanged(android.content.res.Configuration)
5979     */
5980    public void dispatchConfigurationChanged(Configuration newConfig) {
5981        onConfigurationChanged(newConfig);
5982    }
5983
5984    /**
5985     * Called when the current configuration of the resources being used
5986     * by the application have changed.  You can use this to decide when
5987     * to reload resources that can changed based on orientation and other
5988     * configuration characterstics.  You only need to use this if you are
5989     * not relying on the normal {@link android.app.Activity} mechanism of
5990     * recreating the activity instance upon a configuration change.
5991     *
5992     * @param newConfig The new resource configuration.
5993     */
5994    protected void onConfigurationChanged(Configuration newConfig) {
5995    }
5996
5997    /**
5998     * Private function to aggregate all per-view attributes in to the view
5999     * root.
6000     */
6001    void dispatchCollectViewAttributes(int visibility) {
6002        performCollectViewAttributes(visibility);
6003    }
6004
6005    void performCollectViewAttributes(int visibility) {
6006        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
6007            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6008                mAttachInfo.mKeepScreenOn = true;
6009            }
6010            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6011            ListenerInfo li = mListenerInfo;
6012            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6013                mAttachInfo.mHasSystemUiListeners = true;
6014            }
6015        }
6016    }
6017
6018    void needGlobalAttributesUpdate(boolean force) {
6019        final AttachInfo ai = mAttachInfo;
6020        if (ai != null) {
6021            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6022                    || ai.mHasSystemUiListeners) {
6023                ai.mRecomputeGlobalAttributes = true;
6024            }
6025        }
6026    }
6027
6028    /**
6029     * Returns whether the device is currently in touch mode.  Touch mode is entered
6030     * once the user begins interacting with the device by touch, and affects various
6031     * things like whether focus is always visible to the user.
6032     *
6033     * @return Whether the device is in touch mode.
6034     */
6035    @ViewDebug.ExportedProperty
6036    public boolean isInTouchMode() {
6037        if (mAttachInfo != null) {
6038            return mAttachInfo.mInTouchMode;
6039        } else {
6040            return ViewRootImpl.isInTouchMode();
6041        }
6042    }
6043
6044    /**
6045     * Returns the context the view is running in, through which it can
6046     * access the current theme, resources, etc.
6047     *
6048     * @return The view's Context.
6049     */
6050    @ViewDebug.CapturedViewProperty
6051    public final Context getContext() {
6052        return mContext;
6053    }
6054
6055    /**
6056     * Handle a key event before it is processed by any input method
6057     * associated with the view hierarchy.  This can be used to intercept
6058     * key events in special situations before the IME consumes them; a
6059     * typical example would be handling the BACK key to update the application's
6060     * UI instead of allowing the IME to see it and close itself.
6061     *
6062     * @param keyCode The value in event.getKeyCode().
6063     * @param event Description of the key event.
6064     * @return If you handled the event, return true. If you want to allow the
6065     *         event to be handled by the next receiver, return false.
6066     */
6067    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6068        return false;
6069    }
6070
6071    /**
6072     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6073     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6074     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6075     * is released, if the view is enabled and clickable.
6076     *
6077     * @param keyCode A key code that represents the button pressed, from
6078     *                {@link android.view.KeyEvent}.
6079     * @param event   The KeyEvent object that defines the button action.
6080     */
6081    public boolean onKeyDown(int keyCode, KeyEvent event) {
6082        boolean result = false;
6083
6084        switch (keyCode) {
6085            case KeyEvent.KEYCODE_DPAD_CENTER:
6086            case KeyEvent.KEYCODE_ENTER: {
6087                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6088                    return true;
6089                }
6090                // Long clickable items don't necessarily have to be clickable
6091                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6092                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6093                        (event.getRepeatCount() == 0)) {
6094                    setPressed(true);
6095                    checkForLongClick(0);
6096                    return true;
6097                }
6098                break;
6099            }
6100        }
6101        return result;
6102    }
6103
6104    /**
6105     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6106     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6107     * the event).
6108     */
6109    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6110        return false;
6111    }
6112
6113    /**
6114     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6115     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6116     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6117     * {@link KeyEvent#KEYCODE_ENTER} is released.
6118     *
6119     * @param keyCode A key code that represents the button pressed, from
6120     *                {@link android.view.KeyEvent}.
6121     * @param event   The KeyEvent object that defines the button action.
6122     */
6123    public boolean onKeyUp(int keyCode, KeyEvent event) {
6124        boolean result = false;
6125
6126        switch (keyCode) {
6127            case KeyEvent.KEYCODE_DPAD_CENTER:
6128            case KeyEvent.KEYCODE_ENTER: {
6129                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6130                    return true;
6131                }
6132                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6133                    setPressed(false);
6134
6135                    if (!mHasPerformedLongPress) {
6136                        // This is a tap, so remove the longpress check
6137                        removeLongPressCallback();
6138
6139                        result = performClick();
6140                    }
6141                }
6142                break;
6143            }
6144        }
6145        return result;
6146    }
6147
6148    /**
6149     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6150     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6151     * the event).
6152     *
6153     * @param keyCode     A key code that represents the button pressed, from
6154     *                    {@link android.view.KeyEvent}.
6155     * @param repeatCount The number of times the action was made.
6156     * @param event       The KeyEvent object that defines the button action.
6157     */
6158    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6159        return false;
6160    }
6161
6162    /**
6163     * Called on the focused view when a key shortcut event is not handled.
6164     * Override this method to implement local key shortcuts for the View.
6165     * Key shortcuts can also be implemented by setting the
6166     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6167     *
6168     * @param keyCode The value in event.getKeyCode().
6169     * @param event Description of the key event.
6170     * @return If you handled the event, return true. If you want to allow the
6171     *         event to be handled by the next receiver, return false.
6172     */
6173    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6174        return false;
6175    }
6176
6177    /**
6178     * Check whether the called view is a text editor, in which case it
6179     * would make sense to automatically display a soft input window for
6180     * it.  Subclasses should override this if they implement
6181     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6182     * a call on that method would return a non-null InputConnection, and
6183     * they are really a first-class editor that the user would normally
6184     * start typing on when the go into a window containing your view.
6185     *
6186     * <p>The default implementation always returns false.  This does
6187     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6188     * will not be called or the user can not otherwise perform edits on your
6189     * view; it is just a hint to the system that this is not the primary
6190     * purpose of this view.
6191     *
6192     * @return Returns true if this view is a text editor, else false.
6193     */
6194    public boolean onCheckIsTextEditor() {
6195        return false;
6196    }
6197
6198    /**
6199     * Create a new InputConnection for an InputMethod to interact
6200     * with the view.  The default implementation returns null, since it doesn't
6201     * support input methods.  You can override this to implement such support.
6202     * This is only needed for views that take focus and text input.
6203     *
6204     * <p>When implementing this, you probably also want to implement
6205     * {@link #onCheckIsTextEditor()} to indicate you will return a
6206     * non-null InputConnection.
6207     *
6208     * @param outAttrs Fill in with attribute information about the connection.
6209     */
6210    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6211        return null;
6212    }
6213
6214    /**
6215     * Called by the {@link android.view.inputmethod.InputMethodManager}
6216     * when a view who is not the current
6217     * input connection target is trying to make a call on the manager.  The
6218     * default implementation returns false; you can override this to return
6219     * true for certain views if you are performing InputConnection proxying
6220     * to them.
6221     * @param view The View that is making the InputMethodManager call.
6222     * @return Return true to allow the call, false to reject.
6223     */
6224    public boolean checkInputConnectionProxy(View view) {
6225        return false;
6226    }
6227
6228    /**
6229     * Show the context menu for this view. It is not safe to hold on to the
6230     * menu after returning from this method.
6231     *
6232     * You should normally not overload this method. Overload
6233     * {@link #onCreateContextMenu(ContextMenu)} or define an
6234     * {@link OnCreateContextMenuListener} to add items to the context menu.
6235     *
6236     * @param menu The context menu to populate
6237     */
6238    public void createContextMenu(ContextMenu menu) {
6239        ContextMenuInfo menuInfo = getContextMenuInfo();
6240
6241        // Sets the current menu info so all items added to menu will have
6242        // my extra info set.
6243        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6244
6245        onCreateContextMenu(menu);
6246        ListenerInfo li = mListenerInfo;
6247        if (li != null && li.mOnCreateContextMenuListener != null) {
6248            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6249        }
6250
6251        // Clear the extra information so subsequent items that aren't mine don't
6252        // have my extra info.
6253        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6254
6255        if (mParent != null) {
6256            mParent.createContextMenu(menu);
6257        }
6258    }
6259
6260    /**
6261     * Views should implement this if they have extra information to associate
6262     * with the context menu. The return result is supplied as a parameter to
6263     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6264     * callback.
6265     *
6266     * @return Extra information about the item for which the context menu
6267     *         should be shown. This information will vary across different
6268     *         subclasses of View.
6269     */
6270    protected ContextMenuInfo getContextMenuInfo() {
6271        return null;
6272    }
6273
6274    /**
6275     * Views should implement this if the view itself is going to add items to
6276     * the context menu.
6277     *
6278     * @param menu the context menu to populate
6279     */
6280    protected void onCreateContextMenu(ContextMenu menu) {
6281    }
6282
6283    /**
6284     * Implement this method to handle trackball motion events.  The
6285     * <em>relative</em> movement of the trackball since the last event
6286     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6287     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6288     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6289     * they will often be fractional values, representing the more fine-grained
6290     * movement information available from a trackball).
6291     *
6292     * @param event The motion event.
6293     * @return True if the event was handled, false otherwise.
6294     */
6295    public boolean onTrackballEvent(MotionEvent event) {
6296        return false;
6297    }
6298
6299    /**
6300     * Implement this method to handle generic motion events.
6301     * <p>
6302     * Generic motion events describe joystick movements, mouse hovers, track pad
6303     * touches, scroll wheel movements and other input events.  The
6304     * {@link MotionEvent#getSource() source} of the motion event specifies
6305     * the class of input that was received.  Implementations of this method
6306     * must examine the bits in the source before processing the event.
6307     * The following code example shows how this is done.
6308     * </p><p>
6309     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6310     * are delivered to the view under the pointer.  All other generic motion events are
6311     * delivered to the focused view.
6312     * </p>
6313     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6314     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6315     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6316     *             // process the joystick movement...
6317     *             return true;
6318     *         }
6319     *     }
6320     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6321     *         switch (event.getAction()) {
6322     *             case MotionEvent.ACTION_HOVER_MOVE:
6323     *                 // process the mouse hover movement...
6324     *                 return true;
6325     *             case MotionEvent.ACTION_SCROLL:
6326     *                 // process the scroll wheel movement...
6327     *                 return true;
6328     *         }
6329     *     }
6330     *     return super.onGenericMotionEvent(event);
6331     * }</pre>
6332     *
6333     * @param event The generic motion event being processed.
6334     * @return True if the event was handled, false otherwise.
6335     */
6336    public boolean onGenericMotionEvent(MotionEvent event) {
6337        return false;
6338    }
6339
6340    /**
6341     * Implement this method to handle hover events.
6342     * <p>
6343     * This method is called whenever a pointer is hovering into, over, or out of the
6344     * bounds of a view and the view is not currently being touched.
6345     * Hover events are represented as pointer events with action
6346     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6347     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6348     * </p>
6349     * <ul>
6350     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6351     * when the pointer enters the bounds of the view.</li>
6352     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6353     * when the pointer has already entered the bounds of the view and has moved.</li>
6354     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6355     * when the pointer has exited the bounds of the view or when the pointer is
6356     * about to go down due to a button click, tap, or similar user action that
6357     * causes the view to be touched.</li>
6358     * </ul>
6359     * <p>
6360     * The view should implement this method to return true to indicate that it is
6361     * handling the hover event, such as by changing its drawable state.
6362     * </p><p>
6363     * The default implementation calls {@link #setHovered} to update the hovered state
6364     * of the view when a hover enter or hover exit event is received, if the view
6365     * is enabled and is clickable.  The default implementation also sends hover
6366     * accessibility events.
6367     * </p>
6368     *
6369     * @param event The motion event that describes the hover.
6370     * @return True if the view handled the hover event.
6371     *
6372     * @see #isHovered
6373     * @see #setHovered
6374     * @see #onHoverChanged
6375     */
6376    public boolean onHoverEvent(MotionEvent event) {
6377        // The root view may receive hover (or touch) events that are outside the bounds of
6378        // the window.  This code ensures that we only send accessibility events for
6379        // hovers that are actually within the bounds of the root view.
6380        final int action = event.getAction();
6381        if (!mSendingHoverAccessibilityEvents) {
6382            if ((action == MotionEvent.ACTION_HOVER_ENTER
6383                    || action == MotionEvent.ACTION_HOVER_MOVE)
6384                    && !hasHoveredChild()
6385                    && pointInView(event.getX(), event.getY())) {
6386                mSendingHoverAccessibilityEvents = true;
6387                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6388            }
6389        } else {
6390            if (action == MotionEvent.ACTION_HOVER_EXIT
6391                    || (action == MotionEvent.ACTION_HOVER_MOVE
6392                            && !pointInView(event.getX(), event.getY()))) {
6393                mSendingHoverAccessibilityEvents = false;
6394                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6395            }
6396        }
6397
6398        if (isHoverable()) {
6399            switch (action) {
6400                case MotionEvent.ACTION_HOVER_ENTER:
6401                    setHovered(true);
6402                    break;
6403                case MotionEvent.ACTION_HOVER_EXIT:
6404                    setHovered(false);
6405                    break;
6406            }
6407
6408            // Dispatch the event to onGenericMotionEvent before returning true.
6409            // This is to provide compatibility with existing applications that
6410            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6411            // break because of the new default handling for hoverable views
6412            // in onHoverEvent.
6413            // Note that onGenericMotionEvent will be called by default when
6414            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6415            dispatchGenericMotionEventInternal(event);
6416            return true;
6417        }
6418        return false;
6419    }
6420
6421    /**
6422     * Returns true if the view should handle {@link #onHoverEvent}
6423     * by calling {@link #setHovered} to change its hovered state.
6424     *
6425     * @return True if the view is hoverable.
6426     */
6427    private boolean isHoverable() {
6428        final int viewFlags = mViewFlags;
6429        //noinspection SimplifiableIfStatement
6430        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6431            return false;
6432        }
6433
6434        return (viewFlags & CLICKABLE) == CLICKABLE
6435                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6436    }
6437
6438    /**
6439     * Returns true if the view is currently hovered.
6440     *
6441     * @return True if the view is currently hovered.
6442     *
6443     * @see #setHovered
6444     * @see #onHoverChanged
6445     */
6446    @ViewDebug.ExportedProperty
6447    public boolean isHovered() {
6448        return (mPrivateFlags & HOVERED) != 0;
6449    }
6450
6451    /**
6452     * Sets whether the view is currently hovered.
6453     * <p>
6454     * Calling this method also changes the drawable state of the view.  This
6455     * enables the view to react to hover by using different drawable resources
6456     * to change its appearance.
6457     * </p><p>
6458     * The {@link #onHoverChanged} method is called when the hovered state changes.
6459     * </p>
6460     *
6461     * @param hovered True if the view is hovered.
6462     *
6463     * @see #isHovered
6464     * @see #onHoverChanged
6465     */
6466    public void setHovered(boolean hovered) {
6467        if (hovered) {
6468            if ((mPrivateFlags & HOVERED) == 0) {
6469                mPrivateFlags |= HOVERED;
6470                refreshDrawableState();
6471                onHoverChanged(true);
6472            }
6473        } else {
6474            if ((mPrivateFlags & HOVERED) != 0) {
6475                mPrivateFlags &= ~HOVERED;
6476                refreshDrawableState();
6477                onHoverChanged(false);
6478            }
6479        }
6480    }
6481
6482    /**
6483     * Implement this method to handle hover state changes.
6484     * <p>
6485     * This method is called whenever the hover state changes as a result of a
6486     * call to {@link #setHovered}.
6487     * </p>
6488     *
6489     * @param hovered The current hover state, as returned by {@link #isHovered}.
6490     *
6491     * @see #isHovered
6492     * @see #setHovered
6493     */
6494    public void onHoverChanged(boolean hovered) {
6495    }
6496
6497    /**
6498     * Implement this method to handle touch screen motion events.
6499     *
6500     * @param event The motion event.
6501     * @return True if the event was handled, false otherwise.
6502     */
6503    public boolean onTouchEvent(MotionEvent event) {
6504        final int viewFlags = mViewFlags;
6505
6506        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6507            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6508                mPrivateFlags &= ~PRESSED;
6509                refreshDrawableState();
6510            }
6511            // A disabled view that is clickable still consumes the touch
6512            // events, it just doesn't respond to them.
6513            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6514                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6515        }
6516
6517        if (mTouchDelegate != null) {
6518            if (mTouchDelegate.onTouchEvent(event)) {
6519                return true;
6520            }
6521        }
6522
6523        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6524                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6525            switch (event.getAction()) {
6526                case MotionEvent.ACTION_UP:
6527                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6528                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6529                        // take focus if we don't have it already and we should in
6530                        // touch mode.
6531                        boolean focusTaken = false;
6532                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6533                            focusTaken = requestFocus();
6534                        }
6535
6536                        if (prepressed) {
6537                            // The button is being released before we actually
6538                            // showed it as pressed.  Make it show the pressed
6539                            // state now (before scheduling the click) to ensure
6540                            // the user sees it.
6541                            mPrivateFlags |= PRESSED;
6542                            refreshDrawableState();
6543                       }
6544
6545                        if (!mHasPerformedLongPress) {
6546                            // This is a tap, so remove the longpress check
6547                            removeLongPressCallback();
6548
6549                            // Only perform take click actions if we were in the pressed state
6550                            if (!focusTaken) {
6551                                // Use a Runnable and post this rather than calling
6552                                // performClick directly. This lets other visual state
6553                                // of the view update before click actions start.
6554                                if (mPerformClick == null) {
6555                                    mPerformClick = new PerformClick();
6556                                }
6557                                if (!post(mPerformClick)) {
6558                                    performClick();
6559                                }
6560                            }
6561                        }
6562
6563                        if (mUnsetPressedState == null) {
6564                            mUnsetPressedState = new UnsetPressedState();
6565                        }
6566
6567                        if (prepressed) {
6568                            postDelayed(mUnsetPressedState,
6569                                    ViewConfiguration.getPressedStateDuration());
6570                        } else if (!post(mUnsetPressedState)) {
6571                            // If the post failed, unpress right now
6572                            mUnsetPressedState.run();
6573                        }
6574                        removeTapCallback();
6575                    }
6576                    break;
6577
6578                case MotionEvent.ACTION_DOWN:
6579                    mHasPerformedLongPress = false;
6580
6581                    if (performButtonActionOnTouchDown(event)) {
6582                        break;
6583                    }
6584
6585                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6586                    boolean isInScrollingContainer = isInScrollingContainer();
6587
6588                    // For views inside a scrolling container, delay the pressed feedback for
6589                    // a short period in case this is a scroll.
6590                    if (isInScrollingContainer) {
6591                        mPrivateFlags |= PREPRESSED;
6592                        if (mPendingCheckForTap == null) {
6593                            mPendingCheckForTap = new CheckForTap();
6594                        }
6595                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6596                    } else {
6597                        // Not inside a scrolling container, so show the feedback right away
6598                        mPrivateFlags |= PRESSED;
6599                        refreshDrawableState();
6600                        checkForLongClick(0);
6601                    }
6602                    break;
6603
6604                case MotionEvent.ACTION_CANCEL:
6605                    mPrivateFlags &= ~PRESSED;
6606                    refreshDrawableState();
6607                    removeTapCallback();
6608                    break;
6609
6610                case MotionEvent.ACTION_MOVE:
6611                    final int x = (int) event.getX();
6612                    final int y = (int) event.getY();
6613
6614                    // Be lenient about moving outside of buttons
6615                    if (!pointInView(x, y, mTouchSlop)) {
6616                        // Outside button
6617                        removeTapCallback();
6618                        if ((mPrivateFlags & PRESSED) != 0) {
6619                            // Remove any future long press/tap checks
6620                            removeLongPressCallback();
6621
6622                            // Need to switch from pressed to not pressed
6623                            mPrivateFlags &= ~PRESSED;
6624                            refreshDrawableState();
6625                        }
6626                    }
6627                    break;
6628            }
6629            return true;
6630        }
6631
6632        return false;
6633    }
6634
6635    /**
6636     * @hide
6637     */
6638    public boolean isInScrollingContainer() {
6639        ViewParent p = getParent();
6640        while (p != null && p instanceof ViewGroup) {
6641            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6642                return true;
6643            }
6644            p = p.getParent();
6645        }
6646        return false;
6647    }
6648
6649    /**
6650     * Remove the longpress detection timer.
6651     */
6652    private void removeLongPressCallback() {
6653        if (mPendingCheckForLongPress != null) {
6654          removeCallbacks(mPendingCheckForLongPress);
6655        }
6656    }
6657
6658    /**
6659     * Remove the pending click action
6660     */
6661    private void removePerformClickCallback() {
6662        if (mPerformClick != null) {
6663            removeCallbacks(mPerformClick);
6664        }
6665    }
6666
6667    /**
6668     * Remove the prepress detection timer.
6669     */
6670    private void removeUnsetPressCallback() {
6671        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6672            setPressed(false);
6673            removeCallbacks(mUnsetPressedState);
6674        }
6675    }
6676
6677    /**
6678     * Remove the tap detection timer.
6679     */
6680    private void removeTapCallback() {
6681        if (mPendingCheckForTap != null) {
6682            mPrivateFlags &= ~PREPRESSED;
6683            removeCallbacks(mPendingCheckForTap);
6684        }
6685    }
6686
6687    /**
6688     * Cancels a pending long press.  Your subclass can use this if you
6689     * want the context menu to come up if the user presses and holds
6690     * at the same place, but you don't want it to come up if they press
6691     * and then move around enough to cause scrolling.
6692     */
6693    public void cancelLongPress() {
6694        removeLongPressCallback();
6695
6696        /*
6697         * The prepressed state handled by the tap callback is a display
6698         * construct, but the tap callback will post a long press callback
6699         * less its own timeout. Remove it here.
6700         */
6701        removeTapCallback();
6702    }
6703
6704    /**
6705     * Remove the pending callback for sending a
6706     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6707     */
6708    private void removeSendViewScrolledAccessibilityEventCallback() {
6709        if (mSendViewScrolledAccessibilityEvent != null) {
6710            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6711        }
6712    }
6713
6714    /**
6715     * Sets the TouchDelegate for this View.
6716     */
6717    public void setTouchDelegate(TouchDelegate delegate) {
6718        mTouchDelegate = delegate;
6719    }
6720
6721    /**
6722     * Gets the TouchDelegate for this View.
6723     */
6724    public TouchDelegate getTouchDelegate() {
6725        return mTouchDelegate;
6726    }
6727
6728    /**
6729     * Set flags controlling behavior of this view.
6730     *
6731     * @param flags Constant indicating the value which should be set
6732     * @param mask Constant indicating the bit range that should be changed
6733     */
6734    void setFlags(int flags, int mask) {
6735        int old = mViewFlags;
6736        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6737
6738        int changed = mViewFlags ^ old;
6739        if (changed == 0) {
6740            return;
6741        }
6742        int privateFlags = mPrivateFlags;
6743
6744        /* Check if the FOCUSABLE bit has changed */
6745        if (((changed & FOCUSABLE_MASK) != 0) &&
6746                ((privateFlags & HAS_BOUNDS) !=0)) {
6747            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6748                    && ((privateFlags & FOCUSED) != 0)) {
6749                /* Give up focus if we are no longer focusable */
6750                clearFocus();
6751            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6752                    && ((privateFlags & FOCUSED) == 0)) {
6753                /*
6754                 * Tell the view system that we are now available to take focus
6755                 * if no one else already has it.
6756                 */
6757                if (mParent != null) mParent.focusableViewAvailable(this);
6758            }
6759        }
6760
6761        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6762            if ((changed & VISIBILITY_MASK) != 0) {
6763                /*
6764                 * If this view is becoming visible, invalidate it in case it changed while
6765                 * it was not visible. Marking it drawn ensures that the invalidation will
6766                 * go through.
6767                 */
6768                mPrivateFlags |= DRAWN;
6769                invalidate(true);
6770
6771                needGlobalAttributesUpdate(true);
6772
6773                // a view becoming visible is worth notifying the parent
6774                // about in case nothing has focus.  even if this specific view
6775                // isn't focusable, it may contain something that is, so let
6776                // the root view try to give this focus if nothing else does.
6777                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6778                    mParent.focusableViewAvailable(this);
6779                }
6780            }
6781        }
6782
6783        /* Check if the GONE bit has changed */
6784        if ((changed & GONE) != 0) {
6785            needGlobalAttributesUpdate(false);
6786            requestLayout();
6787
6788            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6789                if (hasFocus()) clearFocus();
6790                destroyDrawingCache();
6791                if (mParent instanceof View) {
6792                    // GONE views noop invalidation, so invalidate the parent
6793                    ((View) mParent).invalidate(true);
6794                }
6795                // Mark the view drawn to ensure that it gets invalidated properly the next
6796                // time it is visible and gets invalidated
6797                mPrivateFlags |= DRAWN;
6798            }
6799            if (mAttachInfo != null) {
6800                mAttachInfo.mViewVisibilityChanged = true;
6801            }
6802        }
6803
6804        /* Check if the VISIBLE bit has changed */
6805        if ((changed & INVISIBLE) != 0) {
6806            needGlobalAttributesUpdate(false);
6807            /*
6808             * If this view is becoming invisible, set the DRAWN flag so that
6809             * the next invalidate() will not be skipped.
6810             */
6811            mPrivateFlags |= DRAWN;
6812
6813            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6814                // root view becoming invisible shouldn't clear focus
6815                if (getRootView() != this) {
6816                    clearFocus();
6817                }
6818            }
6819            if (mAttachInfo != null) {
6820                mAttachInfo.mViewVisibilityChanged = true;
6821            }
6822        }
6823
6824        if ((changed & VISIBILITY_MASK) != 0) {
6825            if (mParent instanceof ViewGroup) {
6826                ((ViewGroup) mParent).onChildVisibilityChanged(this,
6827                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
6828                ((View) mParent).invalidate(true);
6829            } else if (mParent != null) {
6830                mParent.invalidateChild(this, null);
6831            }
6832            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6833        }
6834
6835        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6836            destroyDrawingCache();
6837        }
6838
6839        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6840            destroyDrawingCache();
6841            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6842            invalidateParentCaches();
6843        }
6844
6845        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6846            destroyDrawingCache();
6847            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6848        }
6849
6850        if ((changed & DRAW_MASK) != 0) {
6851            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6852                if (mBGDrawable != null) {
6853                    mPrivateFlags &= ~SKIP_DRAW;
6854                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6855                } else {
6856                    mPrivateFlags |= SKIP_DRAW;
6857                }
6858            } else {
6859                mPrivateFlags &= ~SKIP_DRAW;
6860            }
6861            requestLayout();
6862            invalidate(true);
6863        }
6864
6865        if ((changed & KEEP_SCREEN_ON) != 0) {
6866            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6867                mParent.recomputeViewAttributes(this);
6868            }
6869        }
6870
6871        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6872            requestLayout();
6873        }
6874    }
6875
6876    /**
6877     * Change the view's z order in the tree, so it's on top of other sibling
6878     * views
6879     */
6880    public void bringToFront() {
6881        if (mParent != null) {
6882            mParent.bringChildToFront(this);
6883        }
6884    }
6885
6886    /**
6887     * This is called in response to an internal scroll in this view (i.e., the
6888     * view scrolled its own contents). This is typically as a result of
6889     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6890     * called.
6891     *
6892     * @param l Current horizontal scroll origin.
6893     * @param t Current vertical scroll origin.
6894     * @param oldl Previous horizontal scroll origin.
6895     * @param oldt Previous vertical scroll origin.
6896     */
6897    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6898        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6899            postSendViewScrolledAccessibilityEventCallback();
6900        }
6901
6902        mBackgroundSizeChanged = true;
6903
6904        final AttachInfo ai = mAttachInfo;
6905        if (ai != null) {
6906            ai.mViewScrollChanged = true;
6907        }
6908    }
6909
6910    /**
6911     * Interface definition for a callback to be invoked when the layout bounds of a view
6912     * changes due to layout processing.
6913     */
6914    public interface OnLayoutChangeListener {
6915        /**
6916         * Called when the focus state of a view has changed.
6917         *
6918         * @param v The view whose state has changed.
6919         * @param left The new value of the view's left property.
6920         * @param top The new value of the view's top property.
6921         * @param right The new value of the view's right property.
6922         * @param bottom The new value of the view's bottom property.
6923         * @param oldLeft The previous value of the view's left property.
6924         * @param oldTop The previous value of the view's top property.
6925         * @param oldRight The previous value of the view's right property.
6926         * @param oldBottom The previous value of the view's bottom property.
6927         */
6928        void onLayoutChange(View v, int left, int top, int right, int bottom,
6929            int oldLeft, int oldTop, int oldRight, int oldBottom);
6930    }
6931
6932    /**
6933     * This is called during layout when the size of this view has changed. If
6934     * you were just added to the view hierarchy, you're called with the old
6935     * values of 0.
6936     *
6937     * @param w Current width of this view.
6938     * @param h Current height of this view.
6939     * @param oldw Old width of this view.
6940     * @param oldh Old height of this view.
6941     */
6942    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
6943    }
6944
6945    /**
6946     * Called by draw to draw the child views. This may be overridden
6947     * by derived classes to gain control just before its children are drawn
6948     * (but after its own view has been drawn).
6949     * @param canvas the canvas on which to draw the view
6950     */
6951    protected void dispatchDraw(Canvas canvas) {
6952    }
6953
6954    /**
6955     * Gets the parent of this view. Note that the parent is a
6956     * ViewParent and not necessarily a View.
6957     *
6958     * @return Parent of this view.
6959     */
6960    public final ViewParent getParent() {
6961        return mParent;
6962    }
6963
6964    /**
6965     * Set the horizontal scrolled position of your view. This will cause a call to
6966     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6967     * invalidated.
6968     * @param value the x position to scroll to
6969     */
6970    public void setScrollX(int value) {
6971        scrollTo(value, mScrollY);
6972    }
6973
6974    /**
6975     * Set the vertical scrolled position of your view. This will cause a call to
6976     * {@link #onScrollChanged(int, int, int, int)} and the view will be
6977     * invalidated.
6978     * @param value the y position to scroll to
6979     */
6980    public void setScrollY(int value) {
6981        scrollTo(mScrollX, value);
6982    }
6983
6984    /**
6985     * Return the scrolled left position of this view. This is the left edge of
6986     * the displayed part of your view. You do not need to draw any pixels
6987     * farther left, since those are outside of the frame of your view on
6988     * screen.
6989     *
6990     * @return The left edge of the displayed part of your view, in pixels.
6991     */
6992    public final int getScrollX() {
6993        return mScrollX;
6994    }
6995
6996    /**
6997     * Return the scrolled top position of this view. This is the top edge of
6998     * the displayed part of your view. You do not need to draw any pixels above
6999     * it, since those are outside of the frame of your view on screen.
7000     *
7001     * @return The top edge of the displayed part of your view, in pixels.
7002     */
7003    public final int getScrollY() {
7004        return mScrollY;
7005    }
7006
7007    /**
7008     * Return the width of the your view.
7009     *
7010     * @return The width of your view, in pixels.
7011     */
7012    @ViewDebug.ExportedProperty(category = "layout")
7013    public final int getWidth() {
7014        return mRight - mLeft;
7015    }
7016
7017    /**
7018     * Return the height of your view.
7019     *
7020     * @return The height of your view, in pixels.
7021     */
7022    @ViewDebug.ExportedProperty(category = "layout")
7023    public final int getHeight() {
7024        return mBottom - mTop;
7025    }
7026
7027    /**
7028     * Return the visible drawing bounds of your view. Fills in the output
7029     * rectangle with the values from getScrollX(), getScrollY(),
7030     * getWidth(), and getHeight().
7031     *
7032     * @param outRect The (scrolled) drawing bounds of the view.
7033     */
7034    public void getDrawingRect(Rect outRect) {
7035        outRect.left = mScrollX;
7036        outRect.top = mScrollY;
7037        outRect.right = mScrollX + (mRight - mLeft);
7038        outRect.bottom = mScrollY + (mBottom - mTop);
7039    }
7040
7041    /**
7042     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7043     * raw width component (that is the result is masked by
7044     * {@link #MEASURED_SIZE_MASK}).
7045     *
7046     * @return The raw measured width of this view.
7047     */
7048    public final int getMeasuredWidth() {
7049        return mMeasuredWidth & MEASURED_SIZE_MASK;
7050    }
7051
7052    /**
7053     * Return the full width measurement information for this view as computed
7054     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7055     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7056     * This should be used during measurement and layout calculations only. Use
7057     * {@link #getWidth()} to see how wide a view is after layout.
7058     *
7059     * @return The measured width of this view as a bit mask.
7060     */
7061    public final int getMeasuredWidthAndState() {
7062        return mMeasuredWidth;
7063    }
7064
7065    /**
7066     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7067     * raw width component (that is the result is masked by
7068     * {@link #MEASURED_SIZE_MASK}).
7069     *
7070     * @return The raw measured height of this view.
7071     */
7072    public final int getMeasuredHeight() {
7073        return mMeasuredHeight & MEASURED_SIZE_MASK;
7074    }
7075
7076    /**
7077     * Return the full height measurement information for this view as computed
7078     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7079     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7080     * This should be used during measurement and layout calculations only. Use
7081     * {@link #getHeight()} to see how wide a view is after layout.
7082     *
7083     * @return The measured width of this view as a bit mask.
7084     */
7085    public final int getMeasuredHeightAndState() {
7086        return mMeasuredHeight;
7087    }
7088
7089    /**
7090     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7091     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7092     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7093     * and the height component is at the shifted bits
7094     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7095     */
7096    public final int getMeasuredState() {
7097        return (mMeasuredWidth&MEASURED_STATE_MASK)
7098                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7099                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7100    }
7101
7102    /**
7103     * The transform matrix of this view, which is calculated based on the current
7104     * roation, scale, and pivot properties.
7105     *
7106     * @see #getRotation()
7107     * @see #getScaleX()
7108     * @see #getScaleY()
7109     * @see #getPivotX()
7110     * @see #getPivotY()
7111     * @return The current transform matrix for the view
7112     */
7113    public Matrix getMatrix() {
7114        if (mTransformationInfo != null) {
7115            updateMatrix();
7116            return mTransformationInfo.mMatrix;
7117        }
7118        return Matrix.IDENTITY_MATRIX;
7119    }
7120
7121    /**
7122     * Utility function to determine if the value is far enough away from zero to be
7123     * considered non-zero.
7124     * @param value A floating point value to check for zero-ness
7125     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7126     */
7127    private static boolean nonzero(float value) {
7128        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7129    }
7130
7131    /**
7132     * Returns true if the transform matrix is the identity matrix.
7133     * Recomputes the matrix if necessary.
7134     *
7135     * @return True if the transform matrix is the identity matrix, false otherwise.
7136     */
7137    final boolean hasIdentityMatrix() {
7138        if (mTransformationInfo != null) {
7139            updateMatrix();
7140            return mTransformationInfo.mMatrixIsIdentity;
7141        }
7142        return true;
7143    }
7144
7145    void ensureTransformationInfo() {
7146        if (mTransformationInfo == null) {
7147            mTransformationInfo = new TransformationInfo();
7148        }
7149    }
7150
7151    /**
7152     * Recomputes the transform matrix if necessary.
7153     */
7154    private void updateMatrix() {
7155        final TransformationInfo info = mTransformationInfo;
7156        if (info == null) {
7157            return;
7158        }
7159        if (info.mMatrixDirty) {
7160            // transform-related properties have changed since the last time someone
7161            // asked for the matrix; recalculate it with the current values
7162
7163            // Figure out if we need to update the pivot point
7164            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7165                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7166                    info.mPrevWidth = mRight - mLeft;
7167                    info.mPrevHeight = mBottom - mTop;
7168                    info.mPivotX = info.mPrevWidth / 2f;
7169                    info.mPivotY = info.mPrevHeight / 2f;
7170                }
7171            }
7172            info.mMatrix.reset();
7173            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7174                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7175                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7176                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7177            } else {
7178                if (info.mCamera == null) {
7179                    info.mCamera = new Camera();
7180                    info.matrix3D = new Matrix();
7181                }
7182                info.mCamera.save();
7183                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7184                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7185                info.mCamera.getMatrix(info.matrix3D);
7186                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7187                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7188                        info.mPivotY + info.mTranslationY);
7189                info.mMatrix.postConcat(info.matrix3D);
7190                info.mCamera.restore();
7191            }
7192            info.mMatrixDirty = false;
7193            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7194            info.mInverseMatrixDirty = true;
7195        }
7196    }
7197
7198    /**
7199     * Utility method to retrieve the inverse of the current mMatrix property.
7200     * We cache the matrix to avoid recalculating it when transform properties
7201     * have not changed.
7202     *
7203     * @return The inverse of the current matrix of this view.
7204     */
7205    final Matrix getInverseMatrix() {
7206        final TransformationInfo info = mTransformationInfo;
7207        if (info != null) {
7208            updateMatrix();
7209            if (info.mInverseMatrixDirty) {
7210                if (info.mInverseMatrix == null) {
7211                    info.mInverseMatrix = new Matrix();
7212                }
7213                info.mMatrix.invert(info.mInverseMatrix);
7214                info.mInverseMatrixDirty = false;
7215            }
7216            return info.mInverseMatrix;
7217        }
7218        return Matrix.IDENTITY_MATRIX;
7219    }
7220
7221    /**
7222     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7223     * views are drawn) from the camera to this view. The camera's distance
7224     * affects 3D transformations, for instance rotations around the X and Y
7225     * axis. If the rotationX or rotationY properties are changed and this view is
7226     * large (more than half the size of the screen), it is recommended to always
7227     * use a camera distance that's greater than the height (X axis rotation) or
7228     * the width (Y axis rotation) of this view.</p>
7229     *
7230     * <p>The distance of the camera from the view plane can have an affect on the
7231     * perspective distortion of the view when it is rotated around the x or y axis.
7232     * For example, a large distance will result in a large viewing angle, and there
7233     * will not be much perspective distortion of the view as it rotates. A short
7234     * distance may cause much more perspective distortion upon rotation, and can
7235     * also result in some drawing artifacts if the rotated view ends up partially
7236     * behind the camera (which is why the recommendation is to use a distance at
7237     * least as far as the size of the view, if the view is to be rotated.)</p>
7238     *
7239     * <p>The distance is expressed in "depth pixels." The default distance depends
7240     * on the screen density. For instance, on a medium density display, the
7241     * default distance is 1280. On a high density display, the default distance
7242     * is 1920.</p>
7243     *
7244     * <p>If you want to specify a distance that leads to visually consistent
7245     * results across various densities, use the following formula:</p>
7246     * <pre>
7247     * float scale = context.getResources().getDisplayMetrics().density;
7248     * view.setCameraDistance(distance * scale);
7249     * </pre>
7250     *
7251     * <p>The density scale factor of a high density display is 1.5,
7252     * and 1920 = 1280 * 1.5.</p>
7253     *
7254     * @param distance The distance in "depth pixels", if negative the opposite
7255     *        value is used
7256     *
7257     * @see #setRotationX(float)
7258     * @see #setRotationY(float)
7259     */
7260    public void setCameraDistance(float distance) {
7261        invalidateParentCaches();
7262        invalidate(false);
7263
7264        ensureTransformationInfo();
7265        final float dpi = mResources.getDisplayMetrics().densityDpi;
7266        final TransformationInfo info = mTransformationInfo;
7267        if (info.mCamera == null) {
7268            info.mCamera = new Camera();
7269            info.matrix3D = new Matrix();
7270        }
7271
7272        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7273        info.mMatrixDirty = true;
7274
7275        invalidate(false);
7276    }
7277
7278    /**
7279     * The degrees that the view is rotated around the pivot point.
7280     *
7281     * @see #setRotation(float)
7282     * @see #getPivotX()
7283     * @see #getPivotY()
7284     *
7285     * @return The degrees of rotation.
7286     */
7287    @ViewDebug.ExportedProperty(category = "drawing")
7288    public float getRotation() {
7289        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7290    }
7291
7292    /**
7293     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7294     * result in clockwise rotation.
7295     *
7296     * @param rotation The degrees of rotation.
7297     *
7298     * @see #getRotation()
7299     * @see #getPivotX()
7300     * @see #getPivotY()
7301     * @see #setRotationX(float)
7302     * @see #setRotationY(float)
7303     *
7304     * @attr ref android.R.styleable#View_rotation
7305     */
7306    public void setRotation(float rotation) {
7307        ensureTransformationInfo();
7308        final TransformationInfo info = mTransformationInfo;
7309        if (info.mRotation != rotation) {
7310            invalidateParentCaches();
7311            // Double-invalidation is necessary to capture view's old and new areas
7312            invalidate(false);
7313            info.mRotation = rotation;
7314            info.mMatrixDirty = true;
7315            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7316            invalidate(false);
7317        }
7318    }
7319
7320    /**
7321     * The degrees that the view is rotated around the vertical axis through the pivot point.
7322     *
7323     * @see #getPivotX()
7324     * @see #getPivotY()
7325     * @see #setRotationY(float)
7326     *
7327     * @return The degrees of Y rotation.
7328     */
7329    @ViewDebug.ExportedProperty(category = "drawing")
7330    public float getRotationY() {
7331        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7332    }
7333
7334    /**
7335     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7336     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7337     * down the y axis.
7338     *
7339     * When rotating large views, it is recommended to adjust the camera distance
7340     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7341     *
7342     * @param rotationY The degrees of Y rotation.
7343     *
7344     * @see #getRotationY()
7345     * @see #getPivotX()
7346     * @see #getPivotY()
7347     * @see #setRotation(float)
7348     * @see #setRotationX(float)
7349     * @see #setCameraDistance(float)
7350     *
7351     * @attr ref android.R.styleable#View_rotationY
7352     */
7353    public void setRotationY(float rotationY) {
7354        ensureTransformationInfo();
7355        final TransformationInfo info = mTransformationInfo;
7356        if (info.mRotationY != rotationY) {
7357            invalidateParentCaches();
7358            // Double-invalidation is necessary to capture view's old and new areas
7359            invalidate(false);
7360            info.mRotationY = rotationY;
7361            info.mMatrixDirty = true;
7362            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7363            invalidate(false);
7364        }
7365    }
7366
7367    /**
7368     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7369     *
7370     * @see #getPivotX()
7371     * @see #getPivotY()
7372     * @see #setRotationX(float)
7373     *
7374     * @return The degrees of X rotation.
7375     */
7376    @ViewDebug.ExportedProperty(category = "drawing")
7377    public float getRotationX() {
7378        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7379    }
7380
7381    /**
7382     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7383     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7384     * x axis.
7385     *
7386     * When rotating large views, it is recommended to adjust the camera distance
7387     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7388     *
7389     * @param rotationX The degrees of X rotation.
7390     *
7391     * @see #getRotationX()
7392     * @see #getPivotX()
7393     * @see #getPivotY()
7394     * @see #setRotation(float)
7395     * @see #setRotationY(float)
7396     * @see #setCameraDistance(float)
7397     *
7398     * @attr ref android.R.styleable#View_rotationX
7399     */
7400    public void setRotationX(float rotationX) {
7401        ensureTransformationInfo();
7402        final TransformationInfo info = mTransformationInfo;
7403        if (info.mRotationX != rotationX) {
7404            invalidateParentCaches();
7405            // Double-invalidation is necessary to capture view's old and new areas
7406            invalidate(false);
7407            info.mRotationX = rotationX;
7408            info.mMatrixDirty = true;
7409            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7410            invalidate(false);
7411        }
7412    }
7413
7414    /**
7415     * The amount that the view is scaled in x around the pivot point, as a proportion of
7416     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7417     *
7418     * <p>By default, this is 1.0f.
7419     *
7420     * @see #getPivotX()
7421     * @see #getPivotY()
7422     * @return The scaling factor.
7423     */
7424    @ViewDebug.ExportedProperty(category = "drawing")
7425    public float getScaleX() {
7426        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7427    }
7428
7429    /**
7430     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7431     * the view's unscaled width. A value of 1 means that no scaling is applied.
7432     *
7433     * @param scaleX The scaling factor.
7434     * @see #getPivotX()
7435     * @see #getPivotY()
7436     *
7437     * @attr ref android.R.styleable#View_scaleX
7438     */
7439    public void setScaleX(float scaleX) {
7440        ensureTransformationInfo();
7441        final TransformationInfo info = mTransformationInfo;
7442        if (info.mScaleX != scaleX) {
7443            invalidateParentCaches();
7444            // Double-invalidation is necessary to capture view's old and new areas
7445            invalidate(false);
7446            info.mScaleX = scaleX;
7447            info.mMatrixDirty = true;
7448            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7449            invalidate(false);
7450        }
7451    }
7452
7453    /**
7454     * The amount that the view is scaled in y around the pivot point, as a proportion of
7455     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7456     *
7457     * <p>By default, this is 1.0f.
7458     *
7459     * @see #getPivotX()
7460     * @see #getPivotY()
7461     * @return The scaling factor.
7462     */
7463    @ViewDebug.ExportedProperty(category = "drawing")
7464    public float getScaleY() {
7465        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7466    }
7467
7468    /**
7469     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7470     * the view's unscaled width. A value of 1 means that no scaling is applied.
7471     *
7472     * @param scaleY The scaling factor.
7473     * @see #getPivotX()
7474     * @see #getPivotY()
7475     *
7476     * @attr ref android.R.styleable#View_scaleY
7477     */
7478    public void setScaleY(float scaleY) {
7479        ensureTransformationInfo();
7480        final TransformationInfo info = mTransformationInfo;
7481        if (info.mScaleY != scaleY) {
7482            invalidateParentCaches();
7483            // Double-invalidation is necessary to capture view's old and new areas
7484            invalidate(false);
7485            info.mScaleY = scaleY;
7486            info.mMatrixDirty = true;
7487            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7488            invalidate(false);
7489        }
7490    }
7491
7492    /**
7493     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7494     * and {@link #setScaleX(float) scaled}.
7495     *
7496     * @see #getRotation()
7497     * @see #getScaleX()
7498     * @see #getScaleY()
7499     * @see #getPivotY()
7500     * @return The x location of the pivot point.
7501     */
7502    @ViewDebug.ExportedProperty(category = "drawing")
7503    public float getPivotX() {
7504        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7505    }
7506
7507    /**
7508     * Sets the x location of the point around which the view is
7509     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7510     * By default, the pivot point is centered on the object.
7511     * Setting this property disables this behavior and causes the view to use only the
7512     * explicitly set pivotX and pivotY values.
7513     *
7514     * @param pivotX The x location of the pivot point.
7515     * @see #getRotation()
7516     * @see #getScaleX()
7517     * @see #getScaleY()
7518     * @see #getPivotY()
7519     *
7520     * @attr ref android.R.styleable#View_transformPivotX
7521     */
7522    public void setPivotX(float pivotX) {
7523        ensureTransformationInfo();
7524        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7525        final TransformationInfo info = mTransformationInfo;
7526        if (info.mPivotX != pivotX) {
7527            invalidateParentCaches();
7528            // Double-invalidation is necessary to capture view's old and new areas
7529            invalidate(false);
7530            info.mPivotX = pivotX;
7531            info.mMatrixDirty = true;
7532            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7533            invalidate(false);
7534        }
7535    }
7536
7537    /**
7538     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7539     * and {@link #setScaleY(float) scaled}.
7540     *
7541     * @see #getRotation()
7542     * @see #getScaleX()
7543     * @see #getScaleY()
7544     * @see #getPivotY()
7545     * @return The y location of the pivot point.
7546     */
7547    @ViewDebug.ExportedProperty(category = "drawing")
7548    public float getPivotY() {
7549        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7550    }
7551
7552    /**
7553     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7554     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7555     * Setting this property disables this behavior and causes the view to use only the
7556     * explicitly set pivotX and pivotY values.
7557     *
7558     * @param pivotY The y location of the pivot point.
7559     * @see #getRotation()
7560     * @see #getScaleX()
7561     * @see #getScaleY()
7562     * @see #getPivotY()
7563     *
7564     * @attr ref android.R.styleable#View_transformPivotY
7565     */
7566    public void setPivotY(float pivotY) {
7567        ensureTransformationInfo();
7568        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7569        final TransformationInfo info = mTransformationInfo;
7570        if (info.mPivotY != pivotY) {
7571            invalidateParentCaches();
7572            // Double-invalidation is necessary to capture view's old and new areas
7573            invalidate(false);
7574            info.mPivotY = pivotY;
7575            info.mMatrixDirty = true;
7576            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7577            invalidate(false);
7578        }
7579    }
7580
7581    /**
7582     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7583     * completely transparent and 1 means the view is completely opaque.
7584     *
7585     * <p>By default this is 1.0f.
7586     * @return The opacity of the view.
7587     */
7588    @ViewDebug.ExportedProperty(category = "drawing")
7589    public float getAlpha() {
7590        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7591    }
7592
7593    /**
7594     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7595     * completely transparent and 1 means the view is completely opaque.</p>
7596     *
7597     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7598     * responsible for applying the opacity itself. Otherwise, calling this method is
7599     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7600     * setting a hardware layer.</p>
7601     *
7602     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
7603     * performance implications. It is generally best to use the alpha property sparingly and
7604     * transiently, as in the case of fading animations.</p>
7605     *
7606     * @param alpha The opacity of the view.
7607     *
7608     * @see #setLayerType(int, android.graphics.Paint)
7609     *
7610     * @attr ref android.R.styleable#View_alpha
7611     */
7612    public void setAlpha(float alpha) {
7613        ensureTransformationInfo();
7614        if (mTransformationInfo.mAlpha != alpha) {
7615            mTransformationInfo.mAlpha = alpha;
7616            invalidateParentCaches();
7617            if (onSetAlpha((int) (alpha * 255))) {
7618                mPrivateFlags |= ALPHA_SET;
7619                // subclass is handling alpha - don't optimize rendering cache invalidation
7620                invalidate(true);
7621            } else {
7622                mPrivateFlags &= ~ALPHA_SET;
7623                invalidate(false);
7624            }
7625        }
7626    }
7627
7628    /**
7629     * Faster version of setAlpha() which performs the same steps except there are
7630     * no calls to invalidate(). The caller of this function should perform proper invalidation
7631     * on the parent and this object. The return value indicates whether the subclass handles
7632     * alpha (the return value for onSetAlpha()).
7633     *
7634     * @param alpha The new value for the alpha property
7635     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7636     *         the new value for the alpha property is different from the old value
7637     */
7638    boolean setAlphaNoInvalidation(float alpha) {
7639        ensureTransformationInfo();
7640        if (mTransformationInfo.mAlpha != alpha) {
7641            mTransformationInfo.mAlpha = alpha;
7642            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7643            if (subclassHandlesAlpha) {
7644                mPrivateFlags |= ALPHA_SET;
7645                return true;
7646            } else {
7647                mPrivateFlags &= ~ALPHA_SET;
7648            }
7649        }
7650        return false;
7651    }
7652
7653    /**
7654     * Top position of this view relative to its parent.
7655     *
7656     * @return The top of this view, in pixels.
7657     */
7658    @ViewDebug.CapturedViewProperty
7659    public final int getTop() {
7660        return mTop;
7661    }
7662
7663    /**
7664     * Sets the top position of this view relative to its parent. This method is meant to be called
7665     * by the layout system and should not generally be called otherwise, because the property
7666     * may be changed at any time by the layout.
7667     *
7668     * @param top The top of this view, in pixels.
7669     */
7670    public final void setTop(int top) {
7671        if (top != mTop) {
7672            updateMatrix();
7673            final boolean matrixIsIdentity = mTransformationInfo == null
7674                    || mTransformationInfo.mMatrixIsIdentity;
7675            if (matrixIsIdentity) {
7676                if (mAttachInfo != null) {
7677                    int minTop;
7678                    int yLoc;
7679                    if (top < mTop) {
7680                        minTop = top;
7681                        yLoc = top - mTop;
7682                    } else {
7683                        minTop = mTop;
7684                        yLoc = 0;
7685                    }
7686                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7687                }
7688            } else {
7689                // Double-invalidation is necessary to capture view's old and new areas
7690                invalidate(true);
7691            }
7692
7693            int width = mRight - mLeft;
7694            int oldHeight = mBottom - mTop;
7695
7696            mTop = top;
7697
7698            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7699
7700            if (!matrixIsIdentity) {
7701                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7702                    // A change in dimension means an auto-centered pivot point changes, too
7703                    mTransformationInfo.mMatrixDirty = true;
7704                }
7705                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7706                invalidate(true);
7707            }
7708            mBackgroundSizeChanged = true;
7709            invalidateParentIfNeeded();
7710        }
7711    }
7712
7713    /**
7714     * Bottom position of this view relative to its parent.
7715     *
7716     * @return The bottom of this view, in pixels.
7717     */
7718    @ViewDebug.CapturedViewProperty
7719    public final int getBottom() {
7720        return mBottom;
7721    }
7722
7723    /**
7724     * True if this view has changed since the last time being drawn.
7725     *
7726     * @return The dirty state of this view.
7727     */
7728    public boolean isDirty() {
7729        return (mPrivateFlags & DIRTY_MASK) != 0;
7730    }
7731
7732    /**
7733     * Sets the bottom position of this view relative to its parent. This method is meant to be
7734     * called by the layout system and should not generally be called otherwise, because the
7735     * property may be changed at any time by the layout.
7736     *
7737     * @param bottom The bottom of this view, in pixels.
7738     */
7739    public final void setBottom(int bottom) {
7740        if (bottom != mBottom) {
7741            updateMatrix();
7742            final boolean matrixIsIdentity = mTransformationInfo == null
7743                    || mTransformationInfo.mMatrixIsIdentity;
7744            if (matrixIsIdentity) {
7745                if (mAttachInfo != null) {
7746                    int maxBottom;
7747                    if (bottom < mBottom) {
7748                        maxBottom = mBottom;
7749                    } else {
7750                        maxBottom = bottom;
7751                    }
7752                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7753                }
7754            } else {
7755                // Double-invalidation is necessary to capture view's old and new areas
7756                invalidate(true);
7757            }
7758
7759            int width = mRight - mLeft;
7760            int oldHeight = mBottom - mTop;
7761
7762            mBottom = bottom;
7763
7764            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7765
7766            if (!matrixIsIdentity) {
7767                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7768                    // A change in dimension means an auto-centered pivot point changes, too
7769                    mTransformationInfo.mMatrixDirty = true;
7770                }
7771                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7772                invalidate(true);
7773            }
7774            mBackgroundSizeChanged = true;
7775            invalidateParentIfNeeded();
7776        }
7777    }
7778
7779    /**
7780     * Left position of this view relative to its parent.
7781     *
7782     * @return The left edge of this view, in pixels.
7783     */
7784    @ViewDebug.CapturedViewProperty
7785    public final int getLeft() {
7786        return mLeft;
7787    }
7788
7789    /**
7790     * Sets the left position of this view relative to its parent. This method is meant to be called
7791     * by the layout system and should not generally be called otherwise, because the property
7792     * may be changed at any time by the layout.
7793     *
7794     * @param left The bottom of this view, in pixels.
7795     */
7796    public final void setLeft(int left) {
7797        if (left != mLeft) {
7798            updateMatrix();
7799            final boolean matrixIsIdentity = mTransformationInfo == null
7800                    || mTransformationInfo.mMatrixIsIdentity;
7801            if (matrixIsIdentity) {
7802                if (mAttachInfo != null) {
7803                    int minLeft;
7804                    int xLoc;
7805                    if (left < mLeft) {
7806                        minLeft = left;
7807                        xLoc = left - mLeft;
7808                    } else {
7809                        minLeft = mLeft;
7810                        xLoc = 0;
7811                    }
7812                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7813                }
7814            } else {
7815                // Double-invalidation is necessary to capture view's old and new areas
7816                invalidate(true);
7817            }
7818
7819            int oldWidth = mRight - mLeft;
7820            int height = mBottom - mTop;
7821
7822            mLeft = left;
7823
7824            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7825
7826            if (!matrixIsIdentity) {
7827                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7828                    // A change in dimension means an auto-centered pivot point changes, too
7829                    mTransformationInfo.mMatrixDirty = true;
7830                }
7831                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7832                invalidate(true);
7833            }
7834            mBackgroundSizeChanged = true;
7835            invalidateParentIfNeeded();
7836        }
7837    }
7838
7839    /**
7840     * Right position of this view relative to its parent.
7841     *
7842     * @return The right edge of this view, in pixels.
7843     */
7844    @ViewDebug.CapturedViewProperty
7845    public final int getRight() {
7846        return mRight;
7847    }
7848
7849    /**
7850     * Sets the right position of this view relative to its parent. This method is meant to be called
7851     * by the layout system and should not generally be called otherwise, because the property
7852     * may be changed at any time by the layout.
7853     *
7854     * @param right The bottom of this view, in pixels.
7855     */
7856    public final void setRight(int right) {
7857        if (right != mRight) {
7858            updateMatrix();
7859            final boolean matrixIsIdentity = mTransformationInfo == null
7860                    || mTransformationInfo.mMatrixIsIdentity;
7861            if (matrixIsIdentity) {
7862                if (mAttachInfo != null) {
7863                    int maxRight;
7864                    if (right < mRight) {
7865                        maxRight = mRight;
7866                    } else {
7867                        maxRight = right;
7868                    }
7869                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
7870                }
7871            } else {
7872                // Double-invalidation is necessary to capture view's old and new areas
7873                invalidate(true);
7874            }
7875
7876            int oldWidth = mRight - mLeft;
7877            int height = mBottom - mTop;
7878
7879            mRight = right;
7880
7881            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7882
7883            if (!matrixIsIdentity) {
7884                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7885                    // A change in dimension means an auto-centered pivot point changes, too
7886                    mTransformationInfo.mMatrixDirty = true;
7887                }
7888                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7889                invalidate(true);
7890            }
7891            mBackgroundSizeChanged = true;
7892            invalidateParentIfNeeded();
7893        }
7894    }
7895
7896    /**
7897     * The visual x position of this view, in pixels. This is equivalent to the
7898     * {@link #setTranslationX(float) translationX} property plus the current
7899     * {@link #getLeft() left} property.
7900     *
7901     * @return The visual x position of this view, in pixels.
7902     */
7903    @ViewDebug.ExportedProperty(category = "drawing")
7904    public float getX() {
7905        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
7906    }
7907
7908    /**
7909     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
7910     * {@link #setTranslationX(float) translationX} property to be the difference between
7911     * the x value passed in and the current {@link #getLeft() left} property.
7912     *
7913     * @param x The visual x position of this view, in pixels.
7914     */
7915    public void setX(float x) {
7916        setTranslationX(x - mLeft);
7917    }
7918
7919    /**
7920     * The visual y position of this view, in pixels. This is equivalent to the
7921     * {@link #setTranslationY(float) translationY} property plus the current
7922     * {@link #getTop() top} property.
7923     *
7924     * @return The visual y position of this view, in pixels.
7925     */
7926    @ViewDebug.ExportedProperty(category = "drawing")
7927    public float getY() {
7928        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
7929    }
7930
7931    /**
7932     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
7933     * {@link #setTranslationY(float) translationY} property to be the difference between
7934     * the y value passed in and the current {@link #getTop() top} property.
7935     *
7936     * @param y The visual y position of this view, in pixels.
7937     */
7938    public void setY(float y) {
7939        setTranslationY(y - mTop);
7940    }
7941
7942
7943    /**
7944     * The horizontal location of this view relative to its {@link #getLeft() left} position.
7945     * This position is post-layout, in addition to wherever the object's
7946     * layout placed it.
7947     *
7948     * @return The horizontal position of this view relative to its left position, in pixels.
7949     */
7950    @ViewDebug.ExportedProperty(category = "drawing")
7951    public float getTranslationX() {
7952        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
7953    }
7954
7955    /**
7956     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
7957     * This effectively positions the object post-layout, in addition to wherever the object's
7958     * layout placed it.
7959     *
7960     * @param translationX The horizontal position of this view relative to its left position,
7961     * in pixels.
7962     *
7963     * @attr ref android.R.styleable#View_translationX
7964     */
7965    public void setTranslationX(float translationX) {
7966        ensureTransformationInfo();
7967        final TransformationInfo info = mTransformationInfo;
7968        if (info.mTranslationX != translationX) {
7969            invalidateParentCaches();
7970            // Double-invalidation is necessary to capture view's old and new areas
7971            invalidate(false);
7972            info.mTranslationX = translationX;
7973            info.mMatrixDirty = true;
7974            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7975            invalidate(false);
7976        }
7977    }
7978
7979    /**
7980     * The horizontal location of this view relative to its {@link #getTop() top} position.
7981     * This position is post-layout, in addition to wherever the object's
7982     * layout placed it.
7983     *
7984     * @return The vertical position of this view relative to its top position,
7985     * in pixels.
7986     */
7987    @ViewDebug.ExportedProperty(category = "drawing")
7988    public float getTranslationY() {
7989        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
7990    }
7991
7992    /**
7993     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
7994     * This effectively positions the object post-layout, in addition to wherever the object's
7995     * layout placed it.
7996     *
7997     * @param translationY The vertical position of this view relative to its top position,
7998     * in pixels.
7999     *
8000     * @attr ref android.R.styleable#View_translationY
8001     */
8002    public void setTranslationY(float translationY) {
8003        ensureTransformationInfo();
8004        final TransformationInfo info = mTransformationInfo;
8005        if (info.mTranslationY != translationY) {
8006            invalidateParentCaches();
8007            // Double-invalidation is necessary to capture view's old and new areas
8008            invalidate(false);
8009            info.mTranslationY = translationY;
8010            info.mMatrixDirty = true;
8011            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8012            invalidate(false);
8013        }
8014    }
8015
8016    /**
8017     * Hit rectangle in parent's coordinates
8018     *
8019     * @param outRect The hit rectangle of the view.
8020     */
8021    public void getHitRect(Rect outRect) {
8022        updateMatrix();
8023        final TransformationInfo info = mTransformationInfo;
8024        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8025            outRect.set(mLeft, mTop, mRight, mBottom);
8026        } else {
8027            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8028            tmpRect.set(-info.mPivotX, -info.mPivotY,
8029                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8030            info.mMatrix.mapRect(tmpRect);
8031            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8032                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8033        }
8034    }
8035
8036    /**
8037     * Determines whether the given point, in local coordinates is inside the view.
8038     */
8039    /*package*/ final boolean pointInView(float localX, float localY) {
8040        return localX >= 0 && localX < (mRight - mLeft)
8041                && localY >= 0 && localY < (mBottom - mTop);
8042    }
8043
8044    /**
8045     * Utility method to determine whether the given point, in local coordinates,
8046     * is inside the view, where the area of the view is expanded by the slop factor.
8047     * This method is called while processing touch-move events to determine if the event
8048     * is still within the view.
8049     */
8050    private boolean pointInView(float localX, float localY, float slop) {
8051        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8052                localY < ((mBottom - mTop) + slop);
8053    }
8054
8055    /**
8056     * When a view has focus and the user navigates away from it, the next view is searched for
8057     * starting from the rectangle filled in by this method.
8058     *
8059     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8060     * of the view.  However, if your view maintains some idea of internal selection,
8061     * such as a cursor, or a selected row or column, you should override this method and
8062     * fill in a more specific rectangle.
8063     *
8064     * @param r The rectangle to fill in, in this view's coordinates.
8065     */
8066    public void getFocusedRect(Rect r) {
8067        getDrawingRect(r);
8068    }
8069
8070    /**
8071     * If some part of this view is not clipped by any of its parents, then
8072     * return that area in r in global (root) coordinates. To convert r to local
8073     * coordinates (without taking possible View rotations into account), offset
8074     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8075     * If the view is completely clipped or translated out, return false.
8076     *
8077     * @param r If true is returned, r holds the global coordinates of the
8078     *        visible portion of this view.
8079     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8080     *        between this view and its root. globalOffet may be null.
8081     * @return true if r is non-empty (i.e. part of the view is visible at the
8082     *         root level.
8083     */
8084    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8085        int width = mRight - mLeft;
8086        int height = mBottom - mTop;
8087        if (width > 0 && height > 0) {
8088            r.set(0, 0, width, height);
8089            if (globalOffset != null) {
8090                globalOffset.set(-mScrollX, -mScrollY);
8091            }
8092            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8093        }
8094        return false;
8095    }
8096
8097    public final boolean getGlobalVisibleRect(Rect r) {
8098        return getGlobalVisibleRect(r, null);
8099    }
8100
8101    public final boolean getLocalVisibleRect(Rect r) {
8102        Point offset = new Point();
8103        if (getGlobalVisibleRect(r, offset)) {
8104            r.offset(-offset.x, -offset.y); // make r local
8105            return true;
8106        }
8107        return false;
8108    }
8109
8110    /**
8111     * Offset this view's vertical location by the specified number of pixels.
8112     *
8113     * @param offset the number of pixels to offset the view by
8114     */
8115    public void offsetTopAndBottom(int offset) {
8116        if (offset != 0) {
8117            updateMatrix();
8118            final boolean matrixIsIdentity = mTransformationInfo == null
8119                    || mTransformationInfo.mMatrixIsIdentity;
8120            if (matrixIsIdentity) {
8121                final ViewParent p = mParent;
8122                if (p != null && mAttachInfo != null) {
8123                    final Rect r = mAttachInfo.mTmpInvalRect;
8124                    int minTop;
8125                    int maxBottom;
8126                    int yLoc;
8127                    if (offset < 0) {
8128                        minTop = mTop + offset;
8129                        maxBottom = mBottom;
8130                        yLoc = offset;
8131                    } else {
8132                        minTop = mTop;
8133                        maxBottom = mBottom + offset;
8134                        yLoc = 0;
8135                    }
8136                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8137                    p.invalidateChild(this, r);
8138                }
8139            } else {
8140                invalidate(false);
8141            }
8142
8143            mTop += offset;
8144            mBottom += offset;
8145
8146            if (!matrixIsIdentity) {
8147                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8148                invalidate(false);
8149            }
8150            invalidateParentIfNeeded();
8151        }
8152    }
8153
8154    /**
8155     * Offset this view's horizontal location by the specified amount of pixels.
8156     *
8157     * @param offset the numer of pixels to offset the view by
8158     */
8159    public void offsetLeftAndRight(int offset) {
8160        if (offset != 0) {
8161            updateMatrix();
8162            final boolean matrixIsIdentity = mTransformationInfo == null
8163                    || mTransformationInfo.mMatrixIsIdentity;
8164            if (matrixIsIdentity) {
8165                final ViewParent p = mParent;
8166                if (p != null && mAttachInfo != null) {
8167                    final Rect r = mAttachInfo.mTmpInvalRect;
8168                    int minLeft;
8169                    int maxRight;
8170                    if (offset < 0) {
8171                        minLeft = mLeft + offset;
8172                        maxRight = mRight;
8173                    } else {
8174                        minLeft = mLeft;
8175                        maxRight = mRight + offset;
8176                    }
8177                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8178                    p.invalidateChild(this, r);
8179                }
8180            } else {
8181                invalidate(false);
8182            }
8183
8184            mLeft += offset;
8185            mRight += offset;
8186
8187            if (!matrixIsIdentity) {
8188                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8189                invalidate(false);
8190            }
8191            invalidateParentIfNeeded();
8192        }
8193    }
8194
8195    /**
8196     * Get the LayoutParams associated with this view. All views should have
8197     * layout parameters. These supply parameters to the <i>parent</i> of this
8198     * view specifying how it should be arranged. There are many subclasses of
8199     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8200     * of ViewGroup that are responsible for arranging their children.
8201     *
8202     * This method may return null if this View is not attached to a parent
8203     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8204     * was not invoked successfully. When a View is attached to a parent
8205     * ViewGroup, this method must not return null.
8206     *
8207     * @return The LayoutParams associated with this view, or null if no
8208     *         parameters have been set yet
8209     */
8210    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8211    public ViewGroup.LayoutParams getLayoutParams() {
8212        return mLayoutParams;
8213    }
8214
8215    /**
8216     * Set the layout parameters associated with this view. These supply
8217     * parameters to the <i>parent</i> of this view specifying how it should be
8218     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8219     * correspond to the different subclasses of ViewGroup that are responsible
8220     * for arranging their children.
8221     *
8222     * @param params The layout parameters for this view, cannot be null
8223     */
8224    public void setLayoutParams(ViewGroup.LayoutParams params) {
8225        if (params == null) {
8226            throw new NullPointerException("Layout parameters cannot be null");
8227        }
8228        mLayoutParams = params;
8229        if (mParent instanceof ViewGroup) {
8230            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8231        }
8232        requestLayout();
8233    }
8234
8235    /**
8236     * Set the scrolled position of your view. This will cause a call to
8237     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8238     * invalidated.
8239     * @param x the x position to scroll to
8240     * @param y the y position to scroll to
8241     */
8242    public void scrollTo(int x, int y) {
8243        if (mScrollX != x || mScrollY != y) {
8244            int oldX = mScrollX;
8245            int oldY = mScrollY;
8246            mScrollX = x;
8247            mScrollY = y;
8248            invalidateParentCaches();
8249            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8250            if (!awakenScrollBars()) {
8251                invalidate(true);
8252            }
8253        }
8254    }
8255
8256    /**
8257     * Move the scrolled position of your view. This will cause a call to
8258     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8259     * invalidated.
8260     * @param x the amount of pixels to scroll by horizontally
8261     * @param y the amount of pixels to scroll by vertically
8262     */
8263    public void scrollBy(int x, int y) {
8264        scrollTo(mScrollX + x, mScrollY + y);
8265    }
8266
8267    /**
8268     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8269     * animation to fade the scrollbars out after a default delay. If a subclass
8270     * provides animated scrolling, the start delay should equal the duration
8271     * of the scrolling animation.</p>
8272     *
8273     * <p>The animation starts only if at least one of the scrollbars is
8274     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8275     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8276     * this method returns true, and false otherwise. If the animation is
8277     * started, this method calls {@link #invalidate()}; in that case the
8278     * caller should not call {@link #invalidate()}.</p>
8279     *
8280     * <p>This method should be invoked every time a subclass directly updates
8281     * the scroll parameters.</p>
8282     *
8283     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8284     * and {@link #scrollTo(int, int)}.</p>
8285     *
8286     * @return true if the animation is played, false otherwise
8287     *
8288     * @see #awakenScrollBars(int)
8289     * @see #scrollBy(int, int)
8290     * @see #scrollTo(int, int)
8291     * @see #isHorizontalScrollBarEnabled()
8292     * @see #isVerticalScrollBarEnabled()
8293     * @see #setHorizontalScrollBarEnabled(boolean)
8294     * @see #setVerticalScrollBarEnabled(boolean)
8295     */
8296    protected boolean awakenScrollBars() {
8297        return mScrollCache != null &&
8298                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8299    }
8300
8301    /**
8302     * Trigger the scrollbars to draw.
8303     * This method differs from awakenScrollBars() only in its default duration.
8304     * initialAwakenScrollBars() will show the scroll bars for longer than
8305     * usual to give the user more of a chance to notice them.
8306     *
8307     * @return true if the animation is played, false otherwise.
8308     */
8309    private boolean initialAwakenScrollBars() {
8310        return mScrollCache != null &&
8311                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8312    }
8313
8314    /**
8315     * <p>
8316     * Trigger the scrollbars to draw. When invoked this method starts an
8317     * animation to fade the scrollbars out after a fixed delay. If a subclass
8318     * provides animated scrolling, the start delay should equal the duration of
8319     * the scrolling animation.
8320     * </p>
8321     *
8322     * <p>
8323     * The animation starts only if at least one of the scrollbars is enabled,
8324     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8325     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8326     * this method returns true, and false otherwise. If the animation is
8327     * started, this method calls {@link #invalidate()}; in that case the caller
8328     * should not call {@link #invalidate()}.
8329     * </p>
8330     *
8331     * <p>
8332     * This method should be invoked everytime a subclass directly updates the
8333     * scroll parameters.
8334     * </p>
8335     *
8336     * @param startDelay the delay, in milliseconds, after which the animation
8337     *        should start; when the delay is 0, the animation starts
8338     *        immediately
8339     * @return true if the animation is played, false otherwise
8340     *
8341     * @see #scrollBy(int, int)
8342     * @see #scrollTo(int, int)
8343     * @see #isHorizontalScrollBarEnabled()
8344     * @see #isVerticalScrollBarEnabled()
8345     * @see #setHorizontalScrollBarEnabled(boolean)
8346     * @see #setVerticalScrollBarEnabled(boolean)
8347     */
8348    protected boolean awakenScrollBars(int startDelay) {
8349        return awakenScrollBars(startDelay, true);
8350    }
8351
8352    /**
8353     * <p>
8354     * Trigger the scrollbars to draw. When invoked this method starts an
8355     * animation to fade the scrollbars out after a fixed delay. If a subclass
8356     * provides animated scrolling, the start delay should equal the duration of
8357     * the scrolling animation.
8358     * </p>
8359     *
8360     * <p>
8361     * The animation starts only if at least one of the scrollbars is enabled,
8362     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8363     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8364     * this method returns true, and false otherwise. If the animation is
8365     * started, this method calls {@link #invalidate()} if the invalidate parameter
8366     * is set to true; in that case the caller
8367     * should not call {@link #invalidate()}.
8368     * </p>
8369     *
8370     * <p>
8371     * This method should be invoked everytime a subclass directly updates the
8372     * scroll parameters.
8373     * </p>
8374     *
8375     * @param startDelay the delay, in milliseconds, after which the animation
8376     *        should start; when the delay is 0, the animation starts
8377     *        immediately
8378     *
8379     * @param invalidate Wheter this method should call invalidate
8380     *
8381     * @return true if the animation is played, false otherwise
8382     *
8383     * @see #scrollBy(int, int)
8384     * @see #scrollTo(int, int)
8385     * @see #isHorizontalScrollBarEnabled()
8386     * @see #isVerticalScrollBarEnabled()
8387     * @see #setHorizontalScrollBarEnabled(boolean)
8388     * @see #setVerticalScrollBarEnabled(boolean)
8389     */
8390    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8391        final ScrollabilityCache scrollCache = mScrollCache;
8392
8393        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8394            return false;
8395        }
8396
8397        if (scrollCache.scrollBar == null) {
8398            scrollCache.scrollBar = new ScrollBarDrawable();
8399        }
8400
8401        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8402
8403            if (invalidate) {
8404                // Invalidate to show the scrollbars
8405                invalidate(true);
8406            }
8407
8408            if (scrollCache.state == ScrollabilityCache.OFF) {
8409                // FIXME: this is copied from WindowManagerService.
8410                // We should get this value from the system when it
8411                // is possible to do so.
8412                final int KEY_REPEAT_FIRST_DELAY = 750;
8413                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8414            }
8415
8416            // Tell mScrollCache when we should start fading. This may
8417            // extend the fade start time if one was already scheduled
8418            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8419            scrollCache.fadeStartTime = fadeStartTime;
8420            scrollCache.state = ScrollabilityCache.ON;
8421
8422            // Schedule our fader to run, unscheduling any old ones first
8423            if (mAttachInfo != null) {
8424                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8425                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8426            }
8427
8428            return true;
8429        }
8430
8431        return false;
8432    }
8433
8434    /**
8435     * Do not invalidate views which are not visible and which are not running an animation. They
8436     * will not get drawn and they should not set dirty flags as if they will be drawn
8437     */
8438    private boolean skipInvalidate() {
8439        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8440                (!(mParent instanceof ViewGroup) ||
8441                        !((ViewGroup) mParent).isViewTransitioning(this));
8442    }
8443    /**
8444     * Mark the area defined by dirty as needing to be drawn. If the view is
8445     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8446     * in the future. This must be called from a UI thread. To call from a non-UI
8447     * thread, call {@link #postInvalidate()}.
8448     *
8449     * WARNING: This method is destructive to dirty.
8450     * @param dirty the rectangle representing the bounds of the dirty region
8451     */
8452    public void invalidate(Rect dirty) {
8453        if (ViewDebug.TRACE_HIERARCHY) {
8454            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8455        }
8456
8457        if (skipInvalidate()) {
8458            return;
8459        }
8460        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8461                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8462                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8463            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8464            mPrivateFlags |= INVALIDATED;
8465            mPrivateFlags |= DIRTY;
8466            final ViewParent p = mParent;
8467            final AttachInfo ai = mAttachInfo;
8468            //noinspection PointlessBooleanExpression,ConstantConditions
8469            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8470                if (p != null && ai != null && ai.mHardwareAccelerated) {
8471                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8472                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8473                    p.invalidateChild(this, null);
8474                    return;
8475                }
8476            }
8477            if (p != null && ai != null) {
8478                final int scrollX = mScrollX;
8479                final int scrollY = mScrollY;
8480                final Rect r = ai.mTmpInvalRect;
8481                r.set(dirty.left - scrollX, dirty.top - scrollY,
8482                        dirty.right - scrollX, dirty.bottom - scrollY);
8483                mParent.invalidateChild(this, r);
8484            }
8485        }
8486    }
8487
8488    /**
8489     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8490     * The coordinates of the dirty rect are relative to the view.
8491     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8492     * will be called at some point in the future. This must be called from
8493     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8494     * @param l the left position of the dirty region
8495     * @param t the top position of the dirty region
8496     * @param r the right position of the dirty region
8497     * @param b the bottom position of the dirty region
8498     */
8499    public void invalidate(int l, int t, int r, int b) {
8500        if (ViewDebug.TRACE_HIERARCHY) {
8501            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8502        }
8503
8504        if (skipInvalidate()) {
8505            return;
8506        }
8507        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8508                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8509                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8510            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8511            mPrivateFlags |= INVALIDATED;
8512            mPrivateFlags |= DIRTY;
8513            final ViewParent p = mParent;
8514            final AttachInfo ai = mAttachInfo;
8515            //noinspection PointlessBooleanExpression,ConstantConditions
8516            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8517                if (p != null && ai != null && ai.mHardwareAccelerated) {
8518                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8519                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8520                    p.invalidateChild(this, null);
8521                    return;
8522                }
8523            }
8524            if (p != null && ai != null && l < r && t < b) {
8525                final int scrollX = mScrollX;
8526                final int scrollY = mScrollY;
8527                final Rect tmpr = ai.mTmpInvalRect;
8528                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8529                p.invalidateChild(this, tmpr);
8530            }
8531        }
8532    }
8533
8534    /**
8535     * Invalidate the whole view. If the view is visible,
8536     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8537     * the future. This must be called from a UI thread. To call from a non-UI thread,
8538     * call {@link #postInvalidate()}.
8539     */
8540    public void invalidate() {
8541        invalidate(true);
8542    }
8543
8544    /**
8545     * This is where the invalidate() work actually happens. A full invalidate()
8546     * causes the drawing cache to be invalidated, but this function can be called with
8547     * invalidateCache set to false to skip that invalidation step for cases that do not
8548     * need it (for example, a component that remains at the same dimensions with the same
8549     * content).
8550     *
8551     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8552     * well. This is usually true for a full invalidate, but may be set to false if the
8553     * View's contents or dimensions have not changed.
8554     */
8555    void invalidate(boolean invalidateCache) {
8556        if (ViewDebug.TRACE_HIERARCHY) {
8557            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8558        }
8559
8560        if (skipInvalidate()) {
8561            return;
8562        }
8563        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8564                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8565                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8566            mLastIsOpaque = isOpaque();
8567            mPrivateFlags &= ~DRAWN;
8568            mPrivateFlags |= DIRTY;
8569            if (invalidateCache) {
8570                mPrivateFlags |= INVALIDATED;
8571                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8572            }
8573            final AttachInfo ai = mAttachInfo;
8574            final ViewParent p = mParent;
8575            //noinspection PointlessBooleanExpression,ConstantConditions
8576            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8577                if (p != null && ai != null && ai.mHardwareAccelerated) {
8578                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8579                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8580                    p.invalidateChild(this, null);
8581                    return;
8582                }
8583            }
8584
8585            if (p != null && ai != null) {
8586                final Rect r = ai.mTmpInvalRect;
8587                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8588                // Don't call invalidate -- we don't want to internally scroll
8589                // our own bounds
8590                p.invalidateChild(this, r);
8591            }
8592        }
8593    }
8594
8595    /**
8596     * Used to indicate that the parent of this view should clear its caches. This functionality
8597     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8598     * which is necessary when various parent-managed properties of the view change, such as
8599     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8600     * clears the parent caches and does not causes an invalidate event.
8601     *
8602     * @hide
8603     */
8604    protected void invalidateParentCaches() {
8605        if (mParent instanceof View) {
8606            ((View) mParent).mPrivateFlags |= INVALIDATED;
8607        }
8608    }
8609
8610    /**
8611     * Used to indicate that the parent of this view should be invalidated. This functionality
8612     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8613     * which is necessary when various parent-managed properties of the view change, such as
8614     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8615     * an invalidation event to the parent.
8616     *
8617     * @hide
8618     */
8619    protected void invalidateParentIfNeeded() {
8620        if (isHardwareAccelerated() && mParent instanceof View) {
8621            ((View) mParent).invalidate(true);
8622        }
8623    }
8624
8625    /**
8626     * Indicates whether this View is opaque. An opaque View guarantees that it will
8627     * draw all the pixels overlapping its bounds using a fully opaque color.
8628     *
8629     * Subclasses of View should override this method whenever possible to indicate
8630     * whether an instance is opaque. Opaque Views are treated in a special way by
8631     * the View hierarchy, possibly allowing it to perform optimizations during
8632     * invalidate/draw passes.
8633     *
8634     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8635     */
8636    @ViewDebug.ExportedProperty(category = "drawing")
8637    public boolean isOpaque() {
8638        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8639                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8640                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8641    }
8642
8643    /**
8644     * @hide
8645     */
8646    protected void computeOpaqueFlags() {
8647        // Opaque if:
8648        //   - Has a background
8649        //   - Background is opaque
8650        //   - Doesn't have scrollbars or scrollbars are inside overlay
8651
8652        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8653            mPrivateFlags |= OPAQUE_BACKGROUND;
8654        } else {
8655            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8656        }
8657
8658        final int flags = mViewFlags;
8659        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8660                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8661            mPrivateFlags |= OPAQUE_SCROLLBARS;
8662        } else {
8663            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8664        }
8665    }
8666
8667    /**
8668     * @hide
8669     */
8670    protected boolean hasOpaqueScrollbars() {
8671        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8672    }
8673
8674    /**
8675     * @return A handler associated with the thread running the View. This
8676     * handler can be used to pump events in the UI events queue.
8677     */
8678    public Handler getHandler() {
8679        if (mAttachInfo != null) {
8680            return mAttachInfo.mHandler;
8681        }
8682        return null;
8683    }
8684
8685    /**
8686     * <p>Causes the Runnable to be added to the message queue.
8687     * The runnable will be run on the user interface thread.</p>
8688     *
8689     * <p>This method can be invoked from outside of the UI thread
8690     * only when this View is attached to a window.</p>
8691     *
8692     * @param action The Runnable that will be executed.
8693     *
8694     * @return Returns true if the Runnable was successfully placed in to the
8695     *         message queue.  Returns false on failure, usually because the
8696     *         looper processing the message queue is exiting.
8697     */
8698    public boolean post(Runnable action) {
8699        Handler handler;
8700        AttachInfo attachInfo = mAttachInfo;
8701        if (attachInfo != null) {
8702            handler = attachInfo.mHandler;
8703        } else {
8704            // Assume that post will succeed later
8705            ViewRootImpl.getRunQueue().post(action);
8706            return true;
8707        }
8708
8709        return handler.post(action);
8710    }
8711
8712    /**
8713     * <p>Causes the Runnable to be added to the message queue, to be run
8714     * after the specified amount of time elapses.
8715     * The runnable will be run on the user interface thread.</p>
8716     *
8717     * <p>This method can be invoked from outside of the UI thread
8718     * only when this View is attached to a window.</p>
8719     *
8720     * @param action The Runnable that will be executed.
8721     * @param delayMillis The delay (in milliseconds) until the Runnable
8722     *        will be executed.
8723     *
8724     * @return true if the Runnable was successfully placed in to the
8725     *         message queue.  Returns false on failure, usually because the
8726     *         looper processing the message queue is exiting.  Note that a
8727     *         result of true does not mean the Runnable will be processed --
8728     *         if the looper is quit before the delivery time of the message
8729     *         occurs then the message will be dropped.
8730     */
8731    public boolean postDelayed(Runnable action, long delayMillis) {
8732        Handler handler;
8733        AttachInfo attachInfo = mAttachInfo;
8734        if (attachInfo != null) {
8735            handler = attachInfo.mHandler;
8736        } else {
8737            // Assume that post will succeed later
8738            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8739            return true;
8740        }
8741
8742        return handler.postDelayed(action, delayMillis);
8743    }
8744
8745    /**
8746     * <p>Removes the specified Runnable from the message queue.</p>
8747     *
8748     * <p>This method can be invoked from outside of the UI thread
8749     * only when this View is attached to a window.</p>
8750     *
8751     * @param action The Runnable to remove from the message handling queue
8752     *
8753     * @return true if this view could ask the Handler to remove the Runnable,
8754     *         false otherwise. When the returned value is true, the Runnable
8755     *         may or may not have been actually removed from the message queue
8756     *         (for instance, if the Runnable was not in the queue already.)
8757     */
8758    public boolean removeCallbacks(Runnable action) {
8759        Handler handler;
8760        AttachInfo attachInfo = mAttachInfo;
8761        if (attachInfo != null) {
8762            handler = attachInfo.mHandler;
8763        } else {
8764            // Assume that post will succeed later
8765            ViewRootImpl.getRunQueue().removeCallbacks(action);
8766            return true;
8767        }
8768
8769        handler.removeCallbacks(action);
8770        return true;
8771    }
8772
8773    /**
8774     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8775     * Use this to invalidate the View from a non-UI thread.</p>
8776     *
8777     * <p>This method can be invoked from outside of the UI thread
8778     * only when this View is attached to a window.</p>
8779     *
8780     * @see #invalidate()
8781     */
8782    public void postInvalidate() {
8783        postInvalidateDelayed(0);
8784    }
8785
8786    /**
8787     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8788     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8789     *
8790     * <p>This method can be invoked from outside of the UI thread
8791     * only when this View is attached to a window.</p>
8792     *
8793     * @param left The left coordinate of the rectangle to invalidate.
8794     * @param top The top coordinate of the rectangle to invalidate.
8795     * @param right The right coordinate of the rectangle to invalidate.
8796     * @param bottom The bottom coordinate of the rectangle to invalidate.
8797     *
8798     * @see #invalidate(int, int, int, int)
8799     * @see #invalidate(Rect)
8800     */
8801    public void postInvalidate(int left, int top, int right, int bottom) {
8802        postInvalidateDelayed(0, left, top, right, bottom);
8803    }
8804
8805    /**
8806     * <p>Cause an invalidate to happen on a subsequent cycle through the event
8807     * loop. Waits for the specified amount of time.</p>
8808     *
8809     * <p>This method can be invoked from outside of the UI thread
8810     * only when this View is attached to a window.</p>
8811     *
8812     * @param delayMilliseconds the duration in milliseconds to delay the
8813     *         invalidation by
8814     */
8815    public void postInvalidateDelayed(long delayMilliseconds) {
8816        // We try only with the AttachInfo because there's no point in invalidating
8817        // if we are not attached to our window
8818        AttachInfo attachInfo = mAttachInfo;
8819        if (attachInfo != null) {
8820            Message msg = Message.obtain();
8821            msg.what = AttachInfo.INVALIDATE_MSG;
8822            msg.obj = this;
8823            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8824        }
8825    }
8826
8827    /**
8828     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8829     * through the event loop. Waits for the specified amount of time.</p>
8830     *
8831     * <p>This method can be invoked from outside of the UI thread
8832     * only when this View is attached to a window.</p>
8833     *
8834     * @param delayMilliseconds the duration in milliseconds to delay the
8835     *         invalidation by
8836     * @param left The left coordinate of the rectangle to invalidate.
8837     * @param top The top coordinate of the rectangle to invalidate.
8838     * @param right The right coordinate of the rectangle to invalidate.
8839     * @param bottom The bottom coordinate of the rectangle to invalidate.
8840     */
8841    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
8842            int right, int bottom) {
8843
8844        // We try only with the AttachInfo because there's no point in invalidating
8845        // if we are not attached to our window
8846        AttachInfo attachInfo = mAttachInfo;
8847        if (attachInfo != null) {
8848            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
8849            info.target = this;
8850            info.left = left;
8851            info.top = top;
8852            info.right = right;
8853            info.bottom = bottom;
8854
8855            final Message msg = Message.obtain();
8856            msg.what = AttachInfo.INVALIDATE_RECT_MSG;
8857            msg.obj = info;
8858            attachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
8859        }
8860    }
8861
8862    /**
8863     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
8864     * This event is sent at most once every
8865     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
8866     */
8867    private void postSendViewScrolledAccessibilityEventCallback() {
8868        if (mSendViewScrolledAccessibilityEvent == null) {
8869            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
8870        }
8871        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
8872            mSendViewScrolledAccessibilityEvent.mIsPending = true;
8873            postDelayed(mSendViewScrolledAccessibilityEvent,
8874                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
8875        }
8876    }
8877
8878    /**
8879     * Called by a parent to request that a child update its values for mScrollX
8880     * and mScrollY if necessary. This will typically be done if the child is
8881     * animating a scroll using a {@link android.widget.Scroller Scroller}
8882     * object.
8883     */
8884    public void computeScroll() {
8885    }
8886
8887    /**
8888     * <p>Indicate whether the horizontal edges are faded when the view is
8889     * scrolled horizontally.</p>
8890     *
8891     * @return true if the horizontal edges should are faded on scroll, false
8892     *         otherwise
8893     *
8894     * @see #setHorizontalFadingEdgeEnabled(boolean)
8895     * @attr ref android.R.styleable#View_requiresFadingEdge
8896     */
8897    public boolean isHorizontalFadingEdgeEnabled() {
8898        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
8899    }
8900
8901    /**
8902     * <p>Define whether the horizontal edges should be faded when this view
8903     * is scrolled horizontally.</p>
8904     *
8905     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
8906     *                                    be faded when the view is scrolled
8907     *                                    horizontally
8908     *
8909     * @see #isHorizontalFadingEdgeEnabled()
8910     * @attr ref android.R.styleable#View_requiresFadingEdge
8911     */
8912    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
8913        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
8914            if (horizontalFadingEdgeEnabled) {
8915                initScrollCache();
8916            }
8917
8918            mViewFlags ^= FADING_EDGE_HORIZONTAL;
8919        }
8920    }
8921
8922    /**
8923     * <p>Indicate whether the vertical edges are faded when the view is
8924     * scrolled horizontally.</p>
8925     *
8926     * @return true if the vertical edges should are faded on scroll, false
8927     *         otherwise
8928     *
8929     * @see #setVerticalFadingEdgeEnabled(boolean)
8930     * @attr ref android.R.styleable#View_requiresFadingEdge
8931     */
8932    public boolean isVerticalFadingEdgeEnabled() {
8933        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
8934    }
8935
8936    /**
8937     * <p>Define whether the vertical edges should be faded when this view
8938     * is scrolled vertically.</p>
8939     *
8940     * @param verticalFadingEdgeEnabled true if the vertical edges should
8941     *                                  be faded when the view is scrolled
8942     *                                  vertically
8943     *
8944     * @see #isVerticalFadingEdgeEnabled()
8945     * @attr ref android.R.styleable#View_requiresFadingEdge
8946     */
8947    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
8948        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
8949            if (verticalFadingEdgeEnabled) {
8950                initScrollCache();
8951            }
8952
8953            mViewFlags ^= FADING_EDGE_VERTICAL;
8954        }
8955    }
8956
8957    /**
8958     * Returns the strength, or intensity, of the top faded edge. The strength is
8959     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8960     * returns 0.0 or 1.0 but no value in between.
8961     *
8962     * Subclasses should override this method to provide a smoother fade transition
8963     * when scrolling occurs.
8964     *
8965     * @return the intensity of the top fade as a float between 0.0f and 1.0f
8966     */
8967    protected float getTopFadingEdgeStrength() {
8968        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
8969    }
8970
8971    /**
8972     * Returns the strength, or intensity, of the bottom faded edge. The strength is
8973     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8974     * returns 0.0 or 1.0 but no value in between.
8975     *
8976     * Subclasses should override this method to provide a smoother fade transition
8977     * when scrolling occurs.
8978     *
8979     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
8980     */
8981    protected float getBottomFadingEdgeStrength() {
8982        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
8983                computeVerticalScrollRange() ? 1.0f : 0.0f;
8984    }
8985
8986    /**
8987     * Returns the strength, or intensity, of the left faded edge. The strength is
8988     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
8989     * returns 0.0 or 1.0 but no value in between.
8990     *
8991     * Subclasses should override this method to provide a smoother fade transition
8992     * when scrolling occurs.
8993     *
8994     * @return the intensity of the left fade as a float between 0.0f and 1.0f
8995     */
8996    protected float getLeftFadingEdgeStrength() {
8997        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
8998    }
8999
9000    /**
9001     * Returns the strength, or intensity, of the right faded edge. The strength is
9002     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9003     * returns 0.0 or 1.0 but no value in between.
9004     *
9005     * Subclasses should override this method to provide a smoother fade transition
9006     * when scrolling occurs.
9007     *
9008     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9009     */
9010    protected float getRightFadingEdgeStrength() {
9011        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9012                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9013    }
9014
9015    /**
9016     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9017     * scrollbar is not drawn by default.</p>
9018     *
9019     * @return true if the horizontal scrollbar should be painted, false
9020     *         otherwise
9021     *
9022     * @see #setHorizontalScrollBarEnabled(boolean)
9023     */
9024    public boolean isHorizontalScrollBarEnabled() {
9025        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9026    }
9027
9028    /**
9029     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9030     * scrollbar is not drawn by default.</p>
9031     *
9032     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9033     *                                   be painted
9034     *
9035     * @see #isHorizontalScrollBarEnabled()
9036     */
9037    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9038        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9039            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9040            computeOpaqueFlags();
9041            resolvePadding();
9042        }
9043    }
9044
9045    /**
9046     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9047     * scrollbar is not drawn by default.</p>
9048     *
9049     * @return true if the vertical scrollbar should be painted, false
9050     *         otherwise
9051     *
9052     * @see #setVerticalScrollBarEnabled(boolean)
9053     */
9054    public boolean isVerticalScrollBarEnabled() {
9055        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9056    }
9057
9058    /**
9059     * <p>Define whether the vertical scrollbar should be drawn or not. The
9060     * scrollbar is not drawn by default.</p>
9061     *
9062     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9063     *                                 be painted
9064     *
9065     * @see #isVerticalScrollBarEnabled()
9066     */
9067    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9068        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9069            mViewFlags ^= SCROLLBARS_VERTICAL;
9070            computeOpaqueFlags();
9071            resolvePadding();
9072        }
9073    }
9074
9075    /**
9076     * @hide
9077     */
9078    protected void recomputePadding() {
9079        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9080    }
9081
9082    /**
9083     * Define whether scrollbars will fade when the view is not scrolling.
9084     *
9085     * @param fadeScrollbars wheter to enable fading
9086     *
9087     */
9088    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9089        initScrollCache();
9090        final ScrollabilityCache scrollabilityCache = mScrollCache;
9091        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9092        if (fadeScrollbars) {
9093            scrollabilityCache.state = ScrollabilityCache.OFF;
9094        } else {
9095            scrollabilityCache.state = ScrollabilityCache.ON;
9096        }
9097    }
9098
9099    /**
9100     *
9101     * Returns true if scrollbars will fade when this view is not scrolling
9102     *
9103     * @return true if scrollbar fading is enabled
9104     */
9105    public boolean isScrollbarFadingEnabled() {
9106        return mScrollCache != null && mScrollCache.fadeScrollBars;
9107    }
9108
9109    /**
9110     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9111     * inset. When inset, they add to the padding of the view. And the scrollbars
9112     * can be drawn inside the padding area or on the edge of the view. For example,
9113     * if a view has a background drawable and you want to draw the scrollbars
9114     * inside the padding specified by the drawable, you can use
9115     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9116     * appear at the edge of the view, ignoring the padding, then you can use
9117     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9118     * @param style the style of the scrollbars. Should be one of
9119     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9120     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9121     * @see #SCROLLBARS_INSIDE_OVERLAY
9122     * @see #SCROLLBARS_INSIDE_INSET
9123     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9124     * @see #SCROLLBARS_OUTSIDE_INSET
9125     */
9126    public void setScrollBarStyle(int style) {
9127        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9128            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9129            computeOpaqueFlags();
9130            resolvePadding();
9131        }
9132    }
9133
9134    /**
9135     * <p>Returns the current scrollbar style.</p>
9136     * @return the current scrollbar style
9137     * @see #SCROLLBARS_INSIDE_OVERLAY
9138     * @see #SCROLLBARS_INSIDE_INSET
9139     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9140     * @see #SCROLLBARS_OUTSIDE_INSET
9141     */
9142    @ViewDebug.ExportedProperty(mapping = {
9143            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9144            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9145            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9146            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9147    })
9148    public int getScrollBarStyle() {
9149        return mViewFlags & SCROLLBARS_STYLE_MASK;
9150    }
9151
9152    /**
9153     * <p>Compute the horizontal range that the horizontal scrollbar
9154     * represents.</p>
9155     *
9156     * <p>The range is expressed in arbitrary units that must be the same as the
9157     * units used by {@link #computeHorizontalScrollExtent()} and
9158     * {@link #computeHorizontalScrollOffset()}.</p>
9159     *
9160     * <p>The default range is the drawing width of this view.</p>
9161     *
9162     * @return the total horizontal range represented by the horizontal
9163     *         scrollbar
9164     *
9165     * @see #computeHorizontalScrollExtent()
9166     * @see #computeHorizontalScrollOffset()
9167     * @see android.widget.ScrollBarDrawable
9168     */
9169    protected int computeHorizontalScrollRange() {
9170        return getWidth();
9171    }
9172
9173    /**
9174     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9175     * within the horizontal range. This value is used to compute the position
9176     * of the thumb within the scrollbar's track.</p>
9177     *
9178     * <p>The range is expressed in arbitrary units that must be the same as the
9179     * units used by {@link #computeHorizontalScrollRange()} and
9180     * {@link #computeHorizontalScrollExtent()}.</p>
9181     *
9182     * <p>The default offset is the scroll offset of this view.</p>
9183     *
9184     * @return the horizontal offset of the scrollbar's thumb
9185     *
9186     * @see #computeHorizontalScrollRange()
9187     * @see #computeHorizontalScrollExtent()
9188     * @see android.widget.ScrollBarDrawable
9189     */
9190    protected int computeHorizontalScrollOffset() {
9191        return mScrollX;
9192    }
9193
9194    /**
9195     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9196     * within the horizontal range. This value is used to compute the length
9197     * of the thumb within the scrollbar's track.</p>
9198     *
9199     * <p>The range is expressed in arbitrary units that must be the same as the
9200     * units used by {@link #computeHorizontalScrollRange()} and
9201     * {@link #computeHorizontalScrollOffset()}.</p>
9202     *
9203     * <p>The default extent is the drawing width of this view.</p>
9204     *
9205     * @return the horizontal extent of the scrollbar's thumb
9206     *
9207     * @see #computeHorizontalScrollRange()
9208     * @see #computeHorizontalScrollOffset()
9209     * @see android.widget.ScrollBarDrawable
9210     */
9211    protected int computeHorizontalScrollExtent() {
9212        return getWidth();
9213    }
9214
9215    /**
9216     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9217     *
9218     * <p>The range is expressed in arbitrary units that must be the same as the
9219     * units used by {@link #computeVerticalScrollExtent()} and
9220     * {@link #computeVerticalScrollOffset()}.</p>
9221     *
9222     * @return the total vertical range represented by the vertical scrollbar
9223     *
9224     * <p>The default range is the drawing height of this view.</p>
9225     *
9226     * @see #computeVerticalScrollExtent()
9227     * @see #computeVerticalScrollOffset()
9228     * @see android.widget.ScrollBarDrawable
9229     */
9230    protected int computeVerticalScrollRange() {
9231        return getHeight();
9232    }
9233
9234    /**
9235     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9236     * within the horizontal range. This value is used to compute the position
9237     * of the thumb within the scrollbar's track.</p>
9238     *
9239     * <p>The range is expressed in arbitrary units that must be the same as the
9240     * units used by {@link #computeVerticalScrollRange()} and
9241     * {@link #computeVerticalScrollExtent()}.</p>
9242     *
9243     * <p>The default offset is the scroll offset of this view.</p>
9244     *
9245     * @return the vertical offset of the scrollbar's thumb
9246     *
9247     * @see #computeVerticalScrollRange()
9248     * @see #computeVerticalScrollExtent()
9249     * @see android.widget.ScrollBarDrawable
9250     */
9251    protected int computeVerticalScrollOffset() {
9252        return mScrollY;
9253    }
9254
9255    /**
9256     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9257     * within the vertical range. This value is used to compute the length
9258     * of the thumb within the scrollbar's track.</p>
9259     *
9260     * <p>The range is expressed in arbitrary units that must be the same as the
9261     * units used by {@link #computeVerticalScrollRange()} and
9262     * {@link #computeVerticalScrollOffset()}.</p>
9263     *
9264     * <p>The default extent is the drawing height of this view.</p>
9265     *
9266     * @return the vertical extent of the scrollbar's thumb
9267     *
9268     * @see #computeVerticalScrollRange()
9269     * @see #computeVerticalScrollOffset()
9270     * @see android.widget.ScrollBarDrawable
9271     */
9272    protected int computeVerticalScrollExtent() {
9273        return getHeight();
9274    }
9275
9276    /**
9277     * Check if this view can be scrolled horizontally in a certain direction.
9278     *
9279     * @param direction Negative to check scrolling left, positive to check scrolling right.
9280     * @return true if this view can be scrolled in the specified direction, false otherwise.
9281     */
9282    public boolean canScrollHorizontally(int direction) {
9283        final int offset = computeHorizontalScrollOffset();
9284        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9285        if (range == 0) return false;
9286        if (direction < 0) {
9287            return offset > 0;
9288        } else {
9289            return offset < range - 1;
9290        }
9291    }
9292
9293    /**
9294     * Check if this view can be scrolled vertically in a certain direction.
9295     *
9296     * @param direction Negative to check scrolling up, positive to check scrolling down.
9297     * @return true if this view can be scrolled in the specified direction, false otherwise.
9298     */
9299    public boolean canScrollVertically(int direction) {
9300        final int offset = computeVerticalScrollOffset();
9301        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9302        if (range == 0) return false;
9303        if (direction < 0) {
9304            return offset > 0;
9305        } else {
9306            return offset < range - 1;
9307        }
9308    }
9309
9310    /**
9311     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9312     * scrollbars are painted only if they have been awakened first.</p>
9313     *
9314     * @param canvas the canvas on which to draw the scrollbars
9315     *
9316     * @see #awakenScrollBars(int)
9317     */
9318    protected final void onDrawScrollBars(Canvas canvas) {
9319        // scrollbars are drawn only when the animation is running
9320        final ScrollabilityCache cache = mScrollCache;
9321        if (cache != null) {
9322
9323            int state = cache.state;
9324
9325            if (state == ScrollabilityCache.OFF) {
9326                return;
9327            }
9328
9329            boolean invalidate = false;
9330
9331            if (state == ScrollabilityCache.FADING) {
9332                // We're fading -- get our fade interpolation
9333                if (cache.interpolatorValues == null) {
9334                    cache.interpolatorValues = new float[1];
9335                }
9336
9337                float[] values = cache.interpolatorValues;
9338
9339                // Stops the animation if we're done
9340                if (cache.scrollBarInterpolator.timeToValues(values) ==
9341                        Interpolator.Result.FREEZE_END) {
9342                    cache.state = ScrollabilityCache.OFF;
9343                } else {
9344                    cache.scrollBar.setAlpha(Math.round(values[0]));
9345                }
9346
9347                // This will make the scroll bars inval themselves after
9348                // drawing. We only want this when we're fading so that
9349                // we prevent excessive redraws
9350                invalidate = true;
9351            } else {
9352                // We're just on -- but we may have been fading before so
9353                // reset alpha
9354                cache.scrollBar.setAlpha(255);
9355            }
9356
9357
9358            final int viewFlags = mViewFlags;
9359
9360            final boolean drawHorizontalScrollBar =
9361                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9362            final boolean drawVerticalScrollBar =
9363                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9364                && !isVerticalScrollBarHidden();
9365
9366            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9367                final int width = mRight - mLeft;
9368                final int height = mBottom - mTop;
9369
9370                final ScrollBarDrawable scrollBar = cache.scrollBar;
9371
9372                final int scrollX = mScrollX;
9373                final int scrollY = mScrollY;
9374                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9375
9376                int left, top, right, bottom;
9377
9378                if (drawHorizontalScrollBar) {
9379                    int size = scrollBar.getSize(false);
9380                    if (size <= 0) {
9381                        size = cache.scrollBarSize;
9382                    }
9383
9384                    scrollBar.setParameters(computeHorizontalScrollRange(),
9385                                            computeHorizontalScrollOffset(),
9386                                            computeHorizontalScrollExtent(), false);
9387                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9388                            getVerticalScrollbarWidth() : 0;
9389                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9390                    left = scrollX + (mPaddingLeft & inside);
9391                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9392                    bottom = top + size;
9393                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9394                    if (invalidate) {
9395                        invalidate(left, top, right, bottom);
9396                    }
9397                }
9398
9399                if (drawVerticalScrollBar) {
9400                    int size = scrollBar.getSize(true);
9401                    if (size <= 0) {
9402                        size = cache.scrollBarSize;
9403                    }
9404
9405                    scrollBar.setParameters(computeVerticalScrollRange(),
9406                                            computeVerticalScrollOffset(),
9407                                            computeVerticalScrollExtent(), true);
9408                    switch (mVerticalScrollbarPosition) {
9409                        default:
9410                        case SCROLLBAR_POSITION_DEFAULT:
9411                        case SCROLLBAR_POSITION_RIGHT:
9412                            left = scrollX + width - size - (mUserPaddingRight & inside);
9413                            break;
9414                        case SCROLLBAR_POSITION_LEFT:
9415                            left = scrollX + (mUserPaddingLeft & inside);
9416                            break;
9417                    }
9418                    top = scrollY + (mPaddingTop & inside);
9419                    right = left + size;
9420                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9421                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9422                    if (invalidate) {
9423                        invalidate(left, top, right, bottom);
9424                    }
9425                }
9426            }
9427        }
9428    }
9429
9430    /**
9431     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9432     * FastScroller is visible.
9433     * @return whether to temporarily hide the vertical scrollbar
9434     * @hide
9435     */
9436    protected boolean isVerticalScrollBarHidden() {
9437        return false;
9438    }
9439
9440    /**
9441     * <p>Draw the horizontal scrollbar if
9442     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9443     *
9444     * @param canvas the canvas on which to draw the scrollbar
9445     * @param scrollBar the scrollbar's drawable
9446     *
9447     * @see #isHorizontalScrollBarEnabled()
9448     * @see #computeHorizontalScrollRange()
9449     * @see #computeHorizontalScrollExtent()
9450     * @see #computeHorizontalScrollOffset()
9451     * @see android.widget.ScrollBarDrawable
9452     * @hide
9453     */
9454    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9455            int l, int t, int r, int b) {
9456        scrollBar.setBounds(l, t, r, b);
9457        scrollBar.draw(canvas);
9458    }
9459
9460    /**
9461     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9462     * returns true.</p>
9463     *
9464     * @param canvas the canvas on which to draw the scrollbar
9465     * @param scrollBar the scrollbar's drawable
9466     *
9467     * @see #isVerticalScrollBarEnabled()
9468     * @see #computeVerticalScrollRange()
9469     * @see #computeVerticalScrollExtent()
9470     * @see #computeVerticalScrollOffset()
9471     * @see android.widget.ScrollBarDrawable
9472     * @hide
9473     */
9474    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9475            int l, int t, int r, int b) {
9476        scrollBar.setBounds(l, t, r, b);
9477        scrollBar.draw(canvas);
9478    }
9479
9480    /**
9481     * Implement this to do your drawing.
9482     *
9483     * @param canvas the canvas on which the background will be drawn
9484     */
9485    protected void onDraw(Canvas canvas) {
9486    }
9487
9488    /*
9489     * Caller is responsible for calling requestLayout if necessary.
9490     * (This allows addViewInLayout to not request a new layout.)
9491     */
9492    void assignParent(ViewParent parent) {
9493        if (mParent == null) {
9494            mParent = parent;
9495        } else if (parent == null) {
9496            mParent = null;
9497        } else {
9498            throw new RuntimeException("view " + this + " being added, but"
9499                    + " it already has a parent");
9500        }
9501    }
9502
9503    /**
9504     * This is called when the view is attached to a window.  At this point it
9505     * has a Surface and will start drawing.  Note that this function is
9506     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9507     * however it may be called any time before the first onDraw -- including
9508     * before or after {@link #onMeasure(int, int)}.
9509     *
9510     * @see #onDetachedFromWindow()
9511     */
9512    protected void onAttachedToWindow() {
9513        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9514            mParent.requestTransparentRegion(this);
9515        }
9516        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9517            initialAwakenScrollBars();
9518            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9519        }
9520        jumpDrawablesToCurrentState();
9521        // Order is important here: LayoutDirection MUST be resolved before Padding
9522        // and TextDirection
9523        resolveLayoutDirectionIfNeeded();
9524        resolvePadding();
9525        resolveTextDirection();
9526        if (isFocused()) {
9527            InputMethodManager imm = InputMethodManager.peekInstance();
9528            imm.focusIn(this);
9529        }
9530    }
9531
9532    /**
9533     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9534     * that the parent directionality can and will be resolved before its children.
9535     */
9536    private void resolveLayoutDirectionIfNeeded() {
9537        // Do not resolve if it is not needed
9538        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9539
9540        // Clear any previous layout direction resolution
9541        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9542
9543        // Reset also TextDirection as a change into LayoutDirection may impact the selected
9544        // TextDirectionHeuristic
9545        resetResolvedTextDirection();
9546
9547        // Set resolved depending on layout direction
9548        switch (getLayoutDirection()) {
9549            case LAYOUT_DIRECTION_INHERIT:
9550                // We cannot do the resolution if there is no parent
9551                if (mParent == null) return;
9552
9553                // If this is root view, no need to look at parent's layout dir.
9554                if (mParent instanceof ViewGroup) {
9555                    ViewGroup viewGroup = ((ViewGroup) mParent);
9556
9557                    // Check if the parent view group can resolve
9558                    if (! viewGroup.canResolveLayoutDirection()) {
9559                        return;
9560                    }
9561                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9562                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9563                    }
9564                }
9565                break;
9566            case LAYOUT_DIRECTION_RTL:
9567                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9568                break;
9569            case LAYOUT_DIRECTION_LOCALE:
9570                if(isLayoutDirectionRtl(Locale.getDefault())) {
9571                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9572                }
9573                break;
9574            default:
9575                // Nothing to do, LTR by default
9576        }
9577
9578        // Set to resolved
9579        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9580    }
9581
9582    /**
9583     * @hide
9584     */
9585    protected void resolvePadding() {
9586        // If the user specified the absolute padding (either with android:padding or
9587        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9588        // use the default padding or the padding from the background drawable
9589        // (stored at this point in mPadding*)
9590        switch (getResolvedLayoutDirection()) {
9591            case LAYOUT_DIRECTION_RTL:
9592                // Start user padding override Right user padding. Otherwise, if Right user
9593                // padding is not defined, use the default Right padding. If Right user padding
9594                // is defined, just use it.
9595                if (mUserPaddingStart >= 0) {
9596                    mUserPaddingRight = mUserPaddingStart;
9597                } else if (mUserPaddingRight < 0) {
9598                    mUserPaddingRight = mPaddingRight;
9599                }
9600                if (mUserPaddingEnd >= 0) {
9601                    mUserPaddingLeft = mUserPaddingEnd;
9602                } else if (mUserPaddingLeft < 0) {
9603                    mUserPaddingLeft = mPaddingLeft;
9604                }
9605                break;
9606            case LAYOUT_DIRECTION_LTR:
9607            default:
9608                // Start user padding override Left user padding. Otherwise, if Left user
9609                // padding is not defined, use the default left padding. If Left user padding
9610                // is defined, just use it.
9611                if (mUserPaddingStart >= 0) {
9612                    mUserPaddingLeft = mUserPaddingStart;
9613                } else if (mUserPaddingLeft < 0) {
9614                    mUserPaddingLeft = mPaddingLeft;
9615                }
9616                if (mUserPaddingEnd >= 0) {
9617                    mUserPaddingRight = mUserPaddingEnd;
9618                } else if (mUserPaddingRight < 0) {
9619                    mUserPaddingRight = mPaddingRight;
9620                }
9621        }
9622
9623        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9624
9625        recomputePadding();
9626    }
9627
9628    /**
9629     * Return true if layout direction resolution can be done
9630     *
9631     * @hide
9632     */
9633    protected boolean canResolveLayoutDirection() {
9634        switch (getLayoutDirection()) {
9635            case LAYOUT_DIRECTION_INHERIT:
9636                return (mParent != null);
9637            default:
9638                return true;
9639        }
9640    }
9641
9642    /**
9643     * Reset the resolved layout direction.
9644     *
9645     * Subclasses need to override this method to clear cached information that depends on the
9646     * resolved layout direction, or to inform child views that inherit their layout direction.
9647     * Overrides must also call the superclass implementation at the start of their implementation.
9648     *
9649     * @hide
9650     */
9651    protected void resetResolvedLayoutDirection() {
9652        // Reset the current View resolution
9653        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9654    }
9655
9656    /**
9657     * Check if a Locale is corresponding to a RTL script.
9658     *
9659     * @param locale Locale to check
9660     * @return true if a Locale is corresponding to a RTL script.
9661     *
9662     * @hide
9663     */
9664    protected static boolean isLayoutDirectionRtl(Locale locale) {
9665        return (LocaleUtil.TEXT_LAYOUT_DIRECTION_RTL_DO_NOT_USE ==
9666                LocaleUtil.getLayoutDirectionFromLocale(locale));
9667    }
9668
9669    /**
9670     * This is called when the view is detached from a window.  At this point it
9671     * no longer has a surface for drawing.
9672     *
9673     * @see #onAttachedToWindow()
9674     */
9675    protected void onDetachedFromWindow() {
9676        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9677
9678        removeUnsetPressCallback();
9679        removeLongPressCallback();
9680        removePerformClickCallback();
9681        removeSendViewScrolledAccessibilityEventCallback();
9682
9683        destroyDrawingCache();
9684
9685        destroyLayer();
9686
9687        if (mDisplayList != null) {
9688            mDisplayList.invalidate();
9689        }
9690
9691        if (mAttachInfo != null) {
9692            mAttachInfo.mHandler.removeMessages(AttachInfo.INVALIDATE_MSG, this);
9693        }
9694
9695        mCurrentAnimation = null;
9696
9697        resetResolvedLayoutDirection();
9698        resetResolvedTextDirection();
9699    }
9700
9701    /**
9702     * @return The number of times this view has been attached to a window
9703     */
9704    protected int getWindowAttachCount() {
9705        return mWindowAttachCount;
9706    }
9707
9708    /**
9709     * Retrieve a unique token identifying the window this view is attached to.
9710     * @return Return the window's token for use in
9711     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
9712     */
9713    public IBinder getWindowToken() {
9714        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
9715    }
9716
9717    /**
9718     * Retrieve a unique token identifying the top-level "real" window of
9719     * the window that this view is attached to.  That is, this is like
9720     * {@link #getWindowToken}, except if the window this view in is a panel
9721     * window (attached to another containing window), then the token of
9722     * the containing window is returned instead.
9723     *
9724     * @return Returns the associated window token, either
9725     * {@link #getWindowToken()} or the containing window's token.
9726     */
9727    public IBinder getApplicationWindowToken() {
9728        AttachInfo ai = mAttachInfo;
9729        if (ai != null) {
9730            IBinder appWindowToken = ai.mPanelParentWindowToken;
9731            if (appWindowToken == null) {
9732                appWindowToken = ai.mWindowToken;
9733            }
9734            return appWindowToken;
9735        }
9736        return null;
9737    }
9738
9739    /**
9740     * Retrieve private session object this view hierarchy is using to
9741     * communicate with the window manager.
9742     * @return the session object to communicate with the window manager
9743     */
9744    /*package*/ IWindowSession getWindowSession() {
9745        return mAttachInfo != null ? mAttachInfo.mSession : null;
9746    }
9747
9748    /**
9749     * @param info the {@link android.view.View.AttachInfo} to associated with
9750     *        this view
9751     */
9752    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
9753        //System.out.println("Attached! " + this);
9754        mAttachInfo = info;
9755        mWindowAttachCount++;
9756        // We will need to evaluate the drawable state at least once.
9757        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
9758        if (mFloatingTreeObserver != null) {
9759            info.mTreeObserver.merge(mFloatingTreeObserver);
9760            mFloatingTreeObserver = null;
9761        }
9762        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
9763            mAttachInfo.mScrollContainers.add(this);
9764            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
9765        }
9766        performCollectViewAttributes(visibility);
9767        onAttachedToWindow();
9768
9769        ListenerInfo li = mListenerInfo;
9770        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9771                li != null ? li.mOnAttachStateChangeListeners : null;
9772        if (listeners != null && listeners.size() > 0) {
9773            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9774            // perform the dispatching. The iterator is a safe guard against listeners that
9775            // could mutate the list by calling the various add/remove methods. This prevents
9776            // the array from being modified while we iterate it.
9777            for (OnAttachStateChangeListener listener : listeners) {
9778                listener.onViewAttachedToWindow(this);
9779            }
9780        }
9781
9782        int vis = info.mWindowVisibility;
9783        if (vis != GONE) {
9784            onWindowVisibilityChanged(vis);
9785        }
9786        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
9787            // If nobody has evaluated the drawable state yet, then do it now.
9788            refreshDrawableState();
9789        }
9790    }
9791
9792    void dispatchDetachedFromWindow() {
9793        AttachInfo info = mAttachInfo;
9794        if (info != null) {
9795            int vis = info.mWindowVisibility;
9796            if (vis != GONE) {
9797                onWindowVisibilityChanged(GONE);
9798            }
9799        }
9800
9801        onDetachedFromWindow();
9802
9803        ListenerInfo li = mListenerInfo;
9804        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
9805                li != null ? li.mOnAttachStateChangeListeners : null;
9806        if (listeners != null && listeners.size() > 0) {
9807            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
9808            // perform the dispatching. The iterator is a safe guard against listeners that
9809            // could mutate the list by calling the various add/remove methods. This prevents
9810            // the array from being modified while we iterate it.
9811            for (OnAttachStateChangeListener listener : listeners) {
9812                listener.onViewDetachedFromWindow(this);
9813            }
9814        }
9815
9816        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
9817            mAttachInfo.mScrollContainers.remove(this);
9818            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
9819        }
9820
9821        mAttachInfo = null;
9822    }
9823
9824    /**
9825     * Store this view hierarchy's frozen state into the given container.
9826     *
9827     * @param container The SparseArray in which to save the view's state.
9828     *
9829     * @see #restoreHierarchyState(android.util.SparseArray)
9830     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9831     * @see #onSaveInstanceState()
9832     */
9833    public void saveHierarchyState(SparseArray<Parcelable> container) {
9834        dispatchSaveInstanceState(container);
9835    }
9836
9837    /**
9838     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
9839     * this view and its children. May be overridden to modify how freezing happens to a
9840     * view's children; for example, some views may want to not store state for their children.
9841     *
9842     * @param container The SparseArray in which to save the view's state.
9843     *
9844     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9845     * @see #saveHierarchyState(android.util.SparseArray)
9846     * @see #onSaveInstanceState()
9847     */
9848    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
9849        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
9850            mPrivateFlags &= ~SAVE_STATE_CALLED;
9851            Parcelable state = onSaveInstanceState();
9852            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9853                throw new IllegalStateException(
9854                        "Derived class did not call super.onSaveInstanceState()");
9855            }
9856            if (state != null) {
9857                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
9858                // + ": " + state);
9859                container.put(mID, state);
9860            }
9861        }
9862    }
9863
9864    /**
9865     * Hook allowing a view to generate a representation of its internal state
9866     * that can later be used to create a new instance with that same state.
9867     * This state should only contain information that is not persistent or can
9868     * not be reconstructed later. For example, you will never store your
9869     * current position on screen because that will be computed again when a
9870     * new instance of the view is placed in its view hierarchy.
9871     * <p>
9872     * Some examples of things you may store here: the current cursor position
9873     * in a text view (but usually not the text itself since that is stored in a
9874     * content provider or other persistent storage), the currently selected
9875     * item in a list view.
9876     *
9877     * @return Returns a Parcelable object containing the view's current dynamic
9878     *         state, or null if there is nothing interesting to save. The
9879     *         default implementation returns null.
9880     * @see #onRestoreInstanceState(android.os.Parcelable)
9881     * @see #saveHierarchyState(android.util.SparseArray)
9882     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9883     * @see #setSaveEnabled(boolean)
9884     */
9885    protected Parcelable onSaveInstanceState() {
9886        mPrivateFlags |= SAVE_STATE_CALLED;
9887        return BaseSavedState.EMPTY_STATE;
9888    }
9889
9890    /**
9891     * Restore this view hierarchy's frozen state from the given container.
9892     *
9893     * @param container The SparseArray which holds previously frozen states.
9894     *
9895     * @see #saveHierarchyState(android.util.SparseArray)
9896     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9897     * @see #onRestoreInstanceState(android.os.Parcelable)
9898     */
9899    public void restoreHierarchyState(SparseArray<Parcelable> container) {
9900        dispatchRestoreInstanceState(container);
9901    }
9902
9903    /**
9904     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
9905     * state for this view and its children. May be overridden to modify how restoring
9906     * happens to a view's children; for example, some views may want to not store state
9907     * for their children.
9908     *
9909     * @param container The SparseArray which holds previously saved state.
9910     *
9911     * @see #dispatchSaveInstanceState(android.util.SparseArray)
9912     * @see #restoreHierarchyState(android.util.SparseArray)
9913     * @see #onRestoreInstanceState(android.os.Parcelable)
9914     */
9915    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
9916        if (mID != NO_ID) {
9917            Parcelable state = container.get(mID);
9918            if (state != null) {
9919                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
9920                // + ": " + state);
9921                mPrivateFlags &= ~SAVE_STATE_CALLED;
9922                onRestoreInstanceState(state);
9923                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
9924                    throw new IllegalStateException(
9925                            "Derived class did not call super.onRestoreInstanceState()");
9926                }
9927            }
9928        }
9929    }
9930
9931    /**
9932     * Hook allowing a view to re-apply a representation of its internal state that had previously
9933     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
9934     * null state.
9935     *
9936     * @param state The frozen state that had previously been returned by
9937     *        {@link #onSaveInstanceState}.
9938     *
9939     * @see #onSaveInstanceState()
9940     * @see #restoreHierarchyState(android.util.SparseArray)
9941     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
9942     */
9943    protected void onRestoreInstanceState(Parcelable state) {
9944        mPrivateFlags |= SAVE_STATE_CALLED;
9945        if (state != BaseSavedState.EMPTY_STATE && state != null) {
9946            throw new IllegalArgumentException("Wrong state class, expecting View State but "
9947                    + "received " + state.getClass().toString() + " instead. This usually happens "
9948                    + "when two views of different type have the same id in the same hierarchy. "
9949                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
9950                    + "other views do not use the same id.");
9951        }
9952    }
9953
9954    /**
9955     * <p>Return the time at which the drawing of the view hierarchy started.</p>
9956     *
9957     * @return the drawing start time in milliseconds
9958     */
9959    public long getDrawingTime() {
9960        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
9961    }
9962
9963    /**
9964     * <p>Enables or disables the duplication of the parent's state into this view. When
9965     * duplication is enabled, this view gets its drawable state from its parent rather
9966     * than from its own internal properties.</p>
9967     *
9968     * <p>Note: in the current implementation, setting this property to true after the
9969     * view was added to a ViewGroup might have no effect at all. This property should
9970     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
9971     *
9972     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
9973     * property is enabled, an exception will be thrown.</p>
9974     *
9975     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
9976     * parent, these states should not be affected by this method.</p>
9977     *
9978     * @param enabled True to enable duplication of the parent's drawable state, false
9979     *                to disable it.
9980     *
9981     * @see #getDrawableState()
9982     * @see #isDuplicateParentStateEnabled()
9983     */
9984    public void setDuplicateParentStateEnabled(boolean enabled) {
9985        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
9986    }
9987
9988    /**
9989     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
9990     *
9991     * @return True if this view's drawable state is duplicated from the parent,
9992     *         false otherwise
9993     *
9994     * @see #getDrawableState()
9995     * @see #setDuplicateParentStateEnabled(boolean)
9996     */
9997    public boolean isDuplicateParentStateEnabled() {
9998        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
9999    }
10000
10001    /**
10002     * <p>Specifies the type of layer backing this view. The layer can be
10003     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10004     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10005     *
10006     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10007     * instance that controls how the layer is composed on screen. The following
10008     * properties of the paint are taken into account when composing the layer:</p>
10009     * <ul>
10010     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10011     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10012     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10013     * </ul>
10014     *
10015     * <p>If this view has an alpha value set to < 1.0 by calling
10016     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10017     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10018     * equivalent to setting a hardware layer on this view and providing a paint with
10019     * the desired alpha value.<p>
10020     *
10021     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10022     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10023     * for more information on when and how to use layers.</p>
10024     *
10025     * @param layerType The ype of layer to use with this view, must be one of
10026     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10027     *        {@link #LAYER_TYPE_HARDWARE}
10028     * @param paint The paint used to compose the layer. This argument is optional
10029     *        and can be null. It is ignored when the layer type is
10030     *        {@link #LAYER_TYPE_NONE}
10031     *
10032     * @see #getLayerType()
10033     * @see #LAYER_TYPE_NONE
10034     * @see #LAYER_TYPE_SOFTWARE
10035     * @see #LAYER_TYPE_HARDWARE
10036     * @see #setAlpha(float)
10037     *
10038     * @attr ref android.R.styleable#View_layerType
10039     */
10040    public void setLayerType(int layerType, Paint paint) {
10041        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10042            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10043                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10044        }
10045
10046        if (layerType == mLayerType) {
10047            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10048                mLayerPaint = paint == null ? new Paint() : paint;
10049                invalidateParentCaches();
10050                invalidate(true);
10051            }
10052            return;
10053        }
10054
10055        // Destroy any previous software drawing cache if needed
10056        switch (mLayerType) {
10057            case LAYER_TYPE_HARDWARE:
10058                destroyLayer();
10059                // fall through - non-accelerated views may use software layer mechanism instead
10060            case LAYER_TYPE_SOFTWARE:
10061                destroyDrawingCache();
10062                break;
10063            default:
10064                break;
10065        }
10066
10067        mLayerType = layerType;
10068        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10069        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10070        mLocalDirtyRect = layerDisabled ? null : new Rect();
10071
10072        invalidateParentCaches();
10073        invalidate(true);
10074    }
10075
10076    /**
10077     * Indicates whether this view has a static layer. A view with layer type
10078     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10079     * dynamic.
10080     */
10081    boolean hasStaticLayer() {
10082        return mLayerType == LAYER_TYPE_NONE;
10083    }
10084
10085    /**
10086     * Indicates what type of layer is currently associated with this view. By default
10087     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10088     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10089     * for more information on the different types of layers.
10090     *
10091     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10092     *         {@link #LAYER_TYPE_HARDWARE}
10093     *
10094     * @see #setLayerType(int, android.graphics.Paint)
10095     * @see #buildLayer()
10096     * @see #LAYER_TYPE_NONE
10097     * @see #LAYER_TYPE_SOFTWARE
10098     * @see #LAYER_TYPE_HARDWARE
10099     */
10100    public int getLayerType() {
10101        return mLayerType;
10102    }
10103
10104    /**
10105     * Forces this view's layer to be created and this view to be rendered
10106     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10107     * invoking this method will have no effect.
10108     *
10109     * This method can for instance be used to render a view into its layer before
10110     * starting an animation. If this view is complex, rendering into the layer
10111     * before starting the animation will avoid skipping frames.
10112     *
10113     * @throws IllegalStateException If this view is not attached to a window
10114     *
10115     * @see #setLayerType(int, android.graphics.Paint)
10116     */
10117    public void buildLayer() {
10118        if (mLayerType == LAYER_TYPE_NONE) return;
10119
10120        if (mAttachInfo == null) {
10121            throw new IllegalStateException("This view must be attached to a window first");
10122        }
10123
10124        switch (mLayerType) {
10125            case LAYER_TYPE_HARDWARE:
10126                if (mAttachInfo.mHardwareRenderer != null &&
10127                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10128                        mAttachInfo.mHardwareRenderer.validate()) {
10129                    getHardwareLayer();
10130                }
10131                break;
10132            case LAYER_TYPE_SOFTWARE:
10133                buildDrawingCache(true);
10134                break;
10135        }
10136    }
10137
10138    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10139    void flushLayer() {
10140        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10141            mHardwareLayer.flush();
10142        }
10143    }
10144
10145    /**
10146     * <p>Returns a hardware layer that can be used to draw this view again
10147     * without executing its draw method.</p>
10148     *
10149     * @return A HardwareLayer ready to render, or null if an error occurred.
10150     */
10151    HardwareLayer getHardwareLayer() {
10152        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10153                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10154            return null;
10155        }
10156
10157        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10158
10159        final int width = mRight - mLeft;
10160        final int height = mBottom - mTop;
10161
10162        if (width == 0 || height == 0) {
10163            return null;
10164        }
10165
10166        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10167            if (mHardwareLayer == null) {
10168                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10169                        width, height, isOpaque());
10170                mLocalDirtyRect.setEmpty();
10171            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10172                mHardwareLayer.resize(width, height);
10173                mLocalDirtyRect.setEmpty();
10174            }
10175
10176            // The layer is not valid if the underlying GPU resources cannot be allocated
10177            if (!mHardwareLayer.isValid()) {
10178                return null;
10179            }
10180
10181            HardwareCanvas currentCanvas = mAttachInfo.mHardwareCanvas;
10182            final HardwareCanvas canvas = mHardwareLayer.start(currentCanvas);
10183
10184            // Make sure all the GPU resources have been properly allocated
10185            if (canvas == null) {
10186                mHardwareLayer.end(currentCanvas);
10187                return null;
10188            }
10189
10190            mAttachInfo.mHardwareCanvas = canvas;
10191            try {
10192                canvas.setViewport(width, height);
10193                canvas.onPreDraw(mLocalDirtyRect);
10194                mLocalDirtyRect.setEmpty();
10195
10196                final int restoreCount = canvas.save();
10197
10198                computeScroll();
10199                canvas.translate(-mScrollX, -mScrollY);
10200
10201                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10202
10203                // Fast path for layouts with no backgrounds
10204                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10205                    mPrivateFlags &= ~DIRTY_MASK;
10206                    dispatchDraw(canvas);
10207                } else {
10208                    draw(canvas);
10209                }
10210
10211                canvas.restoreToCount(restoreCount);
10212            } finally {
10213                canvas.onPostDraw();
10214                mHardwareLayer.end(currentCanvas);
10215                mAttachInfo.mHardwareCanvas = currentCanvas;
10216            }
10217        }
10218
10219        return mHardwareLayer;
10220    }
10221
10222    /**
10223     * Destroys this View's hardware layer if possible.
10224     *
10225     * @return True if the layer was destroyed, false otherwise.
10226     *
10227     * @see #setLayerType(int, android.graphics.Paint)
10228     * @see #LAYER_TYPE_HARDWARE
10229     */
10230    boolean destroyLayer() {
10231        if (mHardwareLayer != null) {
10232            AttachInfo info = mAttachInfo;
10233            if (info != null && info.mHardwareRenderer != null &&
10234                    info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) {
10235                mHardwareLayer.destroy();
10236                mHardwareLayer = null;
10237
10238                invalidate(true);
10239                invalidateParentCaches();
10240            }
10241            return true;
10242        }
10243        return false;
10244    }
10245
10246    /**
10247     * Destroys all hardware rendering resources. This method is invoked
10248     * when the system needs to reclaim resources. Upon execution of this
10249     * method, you should free any OpenGL resources created by the view.
10250     *
10251     * Note: you <strong>must</strong> call
10252     * <code>super.destroyHardwareResources()</code> when overriding
10253     * this method.
10254     *
10255     * @hide
10256     */
10257    protected void destroyHardwareResources() {
10258        destroyLayer();
10259    }
10260
10261    /**
10262     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10263     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10264     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10265     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10266     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10267     * null.</p>
10268     *
10269     * <p>Enabling the drawing cache is similar to
10270     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10271     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10272     * drawing cache has no effect on rendering because the system uses a different mechanism
10273     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10274     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10275     * for information on how to enable software and hardware layers.</p>
10276     *
10277     * <p>This API can be used to manually generate
10278     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10279     * {@link #getDrawingCache()}.</p>
10280     *
10281     * @param enabled true to enable the drawing cache, false otherwise
10282     *
10283     * @see #isDrawingCacheEnabled()
10284     * @see #getDrawingCache()
10285     * @see #buildDrawingCache()
10286     * @see #setLayerType(int, android.graphics.Paint)
10287     */
10288    public void setDrawingCacheEnabled(boolean enabled) {
10289        mCachingFailed = false;
10290        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10291    }
10292
10293    /**
10294     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10295     *
10296     * @return true if the drawing cache is enabled
10297     *
10298     * @see #setDrawingCacheEnabled(boolean)
10299     * @see #getDrawingCache()
10300     */
10301    @ViewDebug.ExportedProperty(category = "drawing")
10302    public boolean isDrawingCacheEnabled() {
10303        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10304    }
10305
10306    /**
10307     * Debugging utility which recursively outputs the dirty state of a view and its
10308     * descendants.
10309     *
10310     * @hide
10311     */
10312    @SuppressWarnings({"UnusedDeclaration"})
10313    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10314        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10315                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10316                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10317                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10318        if (clear) {
10319            mPrivateFlags &= clearMask;
10320        }
10321        if (this instanceof ViewGroup) {
10322            ViewGroup parent = (ViewGroup) this;
10323            final int count = parent.getChildCount();
10324            for (int i = 0; i < count; i++) {
10325                final View child = parent.getChildAt(i);
10326                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10327            }
10328        }
10329    }
10330
10331    /**
10332     * This method is used by ViewGroup to cause its children to restore or recreate their
10333     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10334     * to recreate its own display list, which would happen if it went through the normal
10335     * draw/dispatchDraw mechanisms.
10336     *
10337     * @hide
10338     */
10339    protected void dispatchGetDisplayList() {}
10340
10341    /**
10342     * A view that is not attached or hardware accelerated cannot create a display list.
10343     * This method checks these conditions and returns the appropriate result.
10344     *
10345     * @return true if view has the ability to create a display list, false otherwise.
10346     *
10347     * @hide
10348     */
10349    public boolean canHaveDisplayList() {
10350        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10351    }
10352
10353    /**
10354     * @return The HardwareRenderer associated with that view or null if hardware rendering
10355     * is not supported or this this has not been attached to a window.
10356     *
10357     * @hide
10358     */
10359    public HardwareRenderer getHardwareRenderer() {
10360        if (mAttachInfo != null) {
10361            return mAttachInfo.mHardwareRenderer;
10362        }
10363        return null;
10364    }
10365
10366    /**
10367     * <p>Returns a display list that can be used to draw this view again
10368     * without executing its draw method.</p>
10369     *
10370     * @return A DisplayList ready to replay, or null if caching is not enabled.
10371     *
10372     * @hide
10373     */
10374    public DisplayList getDisplayList() {
10375        if (!canHaveDisplayList()) {
10376            return null;
10377        }
10378
10379        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10380                mDisplayList == null || !mDisplayList.isValid() ||
10381                mRecreateDisplayList)) {
10382            // Don't need to recreate the display list, just need to tell our
10383            // children to restore/recreate theirs
10384            if (mDisplayList != null && mDisplayList.isValid() &&
10385                    !mRecreateDisplayList) {
10386                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10387                mPrivateFlags &= ~DIRTY_MASK;
10388                dispatchGetDisplayList();
10389
10390                return mDisplayList;
10391            }
10392
10393            // If we got here, we're recreating it. Mark it as such to ensure that
10394            // we copy in child display lists into ours in drawChild()
10395            mRecreateDisplayList = true;
10396            if (mDisplayList == null) {
10397                final String name = getClass().getSimpleName();
10398                mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
10399                // If we're creating a new display list, make sure our parent gets invalidated
10400                // since they will need to recreate their display list to account for this
10401                // new child display list.
10402                invalidateParentCaches();
10403            }
10404
10405            final HardwareCanvas canvas = mDisplayList.start();
10406            int restoreCount = 0;
10407            try {
10408                int width = mRight - mLeft;
10409                int height = mBottom - mTop;
10410
10411                canvas.setViewport(width, height);
10412                // The dirty rect should always be null for a display list
10413                canvas.onPreDraw(null);
10414
10415                computeScroll();
10416
10417                restoreCount = canvas.save();
10418                canvas.translate(-mScrollX, -mScrollY);
10419                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10420                mPrivateFlags &= ~DIRTY_MASK;
10421
10422                // Fast path for layouts with no backgrounds
10423                if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10424                    dispatchDraw(canvas);
10425                } else {
10426                    draw(canvas);
10427                }
10428            } finally {
10429                canvas.restoreToCount(restoreCount);
10430                canvas.onPostDraw();
10431
10432                mDisplayList.end();
10433            }
10434        } else {
10435            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10436            mPrivateFlags &= ~DIRTY_MASK;
10437        }
10438
10439        return mDisplayList;
10440    }
10441
10442    /**
10443     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10444     *
10445     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10446     *
10447     * @see #getDrawingCache(boolean)
10448     */
10449    public Bitmap getDrawingCache() {
10450        return getDrawingCache(false);
10451    }
10452
10453    /**
10454     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10455     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10456     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10457     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10458     * request the drawing cache by calling this method and draw it on screen if the
10459     * returned bitmap is not null.</p>
10460     *
10461     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10462     * this method will create a bitmap of the same size as this view. Because this bitmap
10463     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10464     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10465     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10466     * size than the view. This implies that your application must be able to handle this
10467     * size.</p>
10468     *
10469     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10470     *        the current density of the screen when the application is in compatibility
10471     *        mode.
10472     *
10473     * @return A bitmap representing this view or null if cache is disabled.
10474     *
10475     * @see #setDrawingCacheEnabled(boolean)
10476     * @see #isDrawingCacheEnabled()
10477     * @see #buildDrawingCache(boolean)
10478     * @see #destroyDrawingCache()
10479     */
10480    public Bitmap getDrawingCache(boolean autoScale) {
10481        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10482            return null;
10483        }
10484        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10485            buildDrawingCache(autoScale);
10486        }
10487        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10488    }
10489
10490    /**
10491     * <p>Frees the resources used by the drawing cache. If you call
10492     * {@link #buildDrawingCache()} manually without calling
10493     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10494     * should cleanup the cache with this method afterwards.</p>
10495     *
10496     * @see #setDrawingCacheEnabled(boolean)
10497     * @see #buildDrawingCache()
10498     * @see #getDrawingCache()
10499     */
10500    public void destroyDrawingCache() {
10501        if (mDrawingCache != null) {
10502            mDrawingCache.recycle();
10503            mDrawingCache = null;
10504        }
10505        if (mUnscaledDrawingCache != null) {
10506            mUnscaledDrawingCache.recycle();
10507            mUnscaledDrawingCache = null;
10508        }
10509    }
10510
10511    /**
10512     * Setting a solid background color for the drawing cache's bitmaps will improve
10513     * performance and memory usage. Note, though that this should only be used if this
10514     * view will always be drawn on top of a solid color.
10515     *
10516     * @param color The background color to use for the drawing cache's bitmap
10517     *
10518     * @see #setDrawingCacheEnabled(boolean)
10519     * @see #buildDrawingCache()
10520     * @see #getDrawingCache()
10521     */
10522    public void setDrawingCacheBackgroundColor(int color) {
10523        if (color != mDrawingCacheBackgroundColor) {
10524            mDrawingCacheBackgroundColor = color;
10525            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10526        }
10527    }
10528
10529    /**
10530     * @see #setDrawingCacheBackgroundColor(int)
10531     *
10532     * @return The background color to used for the drawing cache's bitmap
10533     */
10534    public int getDrawingCacheBackgroundColor() {
10535        return mDrawingCacheBackgroundColor;
10536    }
10537
10538    /**
10539     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10540     *
10541     * @see #buildDrawingCache(boolean)
10542     */
10543    public void buildDrawingCache() {
10544        buildDrawingCache(false);
10545    }
10546
10547    /**
10548     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10549     *
10550     * <p>If you call {@link #buildDrawingCache()} manually without calling
10551     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10552     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10553     *
10554     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10555     * this method will create a bitmap of the same size as this view. Because this bitmap
10556     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10557     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10558     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10559     * size than the view. This implies that your application must be able to handle this
10560     * size.</p>
10561     *
10562     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10563     * you do not need the drawing cache bitmap, calling this method will increase memory
10564     * usage and cause the view to be rendered in software once, thus negatively impacting
10565     * performance.</p>
10566     *
10567     * @see #getDrawingCache()
10568     * @see #destroyDrawingCache()
10569     */
10570    public void buildDrawingCache(boolean autoScale) {
10571        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10572                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10573            mCachingFailed = false;
10574
10575            if (ViewDebug.TRACE_HIERARCHY) {
10576                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10577            }
10578
10579            int width = mRight - mLeft;
10580            int height = mBottom - mTop;
10581
10582            final AttachInfo attachInfo = mAttachInfo;
10583            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10584
10585            if (autoScale && scalingRequired) {
10586                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10587                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10588            }
10589
10590            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10591            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10592            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10593
10594            if (width <= 0 || height <= 0 ||
10595                     // Projected bitmap size in bytes
10596                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10597                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10598                destroyDrawingCache();
10599                mCachingFailed = true;
10600                return;
10601            }
10602
10603            boolean clear = true;
10604            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10605
10606            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10607                Bitmap.Config quality;
10608                if (!opaque) {
10609                    // Never pick ARGB_4444 because it looks awful
10610                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10611                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10612                        case DRAWING_CACHE_QUALITY_AUTO:
10613                            quality = Bitmap.Config.ARGB_8888;
10614                            break;
10615                        case DRAWING_CACHE_QUALITY_LOW:
10616                            quality = Bitmap.Config.ARGB_8888;
10617                            break;
10618                        case DRAWING_CACHE_QUALITY_HIGH:
10619                            quality = Bitmap.Config.ARGB_8888;
10620                            break;
10621                        default:
10622                            quality = Bitmap.Config.ARGB_8888;
10623                            break;
10624                    }
10625                } else {
10626                    // Optimization for translucent windows
10627                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10628                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10629                }
10630
10631                // Try to cleanup memory
10632                if (bitmap != null) bitmap.recycle();
10633
10634                try {
10635                    bitmap = Bitmap.createBitmap(width, height, quality);
10636                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10637                    if (autoScale) {
10638                        mDrawingCache = bitmap;
10639                    } else {
10640                        mUnscaledDrawingCache = bitmap;
10641                    }
10642                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10643                } catch (OutOfMemoryError e) {
10644                    // If there is not enough memory to create the bitmap cache, just
10645                    // ignore the issue as bitmap caches are not required to draw the
10646                    // view hierarchy
10647                    if (autoScale) {
10648                        mDrawingCache = null;
10649                    } else {
10650                        mUnscaledDrawingCache = null;
10651                    }
10652                    mCachingFailed = true;
10653                    return;
10654                }
10655
10656                clear = drawingCacheBackgroundColor != 0;
10657            }
10658
10659            Canvas canvas;
10660            if (attachInfo != null) {
10661                canvas = attachInfo.mCanvas;
10662                if (canvas == null) {
10663                    canvas = new Canvas();
10664                }
10665                canvas.setBitmap(bitmap);
10666                // Temporarily clobber the cached Canvas in case one of our children
10667                // is also using a drawing cache. Without this, the children would
10668                // steal the canvas by attaching their own bitmap to it and bad, bad
10669                // thing would happen (invisible views, corrupted drawings, etc.)
10670                attachInfo.mCanvas = null;
10671            } else {
10672                // This case should hopefully never or seldom happen
10673                canvas = new Canvas(bitmap);
10674            }
10675
10676            if (clear) {
10677                bitmap.eraseColor(drawingCacheBackgroundColor);
10678            }
10679
10680            computeScroll();
10681            final int restoreCount = canvas.save();
10682
10683            if (autoScale && scalingRequired) {
10684                final float scale = attachInfo.mApplicationScale;
10685                canvas.scale(scale, scale);
10686            }
10687
10688            canvas.translate(-mScrollX, -mScrollY);
10689
10690            mPrivateFlags |= DRAWN;
10691            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
10692                    mLayerType != LAYER_TYPE_NONE) {
10693                mPrivateFlags |= DRAWING_CACHE_VALID;
10694            }
10695
10696            // Fast path for layouts with no backgrounds
10697            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10698                if (ViewDebug.TRACE_HIERARCHY) {
10699                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
10700                }
10701                mPrivateFlags &= ~DIRTY_MASK;
10702                dispatchDraw(canvas);
10703            } else {
10704                draw(canvas);
10705            }
10706
10707            canvas.restoreToCount(restoreCount);
10708            canvas.setBitmap(null);
10709
10710            if (attachInfo != null) {
10711                // Restore the cached Canvas for our siblings
10712                attachInfo.mCanvas = canvas;
10713            }
10714        }
10715    }
10716
10717    /**
10718     * Create a snapshot of the view into a bitmap.  We should probably make
10719     * some form of this public, but should think about the API.
10720     */
10721    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
10722        int width = mRight - mLeft;
10723        int height = mBottom - mTop;
10724
10725        final AttachInfo attachInfo = mAttachInfo;
10726        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
10727        width = (int) ((width * scale) + 0.5f);
10728        height = (int) ((height * scale) + 0.5f);
10729
10730        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
10731        if (bitmap == null) {
10732            throw new OutOfMemoryError();
10733        }
10734
10735        Resources resources = getResources();
10736        if (resources != null) {
10737            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
10738        }
10739
10740        Canvas canvas;
10741        if (attachInfo != null) {
10742            canvas = attachInfo.mCanvas;
10743            if (canvas == null) {
10744                canvas = new Canvas();
10745            }
10746            canvas.setBitmap(bitmap);
10747            // Temporarily clobber the cached Canvas in case one of our children
10748            // is also using a drawing cache. Without this, the children would
10749            // steal the canvas by attaching their own bitmap to it and bad, bad
10750            // things would happen (invisible views, corrupted drawings, etc.)
10751            attachInfo.mCanvas = null;
10752        } else {
10753            // This case should hopefully never or seldom happen
10754            canvas = new Canvas(bitmap);
10755        }
10756
10757        if ((backgroundColor & 0xff000000) != 0) {
10758            bitmap.eraseColor(backgroundColor);
10759        }
10760
10761        computeScroll();
10762        final int restoreCount = canvas.save();
10763        canvas.scale(scale, scale);
10764        canvas.translate(-mScrollX, -mScrollY);
10765
10766        // Temporarily remove the dirty mask
10767        int flags = mPrivateFlags;
10768        mPrivateFlags &= ~DIRTY_MASK;
10769
10770        // Fast path for layouts with no backgrounds
10771        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10772            dispatchDraw(canvas);
10773        } else {
10774            draw(canvas);
10775        }
10776
10777        mPrivateFlags = flags;
10778
10779        canvas.restoreToCount(restoreCount);
10780        canvas.setBitmap(null);
10781
10782        if (attachInfo != null) {
10783            // Restore the cached Canvas for our siblings
10784            attachInfo.mCanvas = canvas;
10785        }
10786
10787        return bitmap;
10788    }
10789
10790    /**
10791     * Indicates whether this View is currently in edit mode. A View is usually
10792     * in edit mode when displayed within a developer tool. For instance, if
10793     * this View is being drawn by a visual user interface builder, this method
10794     * should return true.
10795     *
10796     * Subclasses should check the return value of this method to provide
10797     * different behaviors if their normal behavior might interfere with the
10798     * host environment. For instance: the class spawns a thread in its
10799     * constructor, the drawing code relies on device-specific features, etc.
10800     *
10801     * This method is usually checked in the drawing code of custom widgets.
10802     *
10803     * @return True if this View is in edit mode, false otherwise.
10804     */
10805    public boolean isInEditMode() {
10806        return false;
10807    }
10808
10809    /**
10810     * If the View draws content inside its padding and enables fading edges,
10811     * it needs to support padding offsets. Padding offsets are added to the
10812     * fading edges to extend the length of the fade so that it covers pixels
10813     * drawn inside the padding.
10814     *
10815     * Subclasses of this class should override this method if they need
10816     * to draw content inside the padding.
10817     *
10818     * @return True if padding offset must be applied, false otherwise.
10819     *
10820     * @see #getLeftPaddingOffset()
10821     * @see #getRightPaddingOffset()
10822     * @see #getTopPaddingOffset()
10823     * @see #getBottomPaddingOffset()
10824     *
10825     * @since CURRENT
10826     */
10827    protected boolean isPaddingOffsetRequired() {
10828        return false;
10829    }
10830
10831    /**
10832     * Amount by which to extend the left fading region. Called only when
10833     * {@link #isPaddingOffsetRequired()} returns true.
10834     *
10835     * @return The left padding offset in pixels.
10836     *
10837     * @see #isPaddingOffsetRequired()
10838     *
10839     * @since CURRENT
10840     */
10841    protected int getLeftPaddingOffset() {
10842        return 0;
10843    }
10844
10845    /**
10846     * Amount by which to extend the right fading region. Called only when
10847     * {@link #isPaddingOffsetRequired()} returns true.
10848     *
10849     * @return The right padding offset in pixels.
10850     *
10851     * @see #isPaddingOffsetRequired()
10852     *
10853     * @since CURRENT
10854     */
10855    protected int getRightPaddingOffset() {
10856        return 0;
10857    }
10858
10859    /**
10860     * Amount by which to extend the top fading region. Called only when
10861     * {@link #isPaddingOffsetRequired()} returns true.
10862     *
10863     * @return The top padding offset in pixels.
10864     *
10865     * @see #isPaddingOffsetRequired()
10866     *
10867     * @since CURRENT
10868     */
10869    protected int getTopPaddingOffset() {
10870        return 0;
10871    }
10872
10873    /**
10874     * Amount by which to extend the bottom fading region. Called only when
10875     * {@link #isPaddingOffsetRequired()} returns true.
10876     *
10877     * @return The bottom padding offset in pixels.
10878     *
10879     * @see #isPaddingOffsetRequired()
10880     *
10881     * @since CURRENT
10882     */
10883    protected int getBottomPaddingOffset() {
10884        return 0;
10885    }
10886
10887    /**
10888     * @hide
10889     * @param offsetRequired
10890     */
10891    protected int getFadeTop(boolean offsetRequired) {
10892        int top = mPaddingTop;
10893        if (offsetRequired) top += getTopPaddingOffset();
10894        return top;
10895    }
10896
10897    /**
10898     * @hide
10899     * @param offsetRequired
10900     */
10901    protected int getFadeHeight(boolean offsetRequired) {
10902        int padding = mPaddingTop;
10903        if (offsetRequired) padding += getTopPaddingOffset();
10904        return mBottom - mTop - mPaddingBottom - padding;
10905    }
10906
10907    /**
10908     * <p>Indicates whether this view is attached to an hardware accelerated
10909     * window or not.</p>
10910     *
10911     * <p>Even if this method returns true, it does not mean that every call
10912     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
10913     * accelerated {@link android.graphics.Canvas}. For instance, if this view
10914     * is drawn onto an offscren {@link android.graphics.Bitmap} and its
10915     * window is hardware accelerated,
10916     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
10917     * return false, and this method will return true.</p>
10918     *
10919     * @return True if the view is attached to a window and the window is
10920     *         hardware accelerated; false in any other case.
10921     */
10922    public boolean isHardwareAccelerated() {
10923        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
10924    }
10925
10926    /**
10927     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
10928     * case of an active Animation being run on the view.
10929     */
10930    private boolean drawAnimation(ViewGroup parent, long drawingTime,
10931            Animation a, boolean scalingRequired) {
10932        Transformation invalidationTransform;
10933        final int flags = parent.mGroupFlags;
10934        final boolean initialized = a.isInitialized();
10935        if (!initialized) {
10936            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
10937            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
10938            onAnimationStart();
10939        }
10940
10941        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
10942        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
10943            if (parent.mInvalidationTransformation == null) {
10944                parent.mInvalidationTransformation = new Transformation();
10945            }
10946            invalidationTransform = parent.mInvalidationTransformation;
10947            a.getTransformation(drawingTime, invalidationTransform, 1f);
10948        } else {
10949            invalidationTransform = parent.mChildTransformation;
10950        }
10951        if (more) {
10952            if (!a.willChangeBounds()) {
10953                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
10954                        parent.FLAG_OPTIMIZE_INVALIDATE) {
10955                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
10956                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
10957                    // The child need to draw an animation, potentially offscreen, so
10958                    // make sure we do not cancel invalidate requests
10959                    parent.mPrivateFlags |= DRAW_ANIMATION;
10960                    parent.invalidate(mLeft, mTop, mRight, mBottom);
10961                }
10962            } else {
10963                if (parent.mInvalidateRegion == null) {
10964                    parent.mInvalidateRegion = new RectF();
10965                }
10966                final RectF region = parent.mInvalidateRegion;
10967                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
10968                        invalidationTransform);
10969
10970                // The child need to draw an animation, potentially offscreen, so
10971                // make sure we do not cancel invalidate requests
10972                parent.mPrivateFlags |= DRAW_ANIMATION;
10973
10974                final int left = mLeft + (int) region.left;
10975                final int top = mTop + (int) region.top;
10976                parent.invalidate(left, top, left + (int) (region.width() + .5f),
10977                        top + (int) (region.height() + .5f));
10978            }
10979        }
10980        return more;
10981    }
10982
10983    /**
10984     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
10985     * This draw() method is an implementation detail and is not intended to be overridden or
10986     * to be called from anywhere else other than ViewGroup.drawChild().
10987     */
10988    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
10989        boolean more = false;
10990        final boolean childHasIdentityMatrix = hasIdentityMatrix();
10991        final int flags = parent.mGroupFlags;
10992
10993        if ((flags & parent.FLAG_CLEAR_TRANSFORMATION) == parent.FLAG_CLEAR_TRANSFORMATION) {
10994            parent.mChildTransformation.clear();
10995            parent.mGroupFlags &= ~parent.FLAG_CLEAR_TRANSFORMATION;
10996        }
10997
10998        Transformation transformToApply = null;
10999        boolean concatMatrix = false;
11000
11001        boolean scalingRequired = false;
11002        boolean caching;
11003        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
11004
11005        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11006        if ((flags & parent.FLAG_CHILDREN_DRAWN_WITH_CACHE) == parent.FLAG_CHILDREN_DRAWN_WITH_CACHE ||
11007                (flags & parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) == parent.FLAG_ALWAYS_DRAWN_WITH_CACHE) {
11008            caching = true;
11009            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11010        } else {
11011            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11012        }
11013
11014        final Animation a = getAnimation();
11015        if (a != null) {
11016            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11017            concatMatrix = a.willChangeTransformationMatrix();
11018            transformToApply = parent.mChildTransformation;
11019        } else if ((flags & parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
11020                parent.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) {
11021            final boolean hasTransform =
11022                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11023            if (hasTransform) {
11024                final int transformType = parent.mChildTransformation.getTransformationType();
11025                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11026                        parent.mChildTransformation : null;
11027                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11028            }
11029        }
11030
11031        concatMatrix |= !childHasIdentityMatrix;
11032
11033        // Sets the flag as early as possible to allow draw() implementations
11034        // to call invalidate() successfully when doing animations
11035        mPrivateFlags |= DRAWN;
11036
11037        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11038                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11039            return more;
11040        }
11041
11042        if (hardwareAccelerated) {
11043            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11044            // retain the flag's value temporarily in the mRecreateDisplayList flag
11045            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11046            mPrivateFlags &= ~INVALIDATED;
11047        }
11048
11049        computeScroll();
11050
11051        final int sx = mScrollX;
11052        final int sy = mScrollY;
11053
11054        DisplayList displayList = null;
11055        Bitmap cache = null;
11056        boolean hasDisplayList = false;
11057        if (caching) {
11058            if (!hardwareAccelerated) {
11059                if (layerType != LAYER_TYPE_NONE) {
11060                    layerType = LAYER_TYPE_SOFTWARE;
11061                    buildDrawingCache(true);
11062                }
11063                cache = getDrawingCache(true);
11064            } else {
11065                switch (layerType) {
11066                    case LAYER_TYPE_SOFTWARE:
11067                        buildDrawingCache(true);
11068                        cache = getDrawingCache(true);
11069                        break;
11070                    case LAYER_TYPE_NONE:
11071                        // Delay getting the display list until animation-driven alpha values are
11072                        // set up and possibly passed on to the view
11073                        hasDisplayList = canHaveDisplayList();
11074                        break;
11075                }
11076            }
11077        }
11078
11079        final boolean hasNoCache = cache == null || hasDisplayList;
11080        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11081                layerType != LAYER_TYPE_HARDWARE;
11082
11083        final int restoreTo = canvas.save();
11084        if (offsetForScroll) {
11085            canvas.translate(mLeft - sx, mTop - sy);
11086        } else {
11087            canvas.translate(mLeft, mTop);
11088            if (scalingRequired) {
11089                // mAttachInfo cannot be null, otherwise scalingRequired == false
11090                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11091                canvas.scale(scale, scale);
11092            }
11093        }
11094
11095        float alpha = getAlpha();
11096        if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) {
11097            if (transformToApply != null || !childHasIdentityMatrix) {
11098                int transX = 0;
11099                int transY = 0;
11100
11101                if (offsetForScroll) {
11102                    transX = -sx;
11103                    transY = -sy;
11104                }
11105
11106                if (transformToApply != null) {
11107                    if (concatMatrix) {
11108                        // Undo the scroll translation, apply the transformation matrix,
11109                        // then redo the scroll translate to get the correct result.
11110                        canvas.translate(-transX, -transY);
11111                        canvas.concat(transformToApply.getMatrix());
11112                        canvas.translate(transX, transY);
11113                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11114                    }
11115
11116                    float transformAlpha = transformToApply.getAlpha();
11117                    if (transformAlpha < 1.0f) {
11118                        alpha *= transformToApply.getAlpha();
11119                        parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11120                    }
11121                }
11122
11123                if (!childHasIdentityMatrix) {
11124                    canvas.translate(-transX, -transY);
11125                    canvas.concat(getMatrix());
11126                    canvas.translate(transX, transY);
11127                }
11128            }
11129
11130            if (alpha < 1.0f) {
11131                parent.mGroupFlags |= parent.FLAG_CLEAR_TRANSFORMATION;
11132                if (hasNoCache) {
11133                    final int multipliedAlpha = (int) (255 * alpha);
11134                    if (!onSetAlpha(multipliedAlpha)) {
11135                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11136                        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN ||
11137                                layerType != LAYER_TYPE_NONE) {
11138                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
11139                        }
11140                        if (layerType == LAYER_TYPE_NONE) {
11141                            final int scrollX = hasDisplayList ? 0 : sx;
11142                            final int scrollY = hasDisplayList ? 0 : sy;
11143                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
11144                                    scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
11145                        }
11146                    } else {
11147                        // Alpha is handled by the child directly, clobber the layer's alpha
11148                        mPrivateFlags |= ALPHA_SET;
11149                    }
11150                }
11151            }
11152        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11153            onSetAlpha(255);
11154            mPrivateFlags &= ~ALPHA_SET;
11155        }
11156
11157        if ((flags & parent.FLAG_CLIP_CHILDREN) == parent.FLAG_CLIP_CHILDREN) {
11158            if (offsetForScroll) {
11159                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
11160            } else {
11161                if (!scalingRequired || cache == null) {
11162                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
11163                } else {
11164                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
11165                }
11166            }
11167        }
11168
11169        if (hasDisplayList) {
11170            displayList = getDisplayList();
11171            if (!displayList.isValid()) {
11172                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11173                // to getDisplayList(), the display list will be marked invalid and we should not
11174                // try to use it again.
11175                displayList = null;
11176                hasDisplayList = false;
11177            }
11178        }
11179
11180        if (hasNoCache) {
11181            boolean layerRendered = false;
11182            if (layerType == LAYER_TYPE_HARDWARE) {
11183                final HardwareLayer layer = getHardwareLayer();
11184                if (layer != null && layer.isValid()) {
11185                    mLayerPaint.setAlpha((int) (alpha * 255));
11186                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
11187                    layerRendered = true;
11188                } else {
11189                    final int scrollX = hasDisplayList ? 0 : sx;
11190                    final int scrollY = hasDisplayList ? 0 : sy;
11191                    canvas.saveLayer(scrollX, scrollY,
11192                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
11193                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11194                }
11195            }
11196
11197            if (!layerRendered) {
11198                if (!hasDisplayList) {
11199                    // Fast path for layouts with no backgrounds
11200                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11201                        if (ViewDebug.TRACE_HIERARCHY) {
11202                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
11203                        }
11204                        mPrivateFlags &= ~DIRTY_MASK;
11205                        dispatchDraw(canvas);
11206                    } else {
11207                        draw(canvas);
11208                    }
11209                } else {
11210                    mPrivateFlags &= ~DIRTY_MASK;
11211                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
11212                            mRight - mLeft, mBottom - mTop, null);
11213                }
11214            }
11215        } else if (cache != null) {
11216            mPrivateFlags &= ~DIRTY_MASK;
11217            Paint cachePaint;
11218
11219            if (layerType == LAYER_TYPE_NONE) {
11220                cachePaint = parent.mCachePaint;
11221                if (cachePaint == null) {
11222                    cachePaint = new Paint();
11223                    cachePaint.setDither(false);
11224                    parent.mCachePaint = cachePaint;
11225                }
11226                if (alpha < 1.0f) {
11227                    cachePaint.setAlpha((int) (alpha * 255));
11228                    parent.mGroupFlags |= parent.FLAG_ALPHA_LOWER_THAN_ONE;
11229                } else if  ((flags & parent.FLAG_ALPHA_LOWER_THAN_ONE) ==
11230                        parent.FLAG_ALPHA_LOWER_THAN_ONE) {
11231                    cachePaint.setAlpha(255);
11232                    parent.mGroupFlags &= ~parent.FLAG_ALPHA_LOWER_THAN_ONE;
11233                }
11234            } else {
11235                cachePaint = mLayerPaint;
11236                cachePaint.setAlpha((int) (alpha * 255));
11237            }
11238            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
11239        }
11240
11241        canvas.restoreToCount(restoreTo);
11242
11243        if (a != null && !more) {
11244            if (!hardwareAccelerated && !a.getFillAfter()) {
11245                onSetAlpha(255);
11246            }
11247            parent.finishAnimatingView(this, a);
11248        }
11249
11250        if (more && hardwareAccelerated) {
11251            // invalidation is the trigger to recreate display lists, so if we're using
11252            // display lists to render, force an invalidate to allow the animation to
11253            // continue drawing another frame
11254            parent.invalidate(true);
11255            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11256                // alpha animations should cause the child to recreate its display list
11257                invalidate(true);
11258            }
11259        }
11260
11261        mRecreateDisplayList = false;
11262
11263        return more;
11264    }
11265
11266    /**
11267     * Manually render this view (and all of its children) to the given Canvas.
11268     * The view must have already done a full layout before this function is
11269     * called.  When implementing a view, implement
11270     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
11271     * If you do need to override this method, call the superclass version.
11272     *
11273     * @param canvas The Canvas to which the View is rendered.
11274     */
11275    public void draw(Canvas canvas) {
11276        if (ViewDebug.TRACE_HIERARCHY) {
11277            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11278        }
11279
11280        final int privateFlags = mPrivateFlags;
11281        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
11282                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
11283        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
11284
11285        /*
11286         * Draw traversal performs several drawing steps which must be executed
11287         * in the appropriate order:
11288         *
11289         *      1. Draw the background
11290         *      2. If necessary, save the canvas' layers to prepare for fading
11291         *      3. Draw view's content
11292         *      4. Draw children
11293         *      5. If necessary, draw the fading edges and restore layers
11294         *      6. Draw decorations (scrollbars for instance)
11295         */
11296
11297        // Step 1, draw the background, if needed
11298        int saveCount;
11299
11300        if (!dirtyOpaque) {
11301            final Drawable background = mBGDrawable;
11302            if (background != null) {
11303                final int scrollX = mScrollX;
11304                final int scrollY = mScrollY;
11305
11306                if (mBackgroundSizeChanged) {
11307                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
11308                    mBackgroundSizeChanged = false;
11309                }
11310
11311                if ((scrollX | scrollY) == 0) {
11312                    background.draw(canvas);
11313                } else {
11314                    canvas.translate(scrollX, scrollY);
11315                    background.draw(canvas);
11316                    canvas.translate(-scrollX, -scrollY);
11317                }
11318            }
11319        }
11320
11321        // skip step 2 & 5 if possible (common case)
11322        final int viewFlags = mViewFlags;
11323        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
11324        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
11325        if (!verticalEdges && !horizontalEdges) {
11326            // Step 3, draw the content
11327            if (!dirtyOpaque) onDraw(canvas);
11328
11329            // Step 4, draw the children
11330            dispatchDraw(canvas);
11331
11332            // Step 6, draw decorations (scrollbars)
11333            onDrawScrollBars(canvas);
11334
11335            // we're done...
11336            return;
11337        }
11338
11339        /*
11340         * Here we do the full fledged routine...
11341         * (this is an uncommon case where speed matters less,
11342         * this is why we repeat some of the tests that have been
11343         * done above)
11344         */
11345
11346        boolean drawTop = false;
11347        boolean drawBottom = false;
11348        boolean drawLeft = false;
11349        boolean drawRight = false;
11350
11351        float topFadeStrength = 0.0f;
11352        float bottomFadeStrength = 0.0f;
11353        float leftFadeStrength = 0.0f;
11354        float rightFadeStrength = 0.0f;
11355
11356        // Step 2, save the canvas' layers
11357        int paddingLeft = mPaddingLeft;
11358
11359        final boolean offsetRequired = isPaddingOffsetRequired();
11360        if (offsetRequired) {
11361            paddingLeft += getLeftPaddingOffset();
11362        }
11363
11364        int left = mScrollX + paddingLeft;
11365        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
11366        int top = mScrollY + getFadeTop(offsetRequired);
11367        int bottom = top + getFadeHeight(offsetRequired);
11368
11369        if (offsetRequired) {
11370            right += getRightPaddingOffset();
11371            bottom += getBottomPaddingOffset();
11372        }
11373
11374        final ScrollabilityCache scrollabilityCache = mScrollCache;
11375        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
11376        int length = (int) fadeHeight;
11377
11378        // clip the fade length if top and bottom fades overlap
11379        // overlapping fades produce odd-looking artifacts
11380        if (verticalEdges && (top + length > bottom - length)) {
11381            length = (bottom - top) / 2;
11382        }
11383
11384        // also clip horizontal fades if necessary
11385        if (horizontalEdges && (left + length > right - length)) {
11386            length = (right - left) / 2;
11387        }
11388
11389        if (verticalEdges) {
11390            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
11391            drawTop = topFadeStrength * fadeHeight > 1.0f;
11392            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
11393            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
11394        }
11395
11396        if (horizontalEdges) {
11397            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
11398            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
11399            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
11400            drawRight = rightFadeStrength * fadeHeight > 1.0f;
11401        }
11402
11403        saveCount = canvas.getSaveCount();
11404
11405        int solidColor = getSolidColor();
11406        if (solidColor == 0) {
11407            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11408
11409            if (drawTop) {
11410                canvas.saveLayer(left, top, right, top + length, null, flags);
11411            }
11412
11413            if (drawBottom) {
11414                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
11415            }
11416
11417            if (drawLeft) {
11418                canvas.saveLayer(left, top, left + length, bottom, null, flags);
11419            }
11420
11421            if (drawRight) {
11422                canvas.saveLayer(right - length, top, right, bottom, null, flags);
11423            }
11424        } else {
11425            scrollabilityCache.setFadeColor(solidColor);
11426        }
11427
11428        // Step 3, draw the content
11429        if (!dirtyOpaque) onDraw(canvas);
11430
11431        // Step 4, draw the children
11432        dispatchDraw(canvas);
11433
11434        // Step 5, draw the fade effect and restore layers
11435        final Paint p = scrollabilityCache.paint;
11436        final Matrix matrix = scrollabilityCache.matrix;
11437        final Shader fade = scrollabilityCache.shader;
11438
11439        if (drawTop) {
11440            matrix.setScale(1, fadeHeight * topFadeStrength);
11441            matrix.postTranslate(left, top);
11442            fade.setLocalMatrix(matrix);
11443            canvas.drawRect(left, top, right, top + length, p);
11444        }
11445
11446        if (drawBottom) {
11447            matrix.setScale(1, fadeHeight * bottomFadeStrength);
11448            matrix.postRotate(180);
11449            matrix.postTranslate(left, bottom);
11450            fade.setLocalMatrix(matrix);
11451            canvas.drawRect(left, bottom - length, right, bottom, p);
11452        }
11453
11454        if (drawLeft) {
11455            matrix.setScale(1, fadeHeight * leftFadeStrength);
11456            matrix.postRotate(-90);
11457            matrix.postTranslate(left, top);
11458            fade.setLocalMatrix(matrix);
11459            canvas.drawRect(left, top, left + length, bottom, p);
11460        }
11461
11462        if (drawRight) {
11463            matrix.setScale(1, fadeHeight * rightFadeStrength);
11464            matrix.postRotate(90);
11465            matrix.postTranslate(right, top);
11466            fade.setLocalMatrix(matrix);
11467            canvas.drawRect(right - length, top, right, bottom, p);
11468        }
11469
11470        canvas.restoreToCount(saveCount);
11471
11472        // Step 6, draw decorations (scrollbars)
11473        onDrawScrollBars(canvas);
11474    }
11475
11476    /**
11477     * Override this if your view is known to always be drawn on top of a solid color background,
11478     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11479     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11480     * should be set to 0xFF.
11481     *
11482     * @see #setVerticalFadingEdgeEnabled(boolean)
11483     * @see #setHorizontalFadingEdgeEnabled(boolean)
11484     *
11485     * @return The known solid color background for this view, or 0 if the color may vary
11486     */
11487    @ViewDebug.ExportedProperty(category = "drawing")
11488    public int getSolidColor() {
11489        return 0;
11490    }
11491
11492    /**
11493     * Build a human readable string representation of the specified view flags.
11494     *
11495     * @param flags the view flags to convert to a string
11496     * @return a String representing the supplied flags
11497     */
11498    private static String printFlags(int flags) {
11499        String output = "";
11500        int numFlags = 0;
11501        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11502            output += "TAKES_FOCUS";
11503            numFlags++;
11504        }
11505
11506        switch (flags & VISIBILITY_MASK) {
11507        case INVISIBLE:
11508            if (numFlags > 0) {
11509                output += " ";
11510            }
11511            output += "INVISIBLE";
11512            // USELESS HERE numFlags++;
11513            break;
11514        case GONE:
11515            if (numFlags > 0) {
11516                output += " ";
11517            }
11518            output += "GONE";
11519            // USELESS HERE numFlags++;
11520            break;
11521        default:
11522            break;
11523        }
11524        return output;
11525    }
11526
11527    /**
11528     * Build a human readable string representation of the specified private
11529     * view flags.
11530     *
11531     * @param privateFlags the private view flags to convert to a string
11532     * @return a String representing the supplied flags
11533     */
11534    private static String printPrivateFlags(int privateFlags) {
11535        String output = "";
11536        int numFlags = 0;
11537
11538        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11539            output += "WANTS_FOCUS";
11540            numFlags++;
11541        }
11542
11543        if ((privateFlags & FOCUSED) == FOCUSED) {
11544            if (numFlags > 0) {
11545                output += " ";
11546            }
11547            output += "FOCUSED";
11548            numFlags++;
11549        }
11550
11551        if ((privateFlags & SELECTED) == SELECTED) {
11552            if (numFlags > 0) {
11553                output += " ";
11554            }
11555            output += "SELECTED";
11556            numFlags++;
11557        }
11558
11559        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11560            if (numFlags > 0) {
11561                output += " ";
11562            }
11563            output += "IS_ROOT_NAMESPACE";
11564            numFlags++;
11565        }
11566
11567        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11568            if (numFlags > 0) {
11569                output += " ";
11570            }
11571            output += "HAS_BOUNDS";
11572            numFlags++;
11573        }
11574
11575        if ((privateFlags & DRAWN) == DRAWN) {
11576            if (numFlags > 0) {
11577                output += " ";
11578            }
11579            output += "DRAWN";
11580            // USELESS HERE numFlags++;
11581        }
11582        return output;
11583    }
11584
11585    /**
11586     * <p>Indicates whether or not this view's layout will be requested during
11587     * the next hierarchy layout pass.</p>
11588     *
11589     * @return true if the layout will be forced during next layout pass
11590     */
11591    public boolean isLayoutRequested() {
11592        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11593    }
11594
11595    /**
11596     * Assign a size and position to a view and all of its
11597     * descendants
11598     *
11599     * <p>This is the second phase of the layout mechanism.
11600     * (The first is measuring). In this phase, each parent calls
11601     * layout on all of its children to position them.
11602     * This is typically done using the child measurements
11603     * that were stored in the measure pass().</p>
11604     *
11605     * <p>Derived classes should not override this method.
11606     * Derived classes with children should override
11607     * onLayout. In that method, they should
11608     * call layout on each of their children.</p>
11609     *
11610     * @param l Left position, relative to parent
11611     * @param t Top position, relative to parent
11612     * @param r Right position, relative to parent
11613     * @param b Bottom position, relative to parent
11614     */
11615    @SuppressWarnings({"unchecked"})
11616    public void layout(int l, int t, int r, int b) {
11617        int oldL = mLeft;
11618        int oldT = mTop;
11619        int oldB = mBottom;
11620        int oldR = mRight;
11621        boolean changed = setFrame(l, t, r, b);
11622        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11623            if (ViewDebug.TRACE_HIERARCHY) {
11624                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11625            }
11626
11627            onLayout(changed, l, t, r, b);
11628            mPrivateFlags &= ~LAYOUT_REQUIRED;
11629
11630            ListenerInfo li = mListenerInfo;
11631            if (li != null && li.mOnLayoutChangeListeners != null) {
11632                ArrayList<OnLayoutChangeListener> listenersCopy =
11633                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
11634                int numListeners = listenersCopy.size();
11635                for (int i = 0; i < numListeners; ++i) {
11636                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
11637                }
11638            }
11639        }
11640        mPrivateFlags &= ~FORCE_LAYOUT;
11641    }
11642
11643    /**
11644     * Called from layout when this view should
11645     * assign a size and position to each of its children.
11646     *
11647     * Derived classes with children should override
11648     * this method and call layout on each of
11649     * their children.
11650     * @param changed This is a new size or position for this view
11651     * @param left Left position, relative to parent
11652     * @param top Top position, relative to parent
11653     * @param right Right position, relative to parent
11654     * @param bottom Bottom position, relative to parent
11655     */
11656    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
11657    }
11658
11659    /**
11660     * Assign a size and position to this view.
11661     *
11662     * This is called from layout.
11663     *
11664     * @param left Left position, relative to parent
11665     * @param top Top position, relative to parent
11666     * @param right Right position, relative to parent
11667     * @param bottom Bottom position, relative to parent
11668     * @return true if the new size and position are different than the
11669     *         previous ones
11670     * {@hide}
11671     */
11672    protected boolean setFrame(int left, int top, int right, int bottom) {
11673        boolean changed = false;
11674
11675        if (DBG) {
11676            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
11677                    + right + "," + bottom + ")");
11678        }
11679
11680        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
11681            changed = true;
11682
11683            // Remember our drawn bit
11684            int drawn = mPrivateFlags & DRAWN;
11685
11686            int oldWidth = mRight - mLeft;
11687            int oldHeight = mBottom - mTop;
11688            int newWidth = right - left;
11689            int newHeight = bottom - top;
11690            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
11691
11692            // Invalidate our old position
11693            invalidate(sizeChanged);
11694
11695            mLeft = left;
11696            mTop = top;
11697            mRight = right;
11698            mBottom = bottom;
11699
11700            mPrivateFlags |= HAS_BOUNDS;
11701
11702
11703            if (sizeChanged) {
11704                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
11705                    // A change in dimension means an auto-centered pivot point changes, too
11706                    if (mTransformationInfo != null) {
11707                        mTransformationInfo.mMatrixDirty = true;
11708                    }
11709                }
11710                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
11711            }
11712
11713            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
11714                // If we are visible, force the DRAWN bit to on so that
11715                // this invalidate will go through (at least to our parent).
11716                // This is because someone may have invalidated this view
11717                // before this call to setFrame came in, thereby clearing
11718                // the DRAWN bit.
11719                mPrivateFlags |= DRAWN;
11720                invalidate(sizeChanged);
11721                // parent display list may need to be recreated based on a change in the bounds
11722                // of any child
11723                invalidateParentCaches();
11724            }
11725
11726            // Reset drawn bit to original value (invalidate turns it off)
11727            mPrivateFlags |= drawn;
11728
11729            mBackgroundSizeChanged = true;
11730        }
11731        return changed;
11732    }
11733
11734    /**
11735     * Finalize inflating a view from XML.  This is called as the last phase
11736     * of inflation, after all child views have been added.
11737     *
11738     * <p>Even if the subclass overrides onFinishInflate, they should always be
11739     * sure to call the super method, so that we get called.
11740     */
11741    protected void onFinishInflate() {
11742    }
11743
11744    /**
11745     * Returns the resources associated with this view.
11746     *
11747     * @return Resources object.
11748     */
11749    public Resources getResources() {
11750        return mResources;
11751    }
11752
11753    /**
11754     * Invalidates the specified Drawable.
11755     *
11756     * @param drawable the drawable to invalidate
11757     */
11758    public void invalidateDrawable(Drawable drawable) {
11759        if (verifyDrawable(drawable)) {
11760            final Rect dirty = drawable.getBounds();
11761            final int scrollX = mScrollX;
11762            final int scrollY = mScrollY;
11763
11764            invalidate(dirty.left + scrollX, dirty.top + scrollY,
11765                    dirty.right + scrollX, dirty.bottom + scrollY);
11766        }
11767    }
11768
11769    /**
11770     * Schedules an action on a drawable to occur at a specified time.
11771     *
11772     * @param who the recipient of the action
11773     * @param what the action to run on the drawable
11774     * @param when the time at which the action must occur. Uses the
11775     *        {@link SystemClock#uptimeMillis} timebase.
11776     */
11777    public void scheduleDrawable(Drawable who, Runnable what, long when) {
11778        if (verifyDrawable(who) && what != null) {
11779            if (mAttachInfo != null) {
11780                mAttachInfo.mHandler.postAtTime(what, who, when);
11781            } else {
11782                ViewRootImpl.getRunQueue().postDelayed(what, when - SystemClock.uptimeMillis());
11783            }
11784        }
11785    }
11786
11787    /**
11788     * Cancels a scheduled action on a drawable.
11789     *
11790     * @param who the recipient of the action
11791     * @param what the action to cancel
11792     */
11793    public void unscheduleDrawable(Drawable who, Runnable what) {
11794        if (verifyDrawable(who) && what != null) {
11795            if (mAttachInfo != null) {
11796                mAttachInfo.mHandler.removeCallbacks(what, who);
11797            } else {
11798                ViewRootImpl.getRunQueue().removeCallbacks(what);
11799            }
11800        }
11801    }
11802
11803    /**
11804     * Unschedule any events associated with the given Drawable.  This can be
11805     * used when selecting a new Drawable into a view, so that the previous
11806     * one is completely unscheduled.
11807     *
11808     * @param who The Drawable to unschedule.
11809     *
11810     * @see #drawableStateChanged
11811     */
11812    public void unscheduleDrawable(Drawable who) {
11813        if (mAttachInfo != null) {
11814            mAttachInfo.mHandler.removeCallbacksAndMessages(who);
11815        }
11816    }
11817
11818    /**
11819    * Return the layout direction of a given Drawable.
11820    *
11821    * @param who the Drawable to query
11822    *
11823    * @hide
11824    */
11825    public int getResolvedLayoutDirection(Drawable who) {
11826        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
11827    }
11828
11829    /**
11830     * If your view subclass is displaying its own Drawable objects, it should
11831     * override this function and return true for any Drawable it is
11832     * displaying.  This allows animations for those drawables to be
11833     * scheduled.
11834     *
11835     * <p>Be sure to call through to the super class when overriding this
11836     * function.
11837     *
11838     * @param who The Drawable to verify.  Return true if it is one you are
11839     *            displaying, else return the result of calling through to the
11840     *            super class.
11841     *
11842     * @return boolean If true than the Drawable is being displayed in the
11843     *         view; else false and it is not allowed to animate.
11844     *
11845     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
11846     * @see #drawableStateChanged()
11847     */
11848    protected boolean verifyDrawable(Drawable who) {
11849        return who == mBGDrawable;
11850    }
11851
11852    /**
11853     * This function is called whenever the state of the view changes in such
11854     * a way that it impacts the state of drawables being shown.
11855     *
11856     * <p>Be sure to call through to the superclass when overriding this
11857     * function.
11858     *
11859     * @see Drawable#setState(int[])
11860     */
11861    protected void drawableStateChanged() {
11862        Drawable d = mBGDrawable;
11863        if (d != null && d.isStateful()) {
11864            d.setState(getDrawableState());
11865        }
11866    }
11867
11868    /**
11869     * Call this to force a view to update its drawable state. This will cause
11870     * drawableStateChanged to be called on this view. Views that are interested
11871     * in the new state should call getDrawableState.
11872     *
11873     * @see #drawableStateChanged
11874     * @see #getDrawableState
11875     */
11876    public void refreshDrawableState() {
11877        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
11878        drawableStateChanged();
11879
11880        ViewParent parent = mParent;
11881        if (parent != null) {
11882            parent.childDrawableStateChanged(this);
11883        }
11884    }
11885
11886    /**
11887     * Return an array of resource IDs of the drawable states representing the
11888     * current state of the view.
11889     *
11890     * @return The current drawable state
11891     *
11892     * @see Drawable#setState(int[])
11893     * @see #drawableStateChanged()
11894     * @see #onCreateDrawableState(int)
11895     */
11896    public final int[] getDrawableState() {
11897        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
11898            return mDrawableState;
11899        } else {
11900            mDrawableState = onCreateDrawableState(0);
11901            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
11902            return mDrawableState;
11903        }
11904    }
11905
11906    /**
11907     * Generate the new {@link android.graphics.drawable.Drawable} state for
11908     * this view. This is called by the view
11909     * system when the cached Drawable state is determined to be invalid.  To
11910     * retrieve the current state, you should use {@link #getDrawableState}.
11911     *
11912     * @param extraSpace if non-zero, this is the number of extra entries you
11913     * would like in the returned array in which you can place your own
11914     * states.
11915     *
11916     * @return Returns an array holding the current {@link Drawable} state of
11917     * the view.
11918     *
11919     * @see #mergeDrawableStates(int[], int[])
11920     */
11921    protected int[] onCreateDrawableState(int extraSpace) {
11922        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
11923                mParent instanceof View) {
11924            return ((View) mParent).onCreateDrawableState(extraSpace);
11925        }
11926
11927        int[] drawableState;
11928
11929        int privateFlags = mPrivateFlags;
11930
11931        int viewStateIndex = 0;
11932        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
11933        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
11934        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
11935        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
11936        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
11937        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
11938        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
11939                HardwareRenderer.isAvailable()) {
11940            // This is set if HW acceleration is requested, even if the current
11941            // process doesn't allow it.  This is just to allow app preview
11942            // windows to better match their app.
11943            viewStateIndex |= VIEW_STATE_ACCELERATED;
11944        }
11945        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
11946
11947        final int privateFlags2 = mPrivateFlags2;
11948        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
11949        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
11950
11951        drawableState = VIEW_STATE_SETS[viewStateIndex];
11952
11953        //noinspection ConstantIfStatement
11954        if (false) {
11955            Log.i("View", "drawableStateIndex=" + viewStateIndex);
11956            Log.i("View", toString()
11957                    + " pressed=" + ((privateFlags & PRESSED) != 0)
11958                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
11959                    + " fo=" + hasFocus()
11960                    + " sl=" + ((privateFlags & SELECTED) != 0)
11961                    + " wf=" + hasWindowFocus()
11962                    + ": " + Arrays.toString(drawableState));
11963        }
11964
11965        if (extraSpace == 0) {
11966            return drawableState;
11967        }
11968
11969        final int[] fullState;
11970        if (drawableState != null) {
11971            fullState = new int[drawableState.length + extraSpace];
11972            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
11973        } else {
11974            fullState = new int[extraSpace];
11975        }
11976
11977        return fullState;
11978    }
11979
11980    /**
11981     * Merge your own state values in <var>additionalState</var> into the base
11982     * state values <var>baseState</var> that were returned by
11983     * {@link #onCreateDrawableState(int)}.
11984     *
11985     * @param baseState The base state values returned by
11986     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
11987     * own additional state values.
11988     *
11989     * @param additionalState The additional state values you would like
11990     * added to <var>baseState</var>; this array is not modified.
11991     *
11992     * @return As a convenience, the <var>baseState</var> array you originally
11993     * passed into the function is returned.
11994     *
11995     * @see #onCreateDrawableState(int)
11996     */
11997    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
11998        final int N = baseState.length;
11999        int i = N - 1;
12000        while (i >= 0 && baseState[i] == 0) {
12001            i--;
12002        }
12003        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
12004        return baseState;
12005    }
12006
12007    /**
12008     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12009     * on all Drawable objects associated with this view.
12010     */
12011    public void jumpDrawablesToCurrentState() {
12012        if (mBGDrawable != null) {
12013            mBGDrawable.jumpToCurrentState();
12014        }
12015    }
12016
12017    /**
12018     * Sets the background color for this view.
12019     * @param color the color of the background
12020     */
12021    @RemotableViewMethod
12022    public void setBackgroundColor(int color) {
12023        if (mBGDrawable instanceof ColorDrawable) {
12024            ((ColorDrawable) mBGDrawable).setColor(color);
12025        } else {
12026            setBackgroundDrawable(new ColorDrawable(color));
12027        }
12028    }
12029
12030    /**
12031     * Set the background to a given resource. The resource should refer to
12032     * a Drawable object or 0 to remove the background.
12033     * @param resid The identifier of the resource.
12034     * @attr ref android.R.styleable#View_background
12035     */
12036    @RemotableViewMethod
12037    public void setBackgroundResource(int resid) {
12038        if (resid != 0 && resid == mBackgroundResource) {
12039            return;
12040        }
12041
12042        Drawable d= null;
12043        if (resid != 0) {
12044            d = mResources.getDrawable(resid);
12045        }
12046        setBackgroundDrawable(d);
12047
12048        mBackgroundResource = resid;
12049    }
12050
12051    /**
12052     * Set the background to a given Drawable, or remove the background. If the
12053     * background has padding, this View's padding is set to the background's
12054     * padding. However, when a background is removed, this View's padding isn't
12055     * touched. If setting the padding is desired, please use
12056     * {@link #setPadding(int, int, int, int)}.
12057     *
12058     * @param d The Drawable to use as the background, or null to remove the
12059     *        background
12060     */
12061    public void setBackgroundDrawable(Drawable d) {
12062        if (d == mBGDrawable) {
12063            return;
12064        }
12065
12066        boolean requestLayout = false;
12067
12068        mBackgroundResource = 0;
12069
12070        /*
12071         * Regardless of whether we're setting a new background or not, we want
12072         * to clear the previous drawable.
12073         */
12074        if (mBGDrawable != null) {
12075            mBGDrawable.setCallback(null);
12076            unscheduleDrawable(mBGDrawable);
12077        }
12078
12079        if (d != null) {
12080            Rect padding = sThreadLocal.get();
12081            if (padding == null) {
12082                padding = new Rect();
12083                sThreadLocal.set(padding);
12084            }
12085            if (d.getPadding(padding)) {
12086                switch (d.getResolvedLayoutDirectionSelf()) {
12087                    case LAYOUT_DIRECTION_RTL:
12088                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12089                        break;
12090                    case LAYOUT_DIRECTION_LTR:
12091                    default:
12092                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12093                }
12094            }
12095
12096            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12097            // if it has a different minimum size, we should layout again
12098            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
12099                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
12100                requestLayout = true;
12101            }
12102
12103            d.setCallback(this);
12104            if (d.isStateful()) {
12105                d.setState(getDrawableState());
12106            }
12107            d.setVisible(getVisibility() == VISIBLE, false);
12108            mBGDrawable = d;
12109
12110            if ((mPrivateFlags & SKIP_DRAW) != 0) {
12111                mPrivateFlags &= ~SKIP_DRAW;
12112                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
12113                requestLayout = true;
12114            }
12115        } else {
12116            /* Remove the background */
12117            mBGDrawable = null;
12118
12119            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
12120                /*
12121                 * This view ONLY drew the background before and we're removing
12122                 * the background, so now it won't draw anything
12123                 * (hence we SKIP_DRAW)
12124                 */
12125                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
12126                mPrivateFlags |= SKIP_DRAW;
12127            }
12128
12129            /*
12130             * When the background is set, we try to apply its padding to this
12131             * View. When the background is removed, we don't touch this View's
12132             * padding. This is noted in the Javadocs. Hence, we don't need to
12133             * requestLayout(), the invalidate() below is sufficient.
12134             */
12135
12136            // The old background's minimum size could have affected this
12137            // View's layout, so let's requestLayout
12138            requestLayout = true;
12139        }
12140
12141        computeOpaqueFlags();
12142
12143        if (requestLayout) {
12144            requestLayout();
12145        }
12146
12147        mBackgroundSizeChanged = true;
12148        invalidate(true);
12149    }
12150
12151    /**
12152     * Gets the background drawable
12153     * @return The drawable used as the background for this view, if any.
12154     */
12155    public Drawable getBackground() {
12156        return mBGDrawable;
12157    }
12158
12159    /**
12160     * Sets the padding. The view may add on the space required to display
12161     * the scrollbars, depending on the style and visibility of the scrollbars.
12162     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
12163     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
12164     * from the values set in this call.
12165     *
12166     * @attr ref android.R.styleable#View_padding
12167     * @attr ref android.R.styleable#View_paddingBottom
12168     * @attr ref android.R.styleable#View_paddingLeft
12169     * @attr ref android.R.styleable#View_paddingRight
12170     * @attr ref android.R.styleable#View_paddingTop
12171     * @param left the left padding in pixels
12172     * @param top the top padding in pixels
12173     * @param right the right padding in pixels
12174     * @param bottom the bottom padding in pixels
12175     */
12176    public void setPadding(int left, int top, int right, int bottom) {
12177        boolean changed = false;
12178
12179        mUserPaddingRelative = false;
12180
12181        mUserPaddingLeft = left;
12182        mUserPaddingRight = right;
12183        mUserPaddingBottom = bottom;
12184
12185        final int viewFlags = mViewFlags;
12186
12187        // Common case is there are no scroll bars.
12188        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
12189            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
12190                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
12191                        ? 0 : getVerticalScrollbarWidth();
12192                switch (mVerticalScrollbarPosition) {
12193                    case SCROLLBAR_POSITION_DEFAULT:
12194                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12195                            left += offset;
12196                        } else {
12197                            right += offset;
12198                        }
12199                        break;
12200                    case SCROLLBAR_POSITION_RIGHT:
12201                        right += offset;
12202                        break;
12203                    case SCROLLBAR_POSITION_LEFT:
12204                        left += offset;
12205                        break;
12206                }
12207            }
12208            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
12209                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
12210                        ? 0 : getHorizontalScrollbarHeight();
12211            }
12212        }
12213
12214        if (mPaddingLeft != left) {
12215            changed = true;
12216            mPaddingLeft = left;
12217        }
12218        if (mPaddingTop != top) {
12219            changed = true;
12220            mPaddingTop = top;
12221        }
12222        if (mPaddingRight != right) {
12223            changed = true;
12224            mPaddingRight = right;
12225        }
12226        if (mPaddingBottom != bottom) {
12227            changed = true;
12228            mPaddingBottom = bottom;
12229        }
12230
12231        if (changed) {
12232            requestLayout();
12233        }
12234    }
12235
12236    /**
12237     * Sets the relative padding. The view may add on the space required to display
12238     * the scrollbars, depending on the style and visibility of the scrollbars.
12239     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
12240     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
12241     * from the values set in this call.
12242     *
12243     * @attr ref android.R.styleable#View_padding
12244     * @attr ref android.R.styleable#View_paddingBottom
12245     * @attr ref android.R.styleable#View_paddingStart
12246     * @attr ref android.R.styleable#View_paddingEnd
12247     * @attr ref android.R.styleable#View_paddingTop
12248     * @param start the start padding in pixels
12249     * @param top the top padding in pixels
12250     * @param end the end padding in pixels
12251     * @param bottom the bottom padding in pixels
12252     */
12253    public void setPaddingRelative(int start, int top, int end, int bottom) {
12254        mUserPaddingRelative = true;
12255
12256        mUserPaddingStart = start;
12257        mUserPaddingEnd = end;
12258
12259        switch(getResolvedLayoutDirection()) {
12260            case LAYOUT_DIRECTION_RTL:
12261                setPadding(end, top, start, bottom);
12262                break;
12263            case LAYOUT_DIRECTION_LTR:
12264            default:
12265                setPadding(start, top, end, bottom);
12266        }
12267    }
12268
12269    /**
12270     * Returns the top padding of this view.
12271     *
12272     * @return the top padding in pixels
12273     */
12274    public int getPaddingTop() {
12275        return mPaddingTop;
12276    }
12277
12278    /**
12279     * Returns the bottom padding of this view. If there are inset and enabled
12280     * scrollbars, this value may include the space required to display the
12281     * scrollbars as well.
12282     *
12283     * @return the bottom padding in pixels
12284     */
12285    public int getPaddingBottom() {
12286        return mPaddingBottom;
12287    }
12288
12289    /**
12290     * Returns the left padding of this view. If there are inset and enabled
12291     * scrollbars, this value may include the space required to display the
12292     * scrollbars as well.
12293     *
12294     * @return the left padding in pixels
12295     */
12296    public int getPaddingLeft() {
12297        return mPaddingLeft;
12298    }
12299
12300    /**
12301     * Returns the start padding of this view. If there are inset and enabled
12302     * scrollbars, this value may include the space required to display the
12303     * scrollbars as well.
12304     *
12305     * @return the start padding in pixels
12306     */
12307    public int getPaddingStart() {
12308        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12309                mPaddingRight : mPaddingLeft;
12310    }
12311
12312    /**
12313     * Returns the right padding of this view. If there are inset and enabled
12314     * scrollbars, this value may include the space required to display the
12315     * scrollbars as well.
12316     *
12317     * @return the right padding in pixels
12318     */
12319    public int getPaddingRight() {
12320        return mPaddingRight;
12321    }
12322
12323    /**
12324     * Returns the end padding of this view. If there are inset and enabled
12325     * scrollbars, this value may include the space required to display the
12326     * scrollbars as well.
12327     *
12328     * @return the end padding in pixels
12329     */
12330    public int getPaddingEnd() {
12331        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12332                mPaddingLeft : mPaddingRight;
12333    }
12334
12335    /**
12336     * Return if the padding as been set thru relative values
12337     * {@link #setPaddingRelative(int, int, int, int)} or thru
12338     * @attr ref android.R.styleable#View_paddingStart or
12339     * @attr ref android.R.styleable#View_paddingEnd
12340     *
12341     * @return true if the padding is relative or false if it is not.
12342     */
12343    public boolean isPaddingRelative() {
12344        return mUserPaddingRelative;
12345    }
12346
12347    /**
12348     * Changes the selection state of this view. A view can be selected or not.
12349     * Note that selection is not the same as focus. Views are typically
12350     * selected in the context of an AdapterView like ListView or GridView;
12351     * the selected view is the view that is highlighted.
12352     *
12353     * @param selected true if the view must be selected, false otherwise
12354     */
12355    public void setSelected(boolean selected) {
12356        if (((mPrivateFlags & SELECTED) != 0) != selected) {
12357            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
12358            if (!selected) resetPressedState();
12359            invalidate(true);
12360            refreshDrawableState();
12361            dispatchSetSelected(selected);
12362        }
12363    }
12364
12365    /**
12366     * Dispatch setSelected to all of this View's children.
12367     *
12368     * @see #setSelected(boolean)
12369     *
12370     * @param selected The new selected state
12371     */
12372    protected void dispatchSetSelected(boolean selected) {
12373    }
12374
12375    /**
12376     * Indicates the selection state of this view.
12377     *
12378     * @return true if the view is selected, false otherwise
12379     */
12380    @ViewDebug.ExportedProperty
12381    public boolean isSelected() {
12382        return (mPrivateFlags & SELECTED) != 0;
12383    }
12384
12385    /**
12386     * Changes the activated state of this view. A view can be activated or not.
12387     * Note that activation is not the same as selection.  Selection is
12388     * a transient property, representing the view (hierarchy) the user is
12389     * currently interacting with.  Activation is a longer-term state that the
12390     * user can move views in and out of.  For example, in a list view with
12391     * single or multiple selection enabled, the views in the current selection
12392     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
12393     * here.)  The activated state is propagated down to children of the view it
12394     * is set on.
12395     *
12396     * @param activated true if the view must be activated, false otherwise
12397     */
12398    public void setActivated(boolean activated) {
12399        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
12400            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
12401            invalidate(true);
12402            refreshDrawableState();
12403            dispatchSetActivated(activated);
12404        }
12405    }
12406
12407    /**
12408     * Dispatch setActivated to all of this View's children.
12409     *
12410     * @see #setActivated(boolean)
12411     *
12412     * @param activated The new activated state
12413     */
12414    protected void dispatchSetActivated(boolean activated) {
12415    }
12416
12417    /**
12418     * Indicates the activation state of this view.
12419     *
12420     * @return true if the view is activated, false otherwise
12421     */
12422    @ViewDebug.ExportedProperty
12423    public boolean isActivated() {
12424        return (mPrivateFlags & ACTIVATED) != 0;
12425    }
12426
12427    /**
12428     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
12429     * observer can be used to get notifications when global events, like
12430     * layout, happen.
12431     *
12432     * The returned ViewTreeObserver observer is not guaranteed to remain
12433     * valid for the lifetime of this View. If the caller of this method keeps
12434     * a long-lived reference to ViewTreeObserver, it should always check for
12435     * the return value of {@link ViewTreeObserver#isAlive()}.
12436     *
12437     * @return The ViewTreeObserver for this view's hierarchy.
12438     */
12439    public ViewTreeObserver getViewTreeObserver() {
12440        if (mAttachInfo != null) {
12441            return mAttachInfo.mTreeObserver;
12442        }
12443        if (mFloatingTreeObserver == null) {
12444            mFloatingTreeObserver = new ViewTreeObserver();
12445        }
12446        return mFloatingTreeObserver;
12447    }
12448
12449    /**
12450     * <p>Finds the topmost view in the current view hierarchy.</p>
12451     *
12452     * @return the topmost view containing this view
12453     */
12454    public View getRootView() {
12455        if (mAttachInfo != null) {
12456            final View v = mAttachInfo.mRootView;
12457            if (v != null) {
12458                return v;
12459            }
12460        }
12461
12462        View parent = this;
12463
12464        while (parent.mParent != null && parent.mParent instanceof View) {
12465            parent = (View) parent.mParent;
12466        }
12467
12468        return parent;
12469    }
12470
12471    /**
12472     * <p>Computes the coordinates of this view on the screen. The argument
12473     * must be an array of two integers. After the method returns, the array
12474     * contains the x and y location in that order.</p>
12475     *
12476     * @param location an array of two integers in which to hold the coordinates
12477     */
12478    public void getLocationOnScreen(int[] location) {
12479        getLocationInWindow(location);
12480
12481        final AttachInfo info = mAttachInfo;
12482        if (info != null) {
12483            location[0] += info.mWindowLeft;
12484            location[1] += info.mWindowTop;
12485        }
12486    }
12487
12488    /**
12489     * <p>Computes the coordinates of this view in its window. The argument
12490     * must be an array of two integers. After the method returns, the array
12491     * contains the x and y location in that order.</p>
12492     *
12493     * @param location an array of two integers in which to hold the coordinates
12494     */
12495    public void getLocationInWindow(int[] location) {
12496        if (location == null || location.length < 2) {
12497            throw new IllegalArgumentException("location must be an array of two integers");
12498        }
12499
12500        if (mAttachInfo == null) {
12501            // When the view is not attached to a window, this method does not make sense
12502            location[0] = location[1] = 0;
12503            return;
12504        }
12505
12506        float[] position = mAttachInfo.mTmpTransformLocation;
12507        position[0] = position[1] = 0.0f;
12508
12509        if (!hasIdentityMatrix()) {
12510            getMatrix().mapPoints(position);
12511        }
12512
12513        position[0] += mLeft;
12514        position[1] += mTop;
12515
12516        ViewParent viewParent = mParent;
12517        while (viewParent instanceof View) {
12518            final View view = (View) viewParent;
12519
12520            position[0] -= view.mScrollX;
12521            position[1] -= view.mScrollY;
12522
12523            if (!view.hasIdentityMatrix()) {
12524                view.getMatrix().mapPoints(position);
12525            }
12526
12527            position[0] += view.mLeft;
12528            position[1] += view.mTop;
12529
12530            viewParent = view.mParent;
12531        }
12532
12533        if (viewParent instanceof ViewRootImpl) {
12534            // *cough*
12535            final ViewRootImpl vr = (ViewRootImpl) viewParent;
12536            position[1] -= vr.mCurScrollY;
12537        }
12538
12539        location[0] = (int) (position[0] + 0.5f);
12540        location[1] = (int) (position[1] + 0.5f);
12541    }
12542
12543    /**
12544     * {@hide}
12545     * @param id the id of the view to be found
12546     * @return the view of the specified id, null if cannot be found
12547     */
12548    protected View findViewTraversal(int id) {
12549        if (id == mID) {
12550            return this;
12551        }
12552        return null;
12553    }
12554
12555    /**
12556     * {@hide}
12557     * @param tag the tag of the view to be found
12558     * @return the view of specified tag, null if cannot be found
12559     */
12560    protected View findViewWithTagTraversal(Object tag) {
12561        if (tag != null && tag.equals(mTag)) {
12562            return this;
12563        }
12564        return null;
12565    }
12566
12567    /**
12568     * {@hide}
12569     * @param predicate The predicate to evaluate.
12570     * @param childToSkip If not null, ignores this child during the recursive traversal.
12571     * @return The first view that matches the predicate or null.
12572     */
12573    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12574        if (predicate.apply(this)) {
12575            return this;
12576        }
12577        return null;
12578    }
12579
12580    /**
12581     * Look for a child view with the given id.  If this view has the given
12582     * id, return this view.
12583     *
12584     * @param id The id to search for.
12585     * @return The view that has the given id in the hierarchy or null
12586     */
12587    public final View findViewById(int id) {
12588        if (id < 0) {
12589            return null;
12590        }
12591        return findViewTraversal(id);
12592    }
12593
12594    /**
12595     * Finds a view by its unuque and stable accessibility id.
12596     *
12597     * @param accessibilityId The searched accessibility id.
12598     * @return The found view.
12599     */
12600    final View findViewByAccessibilityId(int accessibilityId) {
12601        if (accessibilityId < 0) {
12602            return null;
12603        }
12604        return findViewByAccessibilityIdTraversal(accessibilityId);
12605    }
12606
12607    /**
12608     * Performs the traversal to find a view by its unuque and stable accessibility id.
12609     *
12610     * <strong>Note:</strong>This method does not stop at the root namespace
12611     * boundary since the user can touch the screen at an arbitrary location
12612     * potentially crossing the root namespace bounday which will send an
12613     * accessibility event to accessibility services and they should be able
12614     * to obtain the event source. Also accessibility ids are guaranteed to be
12615     * unique in the window.
12616     *
12617     * @param accessibilityId The accessibility id.
12618     * @return The found view.
12619     */
12620    View findViewByAccessibilityIdTraversal(int accessibilityId) {
12621        if (getAccessibilityViewId() == accessibilityId) {
12622            return this;
12623        }
12624        return null;
12625    }
12626
12627    /**
12628     * Look for a child view with the given tag.  If this view has the given
12629     * tag, return this view.
12630     *
12631     * @param tag The tag to search for, using "tag.equals(getTag())".
12632     * @return The View that has the given tag in the hierarchy or null
12633     */
12634    public final View findViewWithTag(Object tag) {
12635        if (tag == null) {
12636            return null;
12637        }
12638        return findViewWithTagTraversal(tag);
12639    }
12640
12641    /**
12642     * {@hide}
12643     * Look for a child view that matches the specified predicate.
12644     * If this view matches the predicate, return this view.
12645     *
12646     * @param predicate The predicate to evaluate.
12647     * @return The first view that matches the predicate or null.
12648     */
12649    public final View findViewByPredicate(Predicate<View> predicate) {
12650        return findViewByPredicateTraversal(predicate, null);
12651    }
12652
12653    /**
12654     * {@hide}
12655     * Look for a child view that matches the specified predicate,
12656     * starting with the specified view and its descendents and then
12657     * recusively searching the ancestors and siblings of that view
12658     * until this view is reached.
12659     *
12660     * This method is useful in cases where the predicate does not match
12661     * a single unique view (perhaps multiple views use the same id)
12662     * and we are trying to find the view that is "closest" in scope to the
12663     * starting view.
12664     *
12665     * @param start The view to start from.
12666     * @param predicate The predicate to evaluate.
12667     * @return The first view that matches the predicate or null.
12668     */
12669    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
12670        View childToSkip = null;
12671        for (;;) {
12672            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
12673            if (view != null || start == this) {
12674                return view;
12675            }
12676
12677            ViewParent parent = start.getParent();
12678            if (parent == null || !(parent instanceof View)) {
12679                return null;
12680            }
12681
12682            childToSkip = start;
12683            start = (View) parent;
12684        }
12685    }
12686
12687    /**
12688     * Sets the identifier for this view. The identifier does not have to be
12689     * unique in this view's hierarchy. The identifier should be a positive
12690     * number.
12691     *
12692     * @see #NO_ID
12693     * @see #getId()
12694     * @see #findViewById(int)
12695     *
12696     * @param id a number used to identify the view
12697     *
12698     * @attr ref android.R.styleable#View_id
12699     */
12700    public void setId(int id) {
12701        mID = id;
12702    }
12703
12704    /**
12705     * {@hide}
12706     *
12707     * @param isRoot true if the view belongs to the root namespace, false
12708     *        otherwise
12709     */
12710    public void setIsRootNamespace(boolean isRoot) {
12711        if (isRoot) {
12712            mPrivateFlags |= IS_ROOT_NAMESPACE;
12713        } else {
12714            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
12715        }
12716    }
12717
12718    /**
12719     * {@hide}
12720     *
12721     * @return true if the view belongs to the root namespace, false otherwise
12722     */
12723    public boolean isRootNamespace() {
12724        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
12725    }
12726
12727    /**
12728     * Returns this view's identifier.
12729     *
12730     * @return a positive integer used to identify the view or {@link #NO_ID}
12731     *         if the view has no ID
12732     *
12733     * @see #setId(int)
12734     * @see #findViewById(int)
12735     * @attr ref android.R.styleable#View_id
12736     */
12737    @ViewDebug.CapturedViewProperty
12738    public int getId() {
12739        return mID;
12740    }
12741
12742    /**
12743     * Returns this view's tag.
12744     *
12745     * @return the Object stored in this view as a tag
12746     *
12747     * @see #setTag(Object)
12748     * @see #getTag(int)
12749     */
12750    @ViewDebug.ExportedProperty
12751    public Object getTag() {
12752        return mTag;
12753    }
12754
12755    /**
12756     * Sets the tag associated with this view. A tag can be used to mark
12757     * a view in its hierarchy and does not have to be unique within the
12758     * hierarchy. Tags can also be used to store data within a view without
12759     * resorting to another data structure.
12760     *
12761     * @param tag an Object to tag the view with
12762     *
12763     * @see #getTag()
12764     * @see #setTag(int, Object)
12765     */
12766    public void setTag(final Object tag) {
12767        mTag = tag;
12768    }
12769
12770    /**
12771     * Returns the tag associated with this view and the specified key.
12772     *
12773     * @param key The key identifying the tag
12774     *
12775     * @return the Object stored in this view as a tag
12776     *
12777     * @see #setTag(int, Object)
12778     * @see #getTag()
12779     */
12780    public Object getTag(int key) {
12781        if (mKeyedTags != null) return mKeyedTags.get(key);
12782        return null;
12783    }
12784
12785    /**
12786     * Sets a tag associated with this view and a key. A tag can be used
12787     * to mark a view in its hierarchy and does not have to be unique within
12788     * the hierarchy. Tags can also be used to store data within a view
12789     * without resorting to another data structure.
12790     *
12791     * The specified key should be an id declared in the resources of the
12792     * application to ensure it is unique (see the <a
12793     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
12794     * Keys identified as belonging to
12795     * the Android framework or not associated with any package will cause
12796     * an {@link IllegalArgumentException} to be thrown.
12797     *
12798     * @param key The key identifying the tag
12799     * @param tag An Object to tag the view with
12800     *
12801     * @throws IllegalArgumentException If they specified key is not valid
12802     *
12803     * @see #setTag(Object)
12804     * @see #getTag(int)
12805     */
12806    public void setTag(int key, final Object tag) {
12807        // If the package id is 0x00 or 0x01, it's either an undefined package
12808        // or a framework id
12809        if ((key >>> 24) < 2) {
12810            throw new IllegalArgumentException("The key must be an application-specific "
12811                    + "resource id.");
12812        }
12813
12814        setKeyedTag(key, tag);
12815    }
12816
12817    /**
12818     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
12819     * framework id.
12820     *
12821     * @hide
12822     */
12823    public void setTagInternal(int key, Object tag) {
12824        if ((key >>> 24) != 0x1) {
12825            throw new IllegalArgumentException("The key must be a framework-specific "
12826                    + "resource id.");
12827        }
12828
12829        setKeyedTag(key, tag);
12830    }
12831
12832    private void setKeyedTag(int key, Object tag) {
12833        if (mKeyedTags == null) {
12834            mKeyedTags = new SparseArray<Object>();
12835        }
12836
12837        mKeyedTags.put(key, tag);
12838    }
12839
12840    /**
12841     * @param consistency The type of consistency. See ViewDebug for more information.
12842     *
12843     * @hide
12844     */
12845    protected boolean dispatchConsistencyCheck(int consistency) {
12846        return onConsistencyCheck(consistency);
12847    }
12848
12849    /**
12850     * Method that subclasses should implement to check their consistency. The type of
12851     * consistency check is indicated by the bit field passed as a parameter.
12852     *
12853     * @param consistency The type of consistency. See ViewDebug for more information.
12854     *
12855     * @throws IllegalStateException if the view is in an inconsistent state.
12856     *
12857     * @hide
12858     */
12859    protected boolean onConsistencyCheck(int consistency) {
12860        boolean result = true;
12861
12862        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
12863        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
12864
12865        if (checkLayout) {
12866            if (getParent() == null) {
12867                result = false;
12868                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12869                        "View " + this + " does not have a parent.");
12870            }
12871
12872            if (mAttachInfo == null) {
12873                result = false;
12874                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12875                        "View " + this + " is not attached to a window.");
12876            }
12877        }
12878
12879        if (checkDrawing) {
12880            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
12881            // from their draw() method
12882
12883            if ((mPrivateFlags & DRAWN) != DRAWN &&
12884                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
12885                result = false;
12886                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
12887                        "View " + this + " was invalidated but its drawing cache is valid.");
12888            }
12889        }
12890
12891        return result;
12892    }
12893
12894    /**
12895     * Prints information about this view in the log output, with the tag
12896     * {@link #VIEW_LOG_TAG}.
12897     *
12898     * @hide
12899     */
12900    public void debug() {
12901        debug(0);
12902    }
12903
12904    /**
12905     * Prints information about this view in the log output, with the tag
12906     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
12907     * indentation defined by the <code>depth</code>.
12908     *
12909     * @param depth the indentation level
12910     *
12911     * @hide
12912     */
12913    protected void debug(int depth) {
12914        String output = debugIndent(depth - 1);
12915
12916        output += "+ " + this;
12917        int id = getId();
12918        if (id != -1) {
12919            output += " (id=" + id + ")";
12920        }
12921        Object tag = getTag();
12922        if (tag != null) {
12923            output += " (tag=" + tag + ")";
12924        }
12925        Log.d(VIEW_LOG_TAG, output);
12926
12927        if ((mPrivateFlags & FOCUSED) != 0) {
12928            output = debugIndent(depth) + " FOCUSED";
12929            Log.d(VIEW_LOG_TAG, output);
12930        }
12931
12932        output = debugIndent(depth);
12933        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
12934                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
12935                + "} ";
12936        Log.d(VIEW_LOG_TAG, output);
12937
12938        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
12939                || mPaddingBottom != 0) {
12940            output = debugIndent(depth);
12941            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
12942                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
12943            Log.d(VIEW_LOG_TAG, output);
12944        }
12945
12946        output = debugIndent(depth);
12947        output += "mMeasureWidth=" + mMeasuredWidth +
12948                " mMeasureHeight=" + mMeasuredHeight;
12949        Log.d(VIEW_LOG_TAG, output);
12950
12951        output = debugIndent(depth);
12952        if (mLayoutParams == null) {
12953            output += "BAD! no layout params";
12954        } else {
12955            output = mLayoutParams.debug(output);
12956        }
12957        Log.d(VIEW_LOG_TAG, output);
12958
12959        output = debugIndent(depth);
12960        output += "flags={";
12961        output += View.printFlags(mViewFlags);
12962        output += "}";
12963        Log.d(VIEW_LOG_TAG, output);
12964
12965        output = debugIndent(depth);
12966        output += "privateFlags={";
12967        output += View.printPrivateFlags(mPrivateFlags);
12968        output += "}";
12969        Log.d(VIEW_LOG_TAG, output);
12970    }
12971
12972    /**
12973     * Creates an string of whitespaces used for indentation.
12974     *
12975     * @param depth the indentation level
12976     * @return a String containing (depth * 2 + 3) * 2 white spaces
12977     *
12978     * @hide
12979     */
12980    protected static String debugIndent(int depth) {
12981        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
12982        for (int i = 0; i < (depth * 2) + 3; i++) {
12983            spaces.append(' ').append(' ');
12984        }
12985        return spaces.toString();
12986    }
12987
12988    /**
12989     * <p>Return the offset of the widget's text baseline from the widget's top
12990     * boundary. If this widget does not support baseline alignment, this
12991     * method returns -1. </p>
12992     *
12993     * @return the offset of the baseline within the widget's bounds or -1
12994     *         if baseline alignment is not supported
12995     */
12996    @ViewDebug.ExportedProperty(category = "layout")
12997    public int getBaseline() {
12998        return -1;
12999    }
13000
13001    /**
13002     * Call this when something has changed which has invalidated the
13003     * layout of this view. This will schedule a layout pass of the view
13004     * tree.
13005     */
13006    public void requestLayout() {
13007        if (ViewDebug.TRACE_HIERARCHY) {
13008            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13009        }
13010
13011        if (getAccessibilityNodeProvider() != null) {
13012            throw new IllegalStateException("Views with AccessibilityNodeProvider"
13013                    + " can't have children.");
13014        }
13015
13016        mPrivateFlags |= FORCE_LAYOUT;
13017        mPrivateFlags |= INVALIDATED;
13018
13019        if (mParent != null) {
13020            if (mLayoutParams != null) {
13021                mLayoutParams.resolveWithDirection(getResolvedLayoutDirection());
13022            }
13023            if (!mParent.isLayoutRequested()) {
13024                mParent.requestLayout();
13025            }
13026        }
13027    }
13028
13029    /**
13030     * Forces this view to be laid out during the next layout pass.
13031     * This method does not call requestLayout() or forceLayout()
13032     * on the parent.
13033     */
13034    public void forceLayout() {
13035        mPrivateFlags |= FORCE_LAYOUT;
13036        mPrivateFlags |= INVALIDATED;
13037    }
13038
13039    /**
13040     * <p>
13041     * This is called to find out how big a view should be. The parent
13042     * supplies constraint information in the width and height parameters.
13043     * </p>
13044     *
13045     * <p>
13046     * The actual measurement work of a view is performed in
13047     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13048     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13049     * </p>
13050     *
13051     *
13052     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13053     *        parent
13054     * @param heightMeasureSpec Vertical space requirements as imposed by the
13055     *        parent
13056     *
13057     * @see #onMeasure(int, int)
13058     */
13059    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13060        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13061                widthMeasureSpec != mOldWidthMeasureSpec ||
13062                heightMeasureSpec != mOldHeightMeasureSpec) {
13063
13064            // first clears the measured dimension flag
13065            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13066
13067            if (ViewDebug.TRACE_HIERARCHY) {
13068                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13069            }
13070
13071            // measure ourselves, this should set the measured dimension flag back
13072            onMeasure(widthMeasureSpec, heightMeasureSpec);
13073
13074            // flag not set, setMeasuredDimension() was not invoked, we raise
13075            // an exception to warn the developer
13076            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13077                throw new IllegalStateException("onMeasure() did not set the"
13078                        + " measured dimension by calling"
13079                        + " setMeasuredDimension()");
13080            }
13081
13082            mPrivateFlags |= LAYOUT_REQUIRED;
13083        }
13084
13085        mOldWidthMeasureSpec = widthMeasureSpec;
13086        mOldHeightMeasureSpec = heightMeasureSpec;
13087    }
13088
13089    /**
13090     * <p>
13091     * Measure the view and its content to determine the measured width and the
13092     * measured height. This method is invoked by {@link #measure(int, int)} and
13093     * should be overriden by subclasses to provide accurate and efficient
13094     * measurement of their contents.
13095     * </p>
13096     *
13097     * <p>
13098     * <strong>CONTRACT:</strong> When overriding this method, you
13099     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13100     * measured width and height of this view. Failure to do so will trigger an
13101     * <code>IllegalStateException</code>, thrown by
13102     * {@link #measure(int, int)}. Calling the superclass'
13103     * {@link #onMeasure(int, int)} is a valid use.
13104     * </p>
13105     *
13106     * <p>
13107     * The base class implementation of measure defaults to the background size,
13108     * unless a larger size is allowed by the MeasureSpec. Subclasses should
13109     * override {@link #onMeasure(int, int)} to provide better measurements of
13110     * their content.
13111     * </p>
13112     *
13113     * <p>
13114     * If this method is overridden, it is the subclass's responsibility to make
13115     * sure the measured height and width are at least the view's minimum height
13116     * and width ({@link #getSuggestedMinimumHeight()} and
13117     * {@link #getSuggestedMinimumWidth()}).
13118     * </p>
13119     *
13120     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
13121     *                         The requirements are encoded with
13122     *                         {@link android.view.View.MeasureSpec}.
13123     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
13124     *                         The requirements are encoded with
13125     *                         {@link android.view.View.MeasureSpec}.
13126     *
13127     * @see #getMeasuredWidth()
13128     * @see #getMeasuredHeight()
13129     * @see #setMeasuredDimension(int, int)
13130     * @see #getSuggestedMinimumHeight()
13131     * @see #getSuggestedMinimumWidth()
13132     * @see android.view.View.MeasureSpec#getMode(int)
13133     * @see android.view.View.MeasureSpec#getSize(int)
13134     */
13135    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
13136        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
13137                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
13138    }
13139
13140    /**
13141     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
13142     * measured width and measured height. Failing to do so will trigger an
13143     * exception at measurement time.</p>
13144     *
13145     * @param measuredWidth The measured width of this view.  May be a complex
13146     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13147     * {@link #MEASURED_STATE_TOO_SMALL}.
13148     * @param measuredHeight The measured height of this view.  May be a complex
13149     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13150     * {@link #MEASURED_STATE_TOO_SMALL}.
13151     */
13152    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
13153        mMeasuredWidth = measuredWidth;
13154        mMeasuredHeight = measuredHeight;
13155
13156        mPrivateFlags |= MEASURED_DIMENSION_SET;
13157    }
13158
13159    /**
13160     * Merge two states as returned by {@link #getMeasuredState()}.
13161     * @param curState The current state as returned from a view or the result
13162     * of combining multiple views.
13163     * @param newState The new view state to combine.
13164     * @return Returns a new integer reflecting the combination of the two
13165     * states.
13166     */
13167    public static int combineMeasuredStates(int curState, int newState) {
13168        return curState | newState;
13169    }
13170
13171    /**
13172     * Version of {@link #resolveSizeAndState(int, int, int)}
13173     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
13174     */
13175    public static int resolveSize(int size, int measureSpec) {
13176        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
13177    }
13178
13179    /**
13180     * Utility to reconcile a desired size and state, with constraints imposed
13181     * by a MeasureSpec.  Will take the desired size, unless a different size
13182     * is imposed by the constraints.  The returned value is a compound integer,
13183     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
13184     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
13185     * size is smaller than the size the view wants to be.
13186     *
13187     * @param size How big the view wants to be
13188     * @param measureSpec Constraints imposed by the parent
13189     * @return Size information bit mask as defined by
13190     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13191     */
13192    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
13193        int result = size;
13194        int specMode = MeasureSpec.getMode(measureSpec);
13195        int specSize =  MeasureSpec.getSize(measureSpec);
13196        switch (specMode) {
13197        case MeasureSpec.UNSPECIFIED:
13198            result = size;
13199            break;
13200        case MeasureSpec.AT_MOST:
13201            if (specSize < size) {
13202                result = specSize | MEASURED_STATE_TOO_SMALL;
13203            } else {
13204                result = size;
13205            }
13206            break;
13207        case MeasureSpec.EXACTLY:
13208            result = specSize;
13209            break;
13210        }
13211        return result | (childMeasuredState&MEASURED_STATE_MASK);
13212    }
13213
13214    /**
13215     * Utility to return a default size. Uses the supplied size if the
13216     * MeasureSpec imposed no constraints. Will get larger if allowed
13217     * by the MeasureSpec.
13218     *
13219     * @param size Default size for this view
13220     * @param measureSpec Constraints imposed by the parent
13221     * @return The size this view should be.
13222     */
13223    public static int getDefaultSize(int size, int measureSpec) {
13224        int result = size;
13225        int specMode = MeasureSpec.getMode(measureSpec);
13226        int specSize = MeasureSpec.getSize(measureSpec);
13227
13228        switch (specMode) {
13229        case MeasureSpec.UNSPECIFIED:
13230            result = size;
13231            break;
13232        case MeasureSpec.AT_MOST:
13233        case MeasureSpec.EXACTLY:
13234            result = specSize;
13235            break;
13236        }
13237        return result;
13238    }
13239
13240    /**
13241     * Returns the suggested minimum height that the view should use. This
13242     * returns the maximum of the view's minimum height
13243     * and the background's minimum height
13244     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
13245     * <p>
13246     * When being used in {@link #onMeasure(int, int)}, the caller should still
13247     * ensure the returned height is within the requirements of the parent.
13248     *
13249     * @return The suggested minimum height of the view.
13250     */
13251    protected int getSuggestedMinimumHeight() {
13252        int suggestedMinHeight = mMinHeight;
13253
13254        if (mBGDrawable != null) {
13255            final int bgMinHeight = mBGDrawable.getMinimumHeight();
13256            if (suggestedMinHeight < bgMinHeight) {
13257                suggestedMinHeight = bgMinHeight;
13258            }
13259        }
13260
13261        return suggestedMinHeight;
13262    }
13263
13264    /**
13265     * Returns the suggested minimum width that the view should use. This
13266     * returns the maximum of the view's minimum width)
13267     * and the background's minimum width
13268     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
13269     * <p>
13270     * When being used in {@link #onMeasure(int, int)}, the caller should still
13271     * ensure the returned width is within the requirements of the parent.
13272     *
13273     * @return The suggested minimum width of the view.
13274     */
13275    protected int getSuggestedMinimumWidth() {
13276        int suggestedMinWidth = mMinWidth;
13277
13278        if (mBGDrawable != null) {
13279            final int bgMinWidth = mBGDrawable.getMinimumWidth();
13280            if (suggestedMinWidth < bgMinWidth) {
13281                suggestedMinWidth = bgMinWidth;
13282            }
13283        }
13284
13285        return suggestedMinWidth;
13286    }
13287
13288    /**
13289     * Sets the minimum height of the view. It is not guaranteed the view will
13290     * be able to achieve this minimum height (for example, if its parent layout
13291     * constrains it with less available height).
13292     *
13293     * @param minHeight The minimum height the view will try to be.
13294     */
13295    public void setMinimumHeight(int minHeight) {
13296        mMinHeight = minHeight;
13297    }
13298
13299    /**
13300     * Sets the minimum width of the view. It is not guaranteed the view will
13301     * be able to achieve this minimum width (for example, if its parent layout
13302     * constrains it with less available width).
13303     *
13304     * @param minWidth The minimum width the view will try to be.
13305     */
13306    public void setMinimumWidth(int minWidth) {
13307        mMinWidth = minWidth;
13308    }
13309
13310    /**
13311     * Get the animation currently associated with this view.
13312     *
13313     * @return The animation that is currently playing or
13314     *         scheduled to play for this view.
13315     */
13316    public Animation getAnimation() {
13317        return mCurrentAnimation;
13318    }
13319
13320    /**
13321     * Start the specified animation now.
13322     *
13323     * @param animation the animation to start now
13324     */
13325    public void startAnimation(Animation animation) {
13326        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
13327        setAnimation(animation);
13328        invalidateParentCaches();
13329        invalidate(true);
13330    }
13331
13332    /**
13333     * Cancels any animations for this view.
13334     */
13335    public void clearAnimation() {
13336        if (mCurrentAnimation != null) {
13337            mCurrentAnimation.detach();
13338        }
13339        mCurrentAnimation = null;
13340        invalidateParentIfNeeded();
13341    }
13342
13343    /**
13344     * Sets the next animation to play for this view.
13345     * If you want the animation to play immediately, use
13346     * startAnimation. This method provides allows fine-grained
13347     * control over the start time and invalidation, but you
13348     * must make sure that 1) the animation has a start time set, and
13349     * 2) the view will be invalidated when the animation is supposed to
13350     * start.
13351     *
13352     * @param animation The next animation, or null.
13353     */
13354    public void setAnimation(Animation animation) {
13355        mCurrentAnimation = animation;
13356        if (animation != null) {
13357            animation.reset();
13358        }
13359    }
13360
13361    /**
13362     * Invoked by a parent ViewGroup to notify the start of the animation
13363     * currently associated with this view. If you override this method,
13364     * always call super.onAnimationStart();
13365     *
13366     * @see #setAnimation(android.view.animation.Animation)
13367     * @see #getAnimation()
13368     */
13369    protected void onAnimationStart() {
13370        mPrivateFlags |= ANIMATION_STARTED;
13371    }
13372
13373    /**
13374     * Invoked by a parent ViewGroup to notify the end of the animation
13375     * currently associated with this view. If you override this method,
13376     * always call super.onAnimationEnd();
13377     *
13378     * @see #setAnimation(android.view.animation.Animation)
13379     * @see #getAnimation()
13380     */
13381    protected void onAnimationEnd() {
13382        mPrivateFlags &= ~ANIMATION_STARTED;
13383    }
13384
13385    /**
13386     * Invoked if there is a Transform that involves alpha. Subclass that can
13387     * draw themselves with the specified alpha should return true, and then
13388     * respect that alpha when their onDraw() is called. If this returns false
13389     * then the view may be redirected to draw into an offscreen buffer to
13390     * fulfill the request, which will look fine, but may be slower than if the
13391     * subclass handles it internally. The default implementation returns false.
13392     *
13393     * @param alpha The alpha (0..255) to apply to the view's drawing
13394     * @return true if the view can draw with the specified alpha.
13395     */
13396    protected boolean onSetAlpha(int alpha) {
13397        return false;
13398    }
13399
13400    /**
13401     * This is used by the RootView to perform an optimization when
13402     * the view hierarchy contains one or several SurfaceView.
13403     * SurfaceView is always considered transparent, but its children are not,
13404     * therefore all View objects remove themselves from the global transparent
13405     * region (passed as a parameter to this function).
13406     *
13407     * @param region The transparent region for this ViewAncestor (window).
13408     *
13409     * @return Returns true if the effective visibility of the view at this
13410     * point is opaque, regardless of the transparent region; returns false
13411     * if it is possible for underlying windows to be seen behind the view.
13412     *
13413     * {@hide}
13414     */
13415    public boolean gatherTransparentRegion(Region region) {
13416        final AttachInfo attachInfo = mAttachInfo;
13417        if (region != null && attachInfo != null) {
13418            final int pflags = mPrivateFlags;
13419            if ((pflags & SKIP_DRAW) == 0) {
13420                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
13421                // remove it from the transparent region.
13422                final int[] location = attachInfo.mTransparentLocation;
13423                getLocationInWindow(location);
13424                region.op(location[0], location[1], location[0] + mRight - mLeft,
13425                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
13426            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
13427                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
13428                // exists, so we remove the background drawable's non-transparent
13429                // parts from this transparent region.
13430                applyDrawableToTransparentRegion(mBGDrawable, region);
13431            }
13432        }
13433        return true;
13434    }
13435
13436    /**
13437     * Play a sound effect for this view.
13438     *
13439     * <p>The framework will play sound effects for some built in actions, such as
13440     * clicking, but you may wish to play these effects in your widget,
13441     * for instance, for internal navigation.
13442     *
13443     * <p>The sound effect will only be played if sound effects are enabled by the user, and
13444     * {@link #isSoundEffectsEnabled()} is true.
13445     *
13446     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
13447     */
13448    public void playSoundEffect(int soundConstant) {
13449        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
13450            return;
13451        }
13452        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
13453    }
13454
13455    /**
13456     * BZZZTT!!1!
13457     *
13458     * <p>Provide haptic feedback to the user for this view.
13459     *
13460     * <p>The framework will provide haptic feedback for some built in actions,
13461     * such as long presses, but you may wish to provide feedback for your
13462     * own widget.
13463     *
13464     * <p>The feedback will only be performed if
13465     * {@link #isHapticFeedbackEnabled()} is true.
13466     *
13467     * @param feedbackConstant One of the constants defined in
13468     * {@link HapticFeedbackConstants}
13469     */
13470    public boolean performHapticFeedback(int feedbackConstant) {
13471        return performHapticFeedback(feedbackConstant, 0);
13472    }
13473
13474    /**
13475     * BZZZTT!!1!
13476     *
13477     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
13478     *
13479     * @param feedbackConstant One of the constants defined in
13480     * {@link HapticFeedbackConstants}
13481     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
13482     */
13483    public boolean performHapticFeedback(int feedbackConstant, int flags) {
13484        if (mAttachInfo == null) {
13485            return false;
13486        }
13487        //noinspection SimplifiableIfStatement
13488        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
13489                && !isHapticFeedbackEnabled()) {
13490            return false;
13491        }
13492        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13493                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13494    }
13495
13496    /**
13497     * Request that the visibility of the status bar be changed.
13498     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13499     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13500     */
13501    public void setSystemUiVisibility(int visibility) {
13502        if (visibility != mSystemUiVisibility) {
13503            mSystemUiVisibility = visibility;
13504            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13505                mParent.recomputeViewAttributes(this);
13506            }
13507        }
13508    }
13509
13510    /**
13511     * Returns the status bar visibility that this view has requested.
13512     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13513     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13514     */
13515    public int getSystemUiVisibility() {
13516        return mSystemUiVisibility;
13517    }
13518
13519    /**
13520     * Set a listener to receive callbacks when the visibility of the system bar changes.
13521     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13522     */
13523    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13524        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
13525        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13526            mParent.recomputeViewAttributes(this);
13527        }
13528    }
13529
13530    /**
13531     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13532     * the view hierarchy.
13533     */
13534    public void dispatchSystemUiVisibilityChanged(int visibility) {
13535        ListenerInfo li = mListenerInfo;
13536        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13537            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13538                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13539        }
13540    }
13541
13542    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13543        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13544        if (val != mSystemUiVisibility) {
13545            setSystemUiVisibility(val);
13546        }
13547    }
13548
13549    /**
13550     * Creates an image that the system displays during the drag and drop
13551     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13552     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13553     * appearance as the given View. The default also positions the center of the drag shadow
13554     * directly under the touch point. If no View is provided (the constructor with no parameters
13555     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13556     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13557     * default is an invisible drag shadow.
13558     * <p>
13559     * You are not required to use the View you provide to the constructor as the basis of the
13560     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13561     * anything you want as the drag shadow.
13562     * </p>
13563     * <p>
13564     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13565     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13566     *  size and position of the drag shadow. It uses this data to construct a
13567     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13568     *  so that your application can draw the shadow image in the Canvas.
13569     * </p>
13570     *
13571     * <div class="special reference">
13572     * <h3>Developer Guides</h3>
13573     * <p>For a guide to implementing drag and drop features, read the
13574     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
13575     * </div>
13576     */
13577    public static class DragShadowBuilder {
13578        private final WeakReference<View> mView;
13579
13580        /**
13581         * Constructs a shadow image builder based on a View. By default, the resulting drag
13582         * shadow will have the same appearance and dimensions as the View, with the touch point
13583         * over the center of the View.
13584         * @param view A View. Any View in scope can be used.
13585         */
13586        public DragShadowBuilder(View view) {
13587            mView = new WeakReference<View>(view);
13588        }
13589
13590        /**
13591         * Construct a shadow builder object with no associated View.  This
13592         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13593         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13594         * to supply the drag shadow's dimensions and appearance without
13595         * reference to any View object. If they are not overridden, then the result is an
13596         * invisible drag shadow.
13597         */
13598        public DragShadowBuilder() {
13599            mView = new WeakReference<View>(null);
13600        }
13601
13602        /**
13603         * Returns the View object that had been passed to the
13604         * {@link #View.DragShadowBuilder(View)}
13605         * constructor.  If that View parameter was {@code null} or if the
13606         * {@link #View.DragShadowBuilder()}
13607         * constructor was used to instantiate the builder object, this method will return
13608         * null.
13609         *
13610         * @return The View object associate with this builder object.
13611         */
13612        @SuppressWarnings({"JavadocReference"})
13613        final public View getView() {
13614            return mView.get();
13615        }
13616
13617        /**
13618         * Provides the metrics for the shadow image. These include the dimensions of
13619         * the shadow image, and the point within that shadow that should
13620         * be centered under the touch location while dragging.
13621         * <p>
13622         * The default implementation sets the dimensions of the shadow to be the
13623         * same as the dimensions of the View itself and centers the shadow under
13624         * the touch point.
13625         * </p>
13626         *
13627         * @param shadowSize A {@link android.graphics.Point} containing the width and height
13628         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
13629         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
13630         * image.
13631         *
13632         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
13633         * shadow image that should be underneath the touch point during the drag and drop
13634         * operation. Your application must set {@link android.graphics.Point#x} to the
13635         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
13636         */
13637        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
13638            final View view = mView.get();
13639            if (view != null) {
13640                shadowSize.set(view.getWidth(), view.getHeight());
13641                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
13642            } else {
13643                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
13644            }
13645        }
13646
13647        /**
13648         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
13649         * based on the dimensions it received from the
13650         * {@link #onProvideShadowMetrics(Point, Point)} callback.
13651         *
13652         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
13653         */
13654        public void onDrawShadow(Canvas canvas) {
13655            final View view = mView.get();
13656            if (view != null) {
13657                view.draw(canvas);
13658            } else {
13659                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
13660            }
13661        }
13662    }
13663
13664    /**
13665     * Starts a drag and drop operation. When your application calls this method, it passes a
13666     * {@link android.view.View.DragShadowBuilder} object to the system. The
13667     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
13668     * to get metrics for the drag shadow, and then calls the object's
13669     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
13670     * <p>
13671     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
13672     *  drag events to all the View objects in your application that are currently visible. It does
13673     *  this either by calling the View object's drag listener (an implementation of
13674     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
13675     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
13676     *  Both are passed a {@link android.view.DragEvent} object that has a
13677     *  {@link android.view.DragEvent#getAction()} value of
13678     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
13679     * </p>
13680     * <p>
13681     * Your application can invoke startDrag() on any attached View object. The View object does not
13682     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
13683     * be related to the View the user selected for dragging.
13684     * </p>
13685     * @param data A {@link android.content.ClipData} object pointing to the data to be
13686     * transferred by the drag and drop operation.
13687     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
13688     * drag shadow.
13689     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
13690     * drop operation. This Object is put into every DragEvent object sent by the system during the
13691     * current drag.
13692     * <p>
13693     * myLocalState is a lightweight mechanism for the sending information from the dragged View
13694     * to the target Views. For example, it can contain flags that differentiate between a
13695     * a copy operation and a move operation.
13696     * </p>
13697     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
13698     * so the parameter should be set to 0.
13699     * @return {@code true} if the method completes successfully, or
13700     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
13701     * do a drag, and so no drag operation is in progress.
13702     */
13703    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
13704            Object myLocalState, int flags) {
13705        if (ViewDebug.DEBUG_DRAG) {
13706            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
13707        }
13708        boolean okay = false;
13709
13710        Point shadowSize = new Point();
13711        Point shadowTouchPoint = new Point();
13712        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
13713
13714        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
13715                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
13716            throw new IllegalStateException("Drag shadow dimensions must not be negative");
13717        }
13718
13719        if (ViewDebug.DEBUG_DRAG) {
13720            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
13721                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
13722        }
13723        Surface surface = new Surface();
13724        try {
13725            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
13726                    flags, shadowSize.x, shadowSize.y, surface);
13727            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
13728                    + " surface=" + surface);
13729            if (token != null) {
13730                Canvas canvas = surface.lockCanvas(null);
13731                try {
13732                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
13733                    shadowBuilder.onDrawShadow(canvas);
13734                } finally {
13735                    surface.unlockCanvasAndPost(canvas);
13736                }
13737
13738                final ViewRootImpl root = getViewRootImpl();
13739
13740                // Cache the local state object for delivery with DragEvents
13741                root.setLocalDragState(myLocalState);
13742
13743                // repurpose 'shadowSize' for the last touch point
13744                root.getLastTouchPoint(shadowSize);
13745
13746                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
13747                        shadowSize.x, shadowSize.y,
13748                        shadowTouchPoint.x, shadowTouchPoint.y, data);
13749                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
13750
13751                // Off and running!  Release our local surface instance; the drag
13752                // shadow surface is now managed by the system process.
13753                surface.release();
13754            }
13755        } catch (Exception e) {
13756            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
13757            surface.destroy();
13758        }
13759
13760        return okay;
13761    }
13762
13763    /**
13764     * Handles drag events sent by the system following a call to
13765     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
13766     *<p>
13767     * When the system calls this method, it passes a
13768     * {@link android.view.DragEvent} object. A call to
13769     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
13770     * in DragEvent. The method uses these to determine what is happening in the drag and drop
13771     * operation.
13772     * @param event The {@link android.view.DragEvent} sent by the system.
13773     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
13774     * in DragEvent, indicating the type of drag event represented by this object.
13775     * @return {@code true} if the method was successful, otherwise {@code false}.
13776     * <p>
13777     *  The method should return {@code true} in response to an action type of
13778     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
13779     *  operation.
13780     * </p>
13781     * <p>
13782     *  The method should also return {@code true} in response to an action type of
13783     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
13784     *  {@code false} if it didn't.
13785     * </p>
13786     */
13787    public boolean onDragEvent(DragEvent event) {
13788        return false;
13789    }
13790
13791    /**
13792     * Detects if this View is enabled and has a drag event listener.
13793     * If both are true, then it calls the drag event listener with the
13794     * {@link android.view.DragEvent} it received. If the drag event listener returns
13795     * {@code true}, then dispatchDragEvent() returns {@code true}.
13796     * <p>
13797     * For all other cases, the method calls the
13798     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
13799     * method and returns its result.
13800     * </p>
13801     * <p>
13802     * This ensures that a drag event is always consumed, even if the View does not have a drag
13803     * event listener. However, if the View has a listener and the listener returns true, then
13804     * onDragEvent() is not called.
13805     * </p>
13806     */
13807    public boolean dispatchDragEvent(DragEvent event) {
13808        //noinspection SimplifiableIfStatement
13809        ListenerInfo li = mListenerInfo;
13810        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
13811                && li.mOnDragListener.onDrag(this, event)) {
13812            return true;
13813        }
13814        return onDragEvent(event);
13815    }
13816
13817    boolean canAcceptDrag() {
13818        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
13819    }
13820
13821    /**
13822     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
13823     * it is ever exposed at all.
13824     * @hide
13825     */
13826    public void onCloseSystemDialogs(String reason) {
13827    }
13828
13829    /**
13830     * Given a Drawable whose bounds have been set to draw into this view,
13831     * update a Region being computed for
13832     * {@link #gatherTransparentRegion(android.graphics.Region)} so
13833     * that any non-transparent parts of the Drawable are removed from the
13834     * given transparent region.
13835     *
13836     * @param dr The Drawable whose transparency is to be applied to the region.
13837     * @param region A Region holding the current transparency information,
13838     * where any parts of the region that are set are considered to be
13839     * transparent.  On return, this region will be modified to have the
13840     * transparency information reduced by the corresponding parts of the
13841     * Drawable that are not transparent.
13842     * {@hide}
13843     */
13844    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
13845        if (DBG) {
13846            Log.i("View", "Getting transparent region for: " + this);
13847        }
13848        final Region r = dr.getTransparentRegion();
13849        final Rect db = dr.getBounds();
13850        final AttachInfo attachInfo = mAttachInfo;
13851        if (r != null && attachInfo != null) {
13852            final int w = getRight()-getLeft();
13853            final int h = getBottom()-getTop();
13854            if (db.left > 0) {
13855                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
13856                r.op(0, 0, db.left, h, Region.Op.UNION);
13857            }
13858            if (db.right < w) {
13859                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
13860                r.op(db.right, 0, w, h, Region.Op.UNION);
13861            }
13862            if (db.top > 0) {
13863                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
13864                r.op(0, 0, w, db.top, Region.Op.UNION);
13865            }
13866            if (db.bottom < h) {
13867                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
13868                r.op(0, db.bottom, w, h, Region.Op.UNION);
13869            }
13870            final int[] location = attachInfo.mTransparentLocation;
13871            getLocationInWindow(location);
13872            r.translate(location[0], location[1]);
13873            region.op(r, Region.Op.INTERSECT);
13874        } else {
13875            region.op(db, Region.Op.DIFFERENCE);
13876        }
13877    }
13878
13879    private void checkForLongClick(int delayOffset) {
13880        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
13881            mHasPerformedLongPress = false;
13882
13883            if (mPendingCheckForLongPress == null) {
13884                mPendingCheckForLongPress = new CheckForLongPress();
13885            }
13886            mPendingCheckForLongPress.rememberWindowAttachCount();
13887            postDelayed(mPendingCheckForLongPress,
13888                    ViewConfiguration.getLongPressTimeout() - delayOffset);
13889        }
13890    }
13891
13892    /**
13893     * Inflate a view from an XML resource.  This convenience method wraps the {@link
13894     * LayoutInflater} class, which provides a full range of options for view inflation.
13895     *
13896     * @param context The Context object for your activity or application.
13897     * @param resource The resource ID to inflate
13898     * @param root A view group that will be the parent.  Used to properly inflate the
13899     * layout_* parameters.
13900     * @see LayoutInflater
13901     */
13902    public static View inflate(Context context, int resource, ViewGroup root) {
13903        LayoutInflater factory = LayoutInflater.from(context);
13904        return factory.inflate(resource, root);
13905    }
13906
13907    /**
13908     * Scroll the view with standard behavior for scrolling beyond the normal
13909     * content boundaries. Views that call this method should override
13910     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
13911     * results of an over-scroll operation.
13912     *
13913     * Views can use this method to handle any touch or fling-based scrolling.
13914     *
13915     * @param deltaX Change in X in pixels
13916     * @param deltaY Change in Y in pixels
13917     * @param scrollX Current X scroll value in pixels before applying deltaX
13918     * @param scrollY Current Y scroll value in pixels before applying deltaY
13919     * @param scrollRangeX Maximum content scroll range along the X axis
13920     * @param scrollRangeY Maximum content scroll range along the Y axis
13921     * @param maxOverScrollX Number of pixels to overscroll by in either direction
13922     *          along the X axis.
13923     * @param maxOverScrollY Number of pixels to overscroll by in either direction
13924     *          along the Y axis.
13925     * @param isTouchEvent true if this scroll operation is the result of a touch event.
13926     * @return true if scrolling was clamped to an over-scroll boundary along either
13927     *          axis, false otherwise.
13928     */
13929    @SuppressWarnings({"UnusedParameters"})
13930    protected boolean overScrollBy(int deltaX, int deltaY,
13931            int scrollX, int scrollY,
13932            int scrollRangeX, int scrollRangeY,
13933            int maxOverScrollX, int maxOverScrollY,
13934            boolean isTouchEvent) {
13935        final int overScrollMode = mOverScrollMode;
13936        final boolean canScrollHorizontal =
13937                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
13938        final boolean canScrollVertical =
13939                computeVerticalScrollRange() > computeVerticalScrollExtent();
13940        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
13941                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13942        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
13943                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
13944
13945        int newScrollX = scrollX + deltaX;
13946        if (!overScrollHorizontal) {
13947            maxOverScrollX = 0;
13948        }
13949
13950        int newScrollY = scrollY + deltaY;
13951        if (!overScrollVertical) {
13952            maxOverScrollY = 0;
13953        }
13954
13955        // Clamp values if at the limits and record
13956        final int left = -maxOverScrollX;
13957        final int right = maxOverScrollX + scrollRangeX;
13958        final int top = -maxOverScrollY;
13959        final int bottom = maxOverScrollY + scrollRangeY;
13960
13961        boolean clampedX = false;
13962        if (newScrollX > right) {
13963            newScrollX = right;
13964            clampedX = true;
13965        } else if (newScrollX < left) {
13966            newScrollX = left;
13967            clampedX = true;
13968        }
13969
13970        boolean clampedY = false;
13971        if (newScrollY > bottom) {
13972            newScrollY = bottom;
13973            clampedY = true;
13974        } else if (newScrollY < top) {
13975            newScrollY = top;
13976            clampedY = true;
13977        }
13978
13979        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
13980
13981        return clampedX || clampedY;
13982    }
13983
13984    /**
13985     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
13986     * respond to the results of an over-scroll operation.
13987     *
13988     * @param scrollX New X scroll value in pixels
13989     * @param scrollY New Y scroll value in pixels
13990     * @param clampedX True if scrollX was clamped to an over-scroll boundary
13991     * @param clampedY True if scrollY was clamped to an over-scroll boundary
13992     */
13993    protected void onOverScrolled(int scrollX, int scrollY,
13994            boolean clampedX, boolean clampedY) {
13995        // Intentionally empty.
13996    }
13997
13998    /**
13999     * Returns the over-scroll mode for this view. The result will be
14000     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14001     * (allow over-scrolling only if the view content is larger than the container),
14002     * or {@link #OVER_SCROLL_NEVER}.
14003     *
14004     * @return This view's over-scroll mode.
14005     */
14006    public int getOverScrollMode() {
14007        return mOverScrollMode;
14008    }
14009
14010    /**
14011     * Set the over-scroll mode for this view. Valid over-scroll modes are
14012     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14013     * (allow over-scrolling only if the view content is larger than the container),
14014     * or {@link #OVER_SCROLL_NEVER}.
14015     *
14016     * Setting the over-scroll mode of a view will have an effect only if the
14017     * view is capable of scrolling.
14018     *
14019     * @param overScrollMode The new over-scroll mode for this view.
14020     */
14021    public void setOverScrollMode(int overScrollMode) {
14022        if (overScrollMode != OVER_SCROLL_ALWAYS &&
14023                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
14024                overScrollMode != OVER_SCROLL_NEVER) {
14025            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
14026        }
14027        mOverScrollMode = overScrollMode;
14028    }
14029
14030    /**
14031     * Gets a scale factor that determines the distance the view should scroll
14032     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
14033     * @return The vertical scroll scale factor.
14034     * @hide
14035     */
14036    protected float getVerticalScrollFactor() {
14037        if (mVerticalScrollFactor == 0) {
14038            TypedValue outValue = new TypedValue();
14039            if (!mContext.getTheme().resolveAttribute(
14040                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
14041                throw new IllegalStateException(
14042                        "Expected theme to define listPreferredItemHeight.");
14043            }
14044            mVerticalScrollFactor = outValue.getDimension(
14045                    mContext.getResources().getDisplayMetrics());
14046        }
14047        return mVerticalScrollFactor;
14048    }
14049
14050    /**
14051     * Gets a scale factor that determines the distance the view should scroll
14052     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
14053     * @return The horizontal scroll scale factor.
14054     * @hide
14055     */
14056    protected float getHorizontalScrollFactor() {
14057        // TODO: Should use something else.
14058        return getVerticalScrollFactor();
14059    }
14060
14061    /**
14062     * Return the value specifying the text direction or policy that was set with
14063     * {@link #setTextDirection(int)}.
14064     *
14065     * @return the defined text direction. It can be one of:
14066     *
14067     * {@link #TEXT_DIRECTION_INHERIT},
14068     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14069     * {@link #TEXT_DIRECTION_ANY_RTL},
14070     * {@link #TEXT_DIRECTION_LTR},
14071     * {@link #TEXT_DIRECTION_RTL},
14072     * {@link #TEXT_DIRECTION_LOCALE},
14073     *
14074     */
14075    public int getTextDirection() {
14076        return mTextDirection;
14077    }
14078
14079    /**
14080     * Set the text direction.
14081     *
14082     * @param textDirection the direction to set. Should be one of:
14083     *
14084     * {@link #TEXT_DIRECTION_INHERIT},
14085     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14086     * {@link #TEXT_DIRECTION_ANY_RTL},
14087     * {@link #TEXT_DIRECTION_LTR},
14088     * {@link #TEXT_DIRECTION_RTL},
14089     * {@link #TEXT_DIRECTION_LOCALE},
14090     *
14091     */
14092    public void setTextDirection(int textDirection) {
14093        if (textDirection != mTextDirection) {
14094            mTextDirection = textDirection;
14095            resetResolvedTextDirection();
14096            requestLayout();
14097        }
14098    }
14099
14100    /**
14101     * Return the resolved text direction.
14102     *
14103     * @return the resolved text direction. Return one of:
14104     *
14105     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14106     * {@link #TEXT_DIRECTION_ANY_RTL},
14107     * {@link #TEXT_DIRECTION_LTR},
14108     * {@link #TEXT_DIRECTION_RTL},
14109     * {@link #TEXT_DIRECTION_LOCALE},
14110     *
14111     */
14112    public int getResolvedTextDirection() {
14113        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
14114            resolveTextDirection();
14115        }
14116        return mResolvedTextDirection;
14117    }
14118
14119    /**
14120     * Resolve the text direction.
14121     *
14122     */
14123    protected void resolveTextDirection() {
14124        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
14125            mResolvedTextDirection = mTextDirection;
14126            return;
14127        }
14128        if (mParent != null && mParent instanceof ViewGroup) {
14129            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
14130            return;
14131        }
14132        mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
14133    }
14134
14135    /**
14136     * Reset resolved text direction. Will be resolved during a call to getResolvedTextDirection().
14137     *
14138     */
14139    protected void resetResolvedTextDirection() {
14140        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
14141    }
14142
14143    //
14144    // Properties
14145    //
14146    /**
14147     * A Property wrapper around the <code>alpha</code> functionality handled by the
14148     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
14149     */
14150    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
14151        @Override
14152        public void setValue(View object, float value) {
14153            object.setAlpha(value);
14154        }
14155
14156        @Override
14157        public Float get(View object) {
14158            return object.getAlpha();
14159        }
14160    };
14161
14162    /**
14163     * A Property wrapper around the <code>translationX</code> functionality handled by the
14164     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
14165     */
14166    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
14167        @Override
14168        public void setValue(View object, float value) {
14169            object.setTranslationX(value);
14170        }
14171
14172                @Override
14173        public Float get(View object) {
14174            return object.getTranslationX();
14175        }
14176    };
14177
14178    /**
14179     * A Property wrapper around the <code>translationY</code> functionality handled by the
14180     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
14181     */
14182    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
14183        @Override
14184        public void setValue(View object, float value) {
14185            object.setTranslationY(value);
14186        }
14187
14188        @Override
14189        public Float get(View object) {
14190            return object.getTranslationY();
14191        }
14192    };
14193
14194    /**
14195     * A Property wrapper around the <code>x</code> functionality handled by the
14196     * {@link View#setX(float)} and {@link View#getX()} methods.
14197     */
14198    public static final Property<View, Float> X = new FloatProperty<View>("x") {
14199        @Override
14200        public void setValue(View object, float value) {
14201            object.setX(value);
14202        }
14203
14204        @Override
14205        public Float get(View object) {
14206            return object.getX();
14207        }
14208    };
14209
14210    /**
14211     * A Property wrapper around the <code>y</code> functionality handled by the
14212     * {@link View#setY(float)} and {@link View#getY()} methods.
14213     */
14214    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
14215        @Override
14216        public void setValue(View object, float value) {
14217            object.setY(value);
14218        }
14219
14220        @Override
14221        public Float get(View object) {
14222            return object.getY();
14223        }
14224    };
14225
14226    /**
14227     * A Property wrapper around the <code>rotation</code> functionality handled by the
14228     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
14229     */
14230    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
14231        @Override
14232        public void setValue(View object, float value) {
14233            object.setRotation(value);
14234        }
14235
14236        @Override
14237        public Float get(View object) {
14238            return object.getRotation();
14239        }
14240    };
14241
14242    /**
14243     * A Property wrapper around the <code>rotationX</code> functionality handled by the
14244     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
14245     */
14246    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
14247        @Override
14248        public void setValue(View object, float value) {
14249            object.setRotationX(value);
14250        }
14251
14252        @Override
14253        public Float get(View object) {
14254            return object.getRotationX();
14255        }
14256    };
14257
14258    /**
14259     * A Property wrapper around the <code>rotationY</code> functionality handled by the
14260     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
14261     */
14262    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
14263        @Override
14264        public void setValue(View object, float value) {
14265            object.setRotationY(value);
14266        }
14267
14268        @Override
14269        public Float get(View object) {
14270            return object.getRotationY();
14271        }
14272    };
14273
14274    /**
14275     * A Property wrapper around the <code>scaleX</code> functionality handled by the
14276     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
14277     */
14278    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
14279        @Override
14280        public void setValue(View object, float value) {
14281            object.setScaleX(value);
14282        }
14283
14284        @Override
14285        public Float get(View object) {
14286            return object.getScaleX();
14287        }
14288    };
14289
14290    /**
14291     * A Property wrapper around the <code>scaleY</code> functionality handled by the
14292     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
14293     */
14294    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
14295        @Override
14296        public void setValue(View object, float value) {
14297            object.setScaleY(value);
14298        }
14299
14300        @Override
14301        public Float get(View object) {
14302            return object.getScaleY();
14303        }
14304    };
14305
14306    /**
14307     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
14308     * Each MeasureSpec represents a requirement for either the width or the height.
14309     * A MeasureSpec is comprised of a size and a mode. There are three possible
14310     * modes:
14311     * <dl>
14312     * <dt>UNSPECIFIED</dt>
14313     * <dd>
14314     * The parent has not imposed any constraint on the child. It can be whatever size
14315     * it wants.
14316     * </dd>
14317     *
14318     * <dt>EXACTLY</dt>
14319     * <dd>
14320     * The parent has determined an exact size for the child. The child is going to be
14321     * given those bounds regardless of how big it wants to be.
14322     * </dd>
14323     *
14324     * <dt>AT_MOST</dt>
14325     * <dd>
14326     * The child can be as large as it wants up to the specified size.
14327     * </dd>
14328     * </dl>
14329     *
14330     * MeasureSpecs are implemented as ints to reduce object allocation. This class
14331     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
14332     */
14333    public static class MeasureSpec {
14334        private static final int MODE_SHIFT = 30;
14335        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
14336
14337        /**
14338         * Measure specification mode: The parent has not imposed any constraint
14339         * on the child. It can be whatever size it wants.
14340         */
14341        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
14342
14343        /**
14344         * Measure specification mode: The parent has determined an exact size
14345         * for the child. The child is going to be given those bounds regardless
14346         * of how big it wants to be.
14347         */
14348        public static final int EXACTLY     = 1 << MODE_SHIFT;
14349
14350        /**
14351         * Measure specification mode: The child can be as large as it wants up
14352         * to the specified size.
14353         */
14354        public static final int AT_MOST     = 2 << MODE_SHIFT;
14355
14356        /**
14357         * Creates a measure specification based on the supplied size and mode.
14358         *
14359         * The mode must always be one of the following:
14360         * <ul>
14361         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
14362         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
14363         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
14364         * </ul>
14365         *
14366         * @param size the size of the measure specification
14367         * @param mode the mode of the measure specification
14368         * @return the measure specification based on size and mode
14369         */
14370        public static int makeMeasureSpec(int size, int mode) {
14371            return size + mode;
14372        }
14373
14374        /**
14375         * Extracts the mode from the supplied measure specification.
14376         *
14377         * @param measureSpec the measure specification to extract the mode from
14378         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
14379         *         {@link android.view.View.MeasureSpec#AT_MOST} or
14380         *         {@link android.view.View.MeasureSpec#EXACTLY}
14381         */
14382        public static int getMode(int measureSpec) {
14383            return (measureSpec & MODE_MASK);
14384        }
14385
14386        /**
14387         * Extracts the size from the supplied measure specification.
14388         *
14389         * @param measureSpec the measure specification to extract the size from
14390         * @return the size in pixels defined in the supplied measure specification
14391         */
14392        public static int getSize(int measureSpec) {
14393            return (measureSpec & ~MODE_MASK);
14394        }
14395
14396        /**
14397         * Returns a String representation of the specified measure
14398         * specification.
14399         *
14400         * @param measureSpec the measure specification to convert to a String
14401         * @return a String with the following format: "MeasureSpec: MODE SIZE"
14402         */
14403        public static String toString(int measureSpec) {
14404            int mode = getMode(measureSpec);
14405            int size = getSize(measureSpec);
14406
14407            StringBuilder sb = new StringBuilder("MeasureSpec: ");
14408
14409            if (mode == UNSPECIFIED)
14410                sb.append("UNSPECIFIED ");
14411            else if (mode == EXACTLY)
14412                sb.append("EXACTLY ");
14413            else if (mode == AT_MOST)
14414                sb.append("AT_MOST ");
14415            else
14416                sb.append(mode).append(" ");
14417
14418            sb.append(size);
14419            return sb.toString();
14420        }
14421    }
14422
14423    class CheckForLongPress implements Runnable {
14424
14425        private int mOriginalWindowAttachCount;
14426
14427        public void run() {
14428            if (isPressed() && (mParent != null)
14429                    && mOriginalWindowAttachCount == mWindowAttachCount) {
14430                if (performLongClick()) {
14431                    mHasPerformedLongPress = true;
14432                }
14433            }
14434        }
14435
14436        public void rememberWindowAttachCount() {
14437            mOriginalWindowAttachCount = mWindowAttachCount;
14438        }
14439    }
14440
14441    private final class CheckForTap implements Runnable {
14442        public void run() {
14443            mPrivateFlags &= ~PREPRESSED;
14444            mPrivateFlags |= PRESSED;
14445            refreshDrawableState();
14446            checkForLongClick(ViewConfiguration.getTapTimeout());
14447        }
14448    }
14449
14450    private final class PerformClick implements Runnable {
14451        public void run() {
14452            performClick();
14453        }
14454    }
14455
14456    /** @hide */
14457    public void hackTurnOffWindowResizeAnim(boolean off) {
14458        mAttachInfo.mTurnOffWindowResizeAnim = off;
14459    }
14460
14461    /**
14462     * This method returns a ViewPropertyAnimator object, which can be used to animate
14463     * specific properties on this View.
14464     *
14465     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
14466     */
14467    public ViewPropertyAnimator animate() {
14468        if (mAnimator == null) {
14469            mAnimator = new ViewPropertyAnimator(this);
14470        }
14471        return mAnimator;
14472    }
14473
14474    /**
14475     * Interface definition for a callback to be invoked when a key event is
14476     * dispatched to this view. The callback will be invoked before the key
14477     * event is given to the view.
14478     */
14479    public interface OnKeyListener {
14480        /**
14481         * Called when a key is dispatched to a view. This allows listeners to
14482         * get a chance to respond before the target view.
14483         *
14484         * @param v The view the key has been dispatched to.
14485         * @param keyCode The code for the physical key that was pressed
14486         * @param event The KeyEvent object containing full information about
14487         *        the event.
14488         * @return True if the listener has consumed the event, false otherwise.
14489         */
14490        boolean onKey(View v, int keyCode, KeyEvent event);
14491    }
14492
14493    /**
14494     * Interface definition for a callback to be invoked when a touch event is
14495     * dispatched to this view. The callback will be invoked before the touch
14496     * event is given to the view.
14497     */
14498    public interface OnTouchListener {
14499        /**
14500         * Called when a touch event is dispatched to a view. This allows listeners to
14501         * get a chance to respond before the target view.
14502         *
14503         * @param v The view the touch event has been dispatched to.
14504         * @param event The MotionEvent object containing full information about
14505         *        the event.
14506         * @return True if the listener has consumed the event, false otherwise.
14507         */
14508        boolean onTouch(View v, MotionEvent event);
14509    }
14510
14511    /**
14512     * Interface definition for a callback to be invoked when a hover event is
14513     * dispatched to this view. The callback will be invoked before the hover
14514     * event is given to the view.
14515     */
14516    public interface OnHoverListener {
14517        /**
14518         * Called when a hover event is dispatched to a view. This allows listeners to
14519         * get a chance to respond before the target view.
14520         *
14521         * @param v The view the hover event has been dispatched to.
14522         * @param event The MotionEvent object containing full information about
14523         *        the event.
14524         * @return True if the listener has consumed the event, false otherwise.
14525         */
14526        boolean onHover(View v, MotionEvent event);
14527    }
14528
14529    /**
14530     * Interface definition for a callback to be invoked when a generic motion event is
14531     * dispatched to this view. The callback will be invoked before the generic motion
14532     * event is given to the view.
14533     */
14534    public interface OnGenericMotionListener {
14535        /**
14536         * Called when a generic motion event is dispatched to a view. This allows listeners to
14537         * get a chance to respond before the target view.
14538         *
14539         * @param v The view the generic motion event has been dispatched to.
14540         * @param event The MotionEvent object containing full information about
14541         *        the event.
14542         * @return True if the listener has consumed the event, false otherwise.
14543         */
14544        boolean onGenericMotion(View v, MotionEvent event);
14545    }
14546
14547    /**
14548     * Interface definition for a callback to be invoked when a view has been clicked and held.
14549     */
14550    public interface OnLongClickListener {
14551        /**
14552         * Called when a view has been clicked and held.
14553         *
14554         * @param v The view that was clicked and held.
14555         *
14556         * @return true if the callback consumed the long click, false otherwise.
14557         */
14558        boolean onLongClick(View v);
14559    }
14560
14561    /**
14562     * Interface definition for a callback to be invoked when a drag is being dispatched
14563     * to this view.  The callback will be invoked before the hosting view's own
14564     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14565     * onDrag(event) behavior, it should return 'false' from this callback.
14566     *
14567     * <div class="special reference">
14568     * <h3>Developer Guides</h3>
14569     * <p>For a guide to implementing drag and drop features, read the
14570     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14571     * </div>
14572     */
14573    public interface OnDragListener {
14574        /**
14575         * Called when a drag event is dispatched to a view. This allows listeners
14576         * to get a chance to override base View behavior.
14577         *
14578         * @param v The View that received the drag event.
14579         * @param event The {@link android.view.DragEvent} object for the drag event.
14580         * @return {@code true} if the drag event was handled successfully, or {@code false}
14581         * if the drag event was not handled. Note that {@code false} will trigger the View
14582         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14583         */
14584        boolean onDrag(View v, DragEvent event);
14585    }
14586
14587    /**
14588     * Interface definition for a callback to be invoked when the focus state of
14589     * a view changed.
14590     */
14591    public interface OnFocusChangeListener {
14592        /**
14593         * Called when the focus state of a view has changed.
14594         *
14595         * @param v The view whose state has changed.
14596         * @param hasFocus The new focus state of v.
14597         */
14598        void onFocusChange(View v, boolean hasFocus);
14599    }
14600
14601    /**
14602     * Interface definition for a callback to be invoked when a view is clicked.
14603     */
14604    public interface OnClickListener {
14605        /**
14606         * Called when a view has been clicked.
14607         *
14608         * @param v The view that was clicked.
14609         */
14610        void onClick(View v);
14611    }
14612
14613    /**
14614     * Interface definition for a callback to be invoked when the context menu
14615     * for this view is being built.
14616     */
14617    public interface OnCreateContextMenuListener {
14618        /**
14619         * Called when the context menu for this view is being built. It is not
14620         * safe to hold onto the menu after this method returns.
14621         *
14622         * @param menu The context menu that is being built
14623         * @param v The view for which the context menu is being built
14624         * @param menuInfo Extra information about the item for which the
14625         *            context menu should be shown. This information will vary
14626         *            depending on the class of v.
14627         */
14628        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
14629    }
14630
14631    /**
14632     * Interface definition for a callback to be invoked when the status bar changes
14633     * visibility.  This reports <strong>global</strong> changes to the system UI
14634     * state, not just what the application is requesting.
14635     *
14636     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
14637     */
14638    public interface OnSystemUiVisibilityChangeListener {
14639        /**
14640         * Called when the status bar changes visibility because of a call to
14641         * {@link View#setSystemUiVisibility(int)}.
14642         *
14643         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
14644         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
14645         * <strong>global</strong> state of the UI visibility flags, not what your
14646         * app is currently applying.
14647         */
14648        public void onSystemUiVisibilityChange(int visibility);
14649    }
14650
14651    /**
14652     * Interface definition for a callback to be invoked when this view is attached
14653     * or detached from its window.
14654     */
14655    public interface OnAttachStateChangeListener {
14656        /**
14657         * Called when the view is attached to a window.
14658         * @param v The view that was attached
14659         */
14660        public void onViewAttachedToWindow(View v);
14661        /**
14662         * Called when the view is detached from a window.
14663         * @param v The view that was detached
14664         */
14665        public void onViewDetachedFromWindow(View v);
14666    }
14667
14668    private final class UnsetPressedState implements Runnable {
14669        public void run() {
14670            setPressed(false);
14671        }
14672    }
14673
14674    /**
14675     * Base class for derived classes that want to save and restore their own
14676     * state in {@link android.view.View#onSaveInstanceState()}.
14677     */
14678    public static class BaseSavedState extends AbsSavedState {
14679        /**
14680         * Constructor used when reading from a parcel. Reads the state of the superclass.
14681         *
14682         * @param source
14683         */
14684        public BaseSavedState(Parcel source) {
14685            super(source);
14686        }
14687
14688        /**
14689         * Constructor called by derived classes when creating their SavedState objects
14690         *
14691         * @param superState The state of the superclass of this view
14692         */
14693        public BaseSavedState(Parcelable superState) {
14694            super(superState);
14695        }
14696
14697        public static final Parcelable.Creator<BaseSavedState> CREATOR =
14698                new Parcelable.Creator<BaseSavedState>() {
14699            public BaseSavedState createFromParcel(Parcel in) {
14700                return new BaseSavedState(in);
14701            }
14702
14703            public BaseSavedState[] newArray(int size) {
14704                return new BaseSavedState[size];
14705            }
14706        };
14707    }
14708
14709    /**
14710     * A set of information given to a view when it is attached to its parent
14711     * window.
14712     */
14713    static class AttachInfo {
14714        interface Callbacks {
14715            void playSoundEffect(int effectId);
14716            boolean performHapticFeedback(int effectId, boolean always);
14717        }
14718
14719        /**
14720         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
14721         * to a Handler. This class contains the target (View) to invalidate and
14722         * the coordinates of the dirty rectangle.
14723         *
14724         * For performance purposes, this class also implements a pool of up to
14725         * POOL_LIMIT objects that get reused. This reduces memory allocations
14726         * whenever possible.
14727         */
14728        static class InvalidateInfo implements Poolable<InvalidateInfo> {
14729            private static final int POOL_LIMIT = 10;
14730            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
14731                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
14732                        public InvalidateInfo newInstance() {
14733                            return new InvalidateInfo();
14734                        }
14735
14736                        public void onAcquired(InvalidateInfo element) {
14737                        }
14738
14739                        public void onReleased(InvalidateInfo element) {
14740                            element.target = null;
14741                        }
14742                    }, POOL_LIMIT)
14743            );
14744
14745            private InvalidateInfo mNext;
14746            private boolean mIsPooled;
14747
14748            View target;
14749
14750            int left;
14751            int top;
14752            int right;
14753            int bottom;
14754
14755            public void setNextPoolable(InvalidateInfo element) {
14756                mNext = element;
14757            }
14758
14759            public InvalidateInfo getNextPoolable() {
14760                return mNext;
14761            }
14762
14763            static InvalidateInfo acquire() {
14764                return sPool.acquire();
14765            }
14766
14767            void release() {
14768                sPool.release(this);
14769            }
14770
14771            public boolean isPooled() {
14772                return mIsPooled;
14773            }
14774
14775            public void setPooled(boolean isPooled) {
14776                mIsPooled = isPooled;
14777            }
14778        }
14779
14780        final IWindowSession mSession;
14781
14782        final IWindow mWindow;
14783
14784        final IBinder mWindowToken;
14785
14786        final Callbacks mRootCallbacks;
14787
14788        HardwareCanvas mHardwareCanvas;
14789
14790        /**
14791         * The top view of the hierarchy.
14792         */
14793        View mRootView;
14794
14795        IBinder mPanelParentWindowToken;
14796        Surface mSurface;
14797
14798        boolean mHardwareAccelerated;
14799        boolean mHardwareAccelerationRequested;
14800        HardwareRenderer mHardwareRenderer;
14801
14802        /**
14803         * Scale factor used by the compatibility mode
14804         */
14805        float mApplicationScale;
14806
14807        /**
14808         * Indicates whether the application is in compatibility mode
14809         */
14810        boolean mScalingRequired;
14811
14812        /**
14813         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
14814         */
14815        boolean mTurnOffWindowResizeAnim;
14816
14817        /**
14818         * Left position of this view's window
14819         */
14820        int mWindowLeft;
14821
14822        /**
14823         * Top position of this view's window
14824         */
14825        int mWindowTop;
14826
14827        /**
14828         * Indicates whether views need to use 32-bit drawing caches
14829         */
14830        boolean mUse32BitDrawingCache;
14831
14832        /**
14833         * For windows that are full-screen but using insets to layout inside
14834         * of the screen decorations, these are the current insets for the
14835         * content of the window.
14836         */
14837        final Rect mContentInsets = new Rect();
14838
14839        /**
14840         * For windows that are full-screen but using insets to layout inside
14841         * of the screen decorations, these are the current insets for the
14842         * actual visible parts of the window.
14843         */
14844        final Rect mVisibleInsets = new Rect();
14845
14846        /**
14847         * The internal insets given by this window.  This value is
14848         * supplied by the client (through
14849         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
14850         * be given to the window manager when changed to be used in laying
14851         * out windows behind it.
14852         */
14853        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
14854                = new ViewTreeObserver.InternalInsetsInfo();
14855
14856        /**
14857         * All views in the window's hierarchy that serve as scroll containers,
14858         * used to determine if the window can be resized or must be panned
14859         * to adjust for a soft input area.
14860         */
14861        final ArrayList<View> mScrollContainers = new ArrayList<View>();
14862
14863        final KeyEvent.DispatcherState mKeyDispatchState
14864                = new KeyEvent.DispatcherState();
14865
14866        /**
14867         * Indicates whether the view's window currently has the focus.
14868         */
14869        boolean mHasWindowFocus;
14870
14871        /**
14872         * The current visibility of the window.
14873         */
14874        int mWindowVisibility;
14875
14876        /**
14877         * Indicates the time at which drawing started to occur.
14878         */
14879        long mDrawingTime;
14880
14881        /**
14882         * Indicates whether or not ignoring the DIRTY_MASK flags.
14883         */
14884        boolean mIgnoreDirtyState;
14885
14886        /**
14887         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
14888         * to avoid clearing that flag prematurely.
14889         */
14890        boolean mSetIgnoreDirtyState = false;
14891
14892        /**
14893         * Indicates whether the view's window is currently in touch mode.
14894         */
14895        boolean mInTouchMode;
14896
14897        /**
14898         * Indicates that ViewAncestor should trigger a global layout change
14899         * the next time it performs a traversal
14900         */
14901        boolean mRecomputeGlobalAttributes;
14902
14903        /**
14904         * Always report new attributes at next traversal.
14905         */
14906        boolean mForceReportNewAttributes;
14907
14908        /**
14909         * Set during a traveral if any views want to keep the screen on.
14910         */
14911        boolean mKeepScreenOn;
14912
14913        /**
14914         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
14915         */
14916        int mSystemUiVisibility;
14917
14918        /**
14919         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
14920         * attached.
14921         */
14922        boolean mHasSystemUiListeners;
14923
14924        /**
14925         * Set if the visibility of any views has changed.
14926         */
14927        boolean mViewVisibilityChanged;
14928
14929        /**
14930         * Set to true if a view has been scrolled.
14931         */
14932        boolean mViewScrollChanged;
14933
14934        /**
14935         * Global to the view hierarchy used as a temporary for dealing with
14936         * x/y points in the transparent region computations.
14937         */
14938        final int[] mTransparentLocation = new int[2];
14939
14940        /**
14941         * Global to the view hierarchy used as a temporary for dealing with
14942         * x/y points in the ViewGroup.invalidateChild implementation.
14943         */
14944        final int[] mInvalidateChildLocation = new int[2];
14945
14946
14947        /**
14948         * Global to the view hierarchy used as a temporary for dealing with
14949         * x/y location when view is transformed.
14950         */
14951        final float[] mTmpTransformLocation = new float[2];
14952
14953        /**
14954         * The view tree observer used to dispatch global events like
14955         * layout, pre-draw, touch mode change, etc.
14956         */
14957        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
14958
14959        /**
14960         * A Canvas used by the view hierarchy to perform bitmap caching.
14961         */
14962        Canvas mCanvas;
14963
14964        /**
14965         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
14966         * handler can be used to pump events in the UI events queue.
14967         */
14968        final Handler mHandler;
14969
14970        /**
14971         * Identifier for messages requesting the view to be invalidated.
14972         * Such messages should be sent to {@link #mHandler}.
14973         */
14974        static final int INVALIDATE_MSG = 0x1;
14975
14976        /**
14977         * Identifier for messages requesting the view to invalidate a region.
14978         * Such messages should be sent to {@link #mHandler}.
14979         */
14980        static final int INVALIDATE_RECT_MSG = 0x2;
14981
14982        /**
14983         * Temporary for use in computing invalidate rectangles while
14984         * calling up the hierarchy.
14985         */
14986        final Rect mTmpInvalRect = new Rect();
14987
14988        /**
14989         * Temporary for use in computing hit areas with transformed views
14990         */
14991        final RectF mTmpTransformRect = new RectF();
14992
14993        /**
14994         * Temporary list for use in collecting focusable descendents of a view.
14995         */
14996        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
14997
14998        /**
14999         * The id of the window for accessibility purposes.
15000         */
15001        int mAccessibilityWindowId = View.NO_ID;
15002
15003        /**
15004         * Creates a new set of attachment information with the specified
15005         * events handler and thread.
15006         *
15007         * @param handler the events handler the view must use
15008         */
15009        AttachInfo(IWindowSession session, IWindow window,
15010                Handler handler, Callbacks effectPlayer) {
15011            mSession = session;
15012            mWindow = window;
15013            mWindowToken = window.asBinder();
15014            mHandler = handler;
15015            mRootCallbacks = effectPlayer;
15016        }
15017    }
15018
15019    /**
15020     * <p>ScrollabilityCache holds various fields used by a View when scrolling
15021     * is supported. This avoids keeping too many unused fields in most
15022     * instances of View.</p>
15023     */
15024    private static class ScrollabilityCache implements Runnable {
15025
15026        /**
15027         * Scrollbars are not visible
15028         */
15029        public static final int OFF = 0;
15030
15031        /**
15032         * Scrollbars are visible
15033         */
15034        public static final int ON = 1;
15035
15036        /**
15037         * Scrollbars are fading away
15038         */
15039        public static final int FADING = 2;
15040
15041        public boolean fadeScrollBars;
15042
15043        public int fadingEdgeLength;
15044        public int scrollBarDefaultDelayBeforeFade;
15045        public int scrollBarFadeDuration;
15046
15047        public int scrollBarSize;
15048        public ScrollBarDrawable scrollBar;
15049        public float[] interpolatorValues;
15050        public View host;
15051
15052        public final Paint paint;
15053        public final Matrix matrix;
15054        public Shader shader;
15055
15056        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
15057
15058        private static final float[] OPAQUE = { 255 };
15059        private static final float[] TRANSPARENT = { 0.0f };
15060
15061        /**
15062         * When fading should start. This time moves into the future every time
15063         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
15064         */
15065        public long fadeStartTime;
15066
15067
15068        /**
15069         * The current state of the scrollbars: ON, OFF, or FADING
15070         */
15071        public int state = OFF;
15072
15073        private int mLastColor;
15074
15075        public ScrollabilityCache(ViewConfiguration configuration, View host) {
15076            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
15077            scrollBarSize = configuration.getScaledScrollBarSize();
15078            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
15079            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
15080
15081            paint = new Paint();
15082            matrix = new Matrix();
15083            // use use a height of 1, and then wack the matrix each time we
15084            // actually use it.
15085            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
15086
15087            paint.setShader(shader);
15088            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
15089            this.host = host;
15090        }
15091
15092        public void setFadeColor(int color) {
15093            if (color != 0 && color != mLastColor) {
15094                mLastColor = color;
15095                color |= 0xFF000000;
15096
15097                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
15098                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
15099
15100                paint.setShader(shader);
15101                // Restore the default transfer mode (src_over)
15102                paint.setXfermode(null);
15103            }
15104        }
15105
15106        public void run() {
15107            long now = AnimationUtils.currentAnimationTimeMillis();
15108            if (now >= fadeStartTime) {
15109
15110                // the animation fades the scrollbars out by changing
15111                // the opacity (alpha) from fully opaque to fully
15112                // transparent
15113                int nextFrame = (int) now;
15114                int framesCount = 0;
15115
15116                Interpolator interpolator = scrollBarInterpolator;
15117
15118                // Start opaque
15119                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
15120
15121                // End transparent
15122                nextFrame += scrollBarFadeDuration;
15123                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
15124
15125                state = FADING;
15126
15127                // Kick off the fade animation
15128                host.invalidate(true);
15129            }
15130        }
15131    }
15132
15133    /**
15134     * Resuable callback for sending
15135     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
15136     */
15137    private class SendViewScrolledAccessibilityEvent implements Runnable {
15138        public volatile boolean mIsPending;
15139
15140        public void run() {
15141            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
15142            mIsPending = false;
15143        }
15144    }
15145
15146    /**
15147     * <p>
15148     * This class represents a delegate that can be registered in a {@link View}
15149     * to enhance accessibility support via composition rather via inheritance.
15150     * It is specifically targeted to widget developers that extend basic View
15151     * classes i.e. classes in package android.view, that would like their
15152     * applications to be backwards compatible.
15153     * </p>
15154     * <p>
15155     * A scenario in which a developer would like to use an accessibility delegate
15156     * is overriding a method introduced in a later API version then the minimal API
15157     * version supported by the application. For example, the method
15158     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
15159     * in API version 4 when the accessibility APIs were first introduced. If a
15160     * developer would like his application to run on API version 4 devices (assuming
15161     * all other APIs used by the application are version 4 or lower) and take advantage
15162     * of this method, instead of overriding the method which would break the application's
15163     * backwards compatibility, he can override the corresponding method in this
15164     * delegate and register the delegate in the target View if the API version of
15165     * the system is high enough i.e. the API version is same or higher to the API
15166     * version that introduced
15167     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
15168     * </p>
15169     * <p>
15170     * Here is an example implementation:
15171     * </p>
15172     * <code><pre><p>
15173     * if (Build.VERSION.SDK_INT >= 14) {
15174     *     // If the API version is equal of higher than the version in
15175     *     // which onInitializeAccessibilityNodeInfo was introduced we
15176     *     // register a delegate with a customized implementation.
15177     *     View view = findViewById(R.id.view_id);
15178     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
15179     *         public void onInitializeAccessibilityNodeInfo(View host,
15180     *                 AccessibilityNodeInfo info) {
15181     *             // Let the default implementation populate the info.
15182     *             super.onInitializeAccessibilityNodeInfo(host, info);
15183     *             // Set some other information.
15184     *             info.setEnabled(host.isEnabled());
15185     *         }
15186     *     });
15187     * }
15188     * </code></pre></p>
15189     * <p>
15190     * This delegate contains methods that correspond to the accessibility methods
15191     * in View. If a delegate has been specified the implementation in View hands
15192     * off handling to the corresponding method in this delegate. The default
15193     * implementation the delegate methods behaves exactly as the corresponding
15194     * method in View for the case of no accessibility delegate been set. Hence,
15195     * to customize the behavior of a View method, clients can override only the
15196     * corresponding delegate method without altering the behavior of the rest
15197     * accessibility related methods of the host view.
15198     * </p>
15199     */
15200    public static class AccessibilityDelegate {
15201
15202        /**
15203         * Sends an accessibility event of the given type. If accessibility is not
15204         * enabled this method has no effect.
15205         * <p>
15206         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
15207         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
15208         * been set.
15209         * </p>
15210         *
15211         * @param host The View hosting the delegate.
15212         * @param eventType The type of the event to send.
15213         *
15214         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
15215         */
15216        public void sendAccessibilityEvent(View host, int eventType) {
15217            host.sendAccessibilityEventInternal(eventType);
15218        }
15219
15220        /**
15221         * Sends an accessibility event. This method behaves exactly as
15222         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
15223         * empty {@link AccessibilityEvent} and does not perform a check whether
15224         * accessibility is enabled.
15225         * <p>
15226         * The default implementation behaves as
15227         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15228         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
15229         * the case of no accessibility delegate been set.
15230         * </p>
15231         *
15232         * @param host The View hosting the delegate.
15233         * @param event The event to send.
15234         *
15235         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15236         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15237         */
15238        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
15239            host.sendAccessibilityEventUncheckedInternal(event);
15240        }
15241
15242        /**
15243         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
15244         * to its children for adding their text content to the event.
15245         * <p>
15246         * The default implementation behaves as
15247         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15248         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
15249         * the case of no accessibility delegate been set.
15250         * </p>
15251         *
15252         * @param host The View hosting the delegate.
15253         * @param event The event.
15254         * @return True if the event population was completed.
15255         *
15256         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15257         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15258         */
15259        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15260            return host.dispatchPopulateAccessibilityEventInternal(event);
15261        }
15262
15263        /**
15264         * Gives a chance to the host View to populate the accessibility event with its
15265         * text content.
15266         * <p>
15267         * The default implementation behaves as
15268         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
15269         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
15270         * the case of no accessibility delegate been set.
15271         * </p>
15272         *
15273         * @param host The View hosting the delegate.
15274         * @param event The accessibility event which to populate.
15275         *
15276         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
15277         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
15278         */
15279        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15280            host.onPopulateAccessibilityEventInternal(event);
15281        }
15282
15283        /**
15284         * Initializes an {@link AccessibilityEvent} with information about the
15285         * the host View which is the event source.
15286         * <p>
15287         * The default implementation behaves as
15288         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
15289         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
15290         * the case of no accessibility delegate been set.
15291         * </p>
15292         *
15293         * @param host The View hosting the delegate.
15294         * @param event The event to initialize.
15295         *
15296         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
15297         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
15298         */
15299        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
15300            host.onInitializeAccessibilityEventInternal(event);
15301        }
15302
15303        /**
15304         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
15305         * <p>
15306         * The default implementation behaves as
15307         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15308         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
15309         * the case of no accessibility delegate been set.
15310         * </p>
15311         *
15312         * @param host The View hosting the delegate.
15313         * @param info The instance to initialize.
15314         *
15315         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15316         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15317         */
15318        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
15319            host.onInitializeAccessibilityNodeInfoInternal(info);
15320        }
15321
15322        /**
15323         * Called when a child of the host View has requested sending an
15324         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
15325         * to augment the event.
15326         * <p>
15327         * The default implementation behaves as
15328         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15329         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
15330         * the case of no accessibility delegate been set.
15331         * </p>
15332         *
15333         * @param host The View hosting the delegate.
15334         * @param child The child which requests sending the event.
15335         * @param event The event to be sent.
15336         * @return True if the event should be sent
15337         *
15338         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15339         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15340         */
15341        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
15342                AccessibilityEvent event) {
15343            return host.onRequestSendAccessibilityEventInternal(child, event);
15344        }
15345
15346        /**
15347         * Gets the provider for managing a virtual view hierarchy rooted at this View
15348         * and reported to {@link android.accessibilityservice.AccessibilityService}s
15349         * that explore the window content.
15350         * <p>
15351         * The default implementation behaves as
15352         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
15353         * the case of no accessibility delegate been set.
15354         * </p>
15355         *
15356         * @return The provider.
15357         *
15358         * @see AccessibilityNodeProvider
15359         */
15360        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
15361            return null;
15362        }
15363    }
15364}
15365