View.java revision c6e8811cb48014d541bc6f85b4b7f92643af8591
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.Parcel;
44import android.os.Parcelable;
45import android.os.RemoteException;
46import android.os.SystemClock;
47import android.text.TextUtils;
48import android.util.AttributeSet;
49import android.util.FloatProperty;
50import android.util.LocaleUtil;
51import android.util.Log;
52import android.util.Pool;
53import android.util.Poolable;
54import android.util.PoolableManager;
55import android.util.Pools;
56import android.util.Property;
57import android.util.SparseArray;
58import android.util.TypedValue;
59import android.view.ContextMenu.ContextMenuInfo;
60import android.view.accessibility.AccessibilityEvent;
61import android.view.accessibility.AccessibilityEventSource;
62import android.view.accessibility.AccessibilityManager;
63import android.view.accessibility.AccessibilityNodeInfo;
64import android.view.accessibility.AccessibilityNodeProvider;
65import android.view.animation.Animation;
66import android.view.animation.AnimationUtils;
67import android.view.animation.Transformation;
68import android.view.inputmethod.EditorInfo;
69import android.view.inputmethod.InputConnection;
70import android.view.inputmethod.InputMethodManager;
71import android.widget.ScrollBarDrawable;
72
73import static android.os.Build.VERSION_CODES.*;
74
75import com.android.internal.R;
76import com.android.internal.util.Predicate;
77import com.android.internal.view.menu.MenuBuilder;
78
79import java.lang.ref.WeakReference;
80import java.lang.reflect.InvocationTargetException;
81import java.lang.reflect.Method;
82import java.util.ArrayList;
83import java.util.Arrays;
84import java.util.Locale;
85import java.util.concurrent.CopyOnWriteArrayList;
86
87/**
88 * <p>
89 * This class represents the basic building block for user interface components. A View
90 * occupies a rectangular area on the screen and is responsible for drawing and
91 * event handling. View is the base class for <em>widgets</em>, which are
92 * used to create interactive UI components (buttons, text fields, etc.). The
93 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
94 * are invisible containers that hold other Views (or other ViewGroups) and define
95 * their layout properties.
96 * </p>
97 *
98 * <div class="special reference">
99 * <h3>Developer Guides</h3>
100 * <p>For information about using this class to develop your application's user interface,
101 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide.
102 * </div>
103 *
104 * <a name="Using"></a>
105 * <h3>Using Views</h3>
106 * <p>
107 * All of the views in a window are arranged in a single tree. You can add views
108 * either from code or by specifying a tree of views in one or more XML layout
109 * files. There are many specialized subclasses of views that act as controls or
110 * are capable of displaying text, images, or other content.
111 * </p>
112 * <p>
113 * Once you have created a tree of views, there are typically a few types of
114 * common operations you may wish to perform:
115 * <ul>
116 * <li><strong>Set properties:</strong> for example setting the text of a
117 * {@link android.widget.TextView}. The available properties and the methods
118 * that set them will vary among the different subclasses of views. Note that
119 * properties that are known at build time can be set in the XML layout
120 * files.</li>
121 * <li><strong>Set focus:</strong> The framework will handled moving focus in
122 * response to user input. To force focus to a specific view, call
123 * {@link #requestFocus}.</li>
124 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners
125 * that will be notified when something interesting happens to the view. For
126 * example, all views will let you set a listener to be notified when the view
127 * gains or loses focus. You can register such a listener using
128 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}.
129 * Other view subclasses offer more specialized listeners. For example, a Button
130 * exposes a listener to notify clients when the button is clicked.</li>
131 * <li><strong>Set visibility:</strong> You can hide or show views using
132 * {@link #setVisibility(int)}.</li>
133 * </ul>
134 * </p>
135 * <p><em>
136 * Note: The Android framework is responsible for measuring, laying out and
137 * drawing views. You should not call methods that perform these actions on
138 * views yourself unless you are actually implementing a
139 * {@link android.view.ViewGroup}.
140 * </em></p>
141 *
142 * <a name="Lifecycle"></a>
143 * <h3>Implementing a Custom View</h3>
144 *
145 * <p>
146 * To implement a custom view, you will usually begin by providing overrides for
147 * some of the standard methods that the framework calls on all views. You do
148 * not need to override all of these methods. In fact, you can start by just
149 * overriding {@link #onDraw(android.graphics.Canvas)}.
150 * <table border="2" width="85%" align="center" cellpadding="5">
151 *     <thead>
152 *         <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
153 *     </thead>
154 *
155 *     <tbody>
156 *     <tr>
157 *         <td rowspan="2">Creation</td>
158 *         <td>Constructors</td>
159 *         <td>There is a form of the constructor that are called when the view
160 *         is created from code and a form that is called when the view is
161 *         inflated from a layout file. The second form should parse and apply
162 *         any attributes defined in the layout file.
163 *         </td>
164 *     </tr>
165 *     <tr>
166 *         <td><code>{@link #onFinishInflate()}</code></td>
167 *         <td>Called after a view and all of its children has been inflated
168 *         from XML.</td>
169 *     </tr>
170 *
171 *     <tr>
172 *         <td rowspan="3">Layout</td>
173 *         <td><code>{@link #onMeasure(int, int)}</code></td>
174 *         <td>Called to determine the size requirements for this view and all
175 *         of its children.
176 *         </td>
177 *     </tr>
178 *     <tr>
179 *         <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td>
180 *         <td>Called when this view should assign a size and position to all
181 *         of its children.
182 *         </td>
183 *     </tr>
184 *     <tr>
185 *         <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td>
186 *         <td>Called when the size of this view has changed.
187 *         </td>
188 *     </tr>
189 *
190 *     <tr>
191 *         <td>Drawing</td>
192 *         <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td>
193 *         <td>Called when the view should render its content.
194 *         </td>
195 *     </tr>
196 *
197 *     <tr>
198 *         <td rowspan="4">Event processing</td>
199 *         <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td>
200 *         <td>Called when a new key event occurs.
201 *         </td>
202 *     </tr>
203 *     <tr>
204 *         <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td>
205 *         <td>Called when a key up event occurs.
206 *         </td>
207 *     </tr>
208 *     <tr>
209 *         <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td>
210 *         <td>Called when a trackball motion event occurs.
211 *         </td>
212 *     </tr>
213 *     <tr>
214 *         <td><code>{@link #onTouchEvent(MotionEvent)}</code></td>
215 *         <td>Called when a touch screen motion event occurs.
216 *         </td>
217 *     </tr>
218 *
219 *     <tr>
220 *         <td rowspan="2">Focus</td>
221 *         <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td>
222 *         <td>Called when the view gains or loses focus.
223 *         </td>
224 *     </tr>
225 *
226 *     <tr>
227 *         <td><code>{@link #onWindowFocusChanged(boolean)}</code></td>
228 *         <td>Called when the window containing the view gains or loses focus.
229 *         </td>
230 *     </tr>
231 *
232 *     <tr>
233 *         <td rowspan="3">Attaching</td>
234 *         <td><code>{@link #onAttachedToWindow()}</code></td>
235 *         <td>Called when the view is attached to a window.
236 *         </td>
237 *     </tr>
238 *
239 *     <tr>
240 *         <td><code>{@link #onDetachedFromWindow}</code></td>
241 *         <td>Called when the view is detached from its window.
242 *         </td>
243 *     </tr>
244 *
245 *     <tr>
246 *         <td><code>{@link #onWindowVisibilityChanged(int)}</code></td>
247 *         <td>Called when the visibility of the window containing the view
248 *         has changed.
249 *         </td>
250 *     </tr>
251 *     </tbody>
252 *
253 * </table>
254 * </p>
255 *
256 * <a name="IDs"></a>
257 * <h3>IDs</h3>
258 * Views may have an integer id associated with them. These ids are typically
259 * assigned in the layout XML files, and are used to find specific views within
260 * the view tree. A common pattern is to:
261 * <ul>
262 * <li>Define a Button in the layout file and assign it a unique ID.
263 * <pre>
264 * &lt;Button
265 *     android:id="@+id/my_button"
266 *     android:layout_width="wrap_content"
267 *     android:layout_height="wrap_content"
268 *     android:text="@string/my_button_text"/&gt;
269 * </pre></li>
270 * <li>From the onCreate method of an Activity, find the Button
271 * <pre class="prettyprint">
272 *      Button myButton = (Button) findViewById(R.id.my_button);
273 * </pre></li>
274 * </ul>
275 * <p>
276 * View IDs need not be unique throughout the tree, but it is good practice to
277 * ensure that they are at least unique within the part of the tree you are
278 * searching.
279 * </p>
280 *
281 * <a name="Position"></a>
282 * <h3>Position</h3>
283 * <p>
284 * The geometry of a view is that of a rectangle. A view has a location,
285 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
286 * two dimensions, expressed as a width and a height. The unit for location
287 * and dimensions is the pixel.
288 * </p>
289 *
290 * <p>
291 * It is possible to retrieve the location of a view by invoking the methods
292 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
293 * coordinate of the rectangle representing the view. The latter returns the
294 * top, or Y, coordinate of the rectangle representing the view. These methods
295 * both return the location of the view relative to its parent. For instance,
296 * when getLeft() returns 20, that means the view is located 20 pixels to the
297 * right of the left edge of its direct parent.
298 * </p>
299 *
300 * <p>
301 * In addition, several convenience methods are offered to avoid unnecessary
302 * computations, namely {@link #getRight()} and {@link #getBottom()}.
303 * These methods return the coordinates of the right and bottom edges of the
304 * rectangle representing the view. For instance, calling {@link #getRight()}
305 * is similar to the following computation: <code>getLeft() + getWidth()</code>
306 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
307 * </p>
308 *
309 * <a name="SizePaddingMargins"></a>
310 * <h3>Size, padding and margins</h3>
311 * <p>
312 * The size of a view is expressed with a width and a height. A view actually
313 * possess two pairs of width and height values.
314 * </p>
315 *
316 * <p>
317 * The first pair is known as <em>measured width</em> and
318 * <em>measured height</em>. These dimensions define how big a view wants to be
319 * within its parent (see <a href="#Layout">Layout</a> for more details.) The
320 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
321 * and {@link #getMeasuredHeight()}.
322 * </p>
323 *
324 * <p>
325 * The second pair is simply known as <em>width</em> and <em>height</em>, or
326 * sometimes <em>drawing width</em> and <em>drawing height</em>. These
327 * dimensions define the actual size of the view on screen, at drawing time and
328 * after layout. These values may, but do not have to, be different from the
329 * measured width and height. The width and height can be obtained by calling
330 * {@link #getWidth()} and {@link #getHeight()}.
331 * </p>
332 *
333 * <p>
334 * To measure its dimensions, a view takes into account its padding. The padding
335 * is expressed in pixels for the left, top, right and bottom parts of the view.
336 * Padding can be used to offset the content of the view by a specific amount of
337 * pixels. For instance, a left padding of 2 will push the view's content by
338 * 2 pixels to the right of the left edge. Padding can be set using the
339 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)}
340 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()},
341 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()},
342 * {@link #getPaddingEnd()}.
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_paddingStart
605 * @attr ref android.R.styleable#View_paddingEnd
606 * @attr ref android.R.styleable#View_saveEnabled
607 * @attr ref android.R.styleable#View_rotation
608 * @attr ref android.R.styleable#View_rotationX
609 * @attr ref android.R.styleable#View_rotationY
610 * @attr ref android.R.styleable#View_scaleX
611 * @attr ref android.R.styleable#View_scaleY
612 * @attr ref android.R.styleable#View_scrollX
613 * @attr ref android.R.styleable#View_scrollY
614 * @attr ref android.R.styleable#View_scrollbarSize
615 * @attr ref android.R.styleable#View_scrollbarStyle
616 * @attr ref android.R.styleable#View_scrollbars
617 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade
618 * @attr ref android.R.styleable#View_scrollbarFadeDuration
619 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal
620 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal
621 * @attr ref android.R.styleable#View_scrollbarThumbVertical
622 * @attr ref android.R.styleable#View_scrollbarTrackVertical
623 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
624 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
625 * @attr ref android.R.styleable#View_soundEffectsEnabled
626 * @attr ref android.R.styleable#View_tag
627 * @attr ref android.R.styleable#View_transformPivotX
628 * @attr ref android.R.styleable#View_transformPivotY
629 * @attr ref android.R.styleable#View_translationX
630 * @attr ref android.R.styleable#View_translationY
631 * @attr ref android.R.styleable#View_visibility
632 *
633 * @see android.view.ViewGroup
634 */
635public class View implements Drawable.Callback, Drawable.Callback2, KeyEvent.Callback,
636        AccessibilityEventSource {
637    private static final boolean DBG = false;
638
639    /**
640     * The logging tag used by this class with android.util.Log.
641     */
642    protected static final String VIEW_LOG_TAG = "View";
643
644    /**
645     * Used to mark a View that has no ID.
646     */
647    public static final int NO_ID = -1;
648
649    /**
650     * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
651     * calling setFlags.
652     */
653    private static final int NOT_FOCUSABLE = 0x00000000;
654
655    /**
656     * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
657     * setFlags.
658     */
659    private static final int FOCUSABLE = 0x00000001;
660
661    /**
662     * Mask for use with setFlags indicating bits used for focus.
663     */
664    private static final int FOCUSABLE_MASK = 0x00000001;
665
666    /**
667     * This view will adjust its padding to fit sytem windows (e.g. status bar)
668     */
669    private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
670
671    /**
672     * This view is visible.
673     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
674     * android:visibility}.
675     */
676    public static final int VISIBLE = 0x00000000;
677
678    /**
679     * This view is invisible, but it still takes up space for layout purposes.
680     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
681     * android:visibility}.
682     */
683    public static final int INVISIBLE = 0x00000004;
684
685    /**
686     * This view is invisible, and it doesn't take any space for layout
687     * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
688     * android:visibility}.
689     */
690    public static final int GONE = 0x00000008;
691
692    /**
693     * Mask for use with setFlags indicating bits used for visibility.
694     * {@hide}
695     */
696    static final int VISIBILITY_MASK = 0x0000000C;
697
698    private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
699
700    /**
701     * This view is enabled. Intrepretation varies by subclass.
702     * Use with ENABLED_MASK when calling setFlags.
703     * {@hide}
704     */
705    static final int ENABLED = 0x00000000;
706
707    /**
708     * This view is disabled. Intrepretation varies by subclass.
709     * Use with ENABLED_MASK when calling setFlags.
710     * {@hide}
711     */
712    static final int DISABLED = 0x00000020;
713
714   /**
715    * Mask for use with setFlags indicating bits used for indicating whether
716    * this view is enabled
717    * {@hide}
718    */
719    static final int ENABLED_MASK = 0x00000020;
720
721    /**
722     * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be
723     * called and further optimizations will be performed. It is okay to have
724     * this flag set and a background. Use with DRAW_MASK when calling setFlags.
725     * {@hide}
726     */
727    static final int WILL_NOT_DRAW = 0x00000080;
728
729    /**
730     * Mask for use with setFlags indicating bits used for indicating whether
731     * this view is will draw
732     * {@hide}
733     */
734    static final int DRAW_MASK = 0x00000080;
735
736    /**
737     * <p>This view doesn't show scrollbars.</p>
738     * {@hide}
739     */
740    static final int SCROLLBARS_NONE = 0x00000000;
741
742    /**
743     * <p>This view shows horizontal scrollbars.</p>
744     * {@hide}
745     */
746    static final int SCROLLBARS_HORIZONTAL = 0x00000100;
747
748    /**
749     * <p>This view shows vertical scrollbars.</p>
750     * {@hide}
751     */
752    static final int SCROLLBARS_VERTICAL = 0x00000200;
753
754    /**
755     * <p>Mask for use with setFlags indicating bits used for indicating which
756     * scrollbars are enabled.</p>
757     * {@hide}
758     */
759    static final int SCROLLBARS_MASK = 0x00000300;
760
761    /**
762     * Indicates that the view should filter touches when its window is obscured.
763     * Refer to the class comments for more information about this security feature.
764     * {@hide}
765     */
766    static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400;
767
768    // note flag value 0x00000800 is now available for next flags...
769
770    /**
771     * <p>This view doesn't show fading edges.</p>
772     * {@hide}
773     */
774    static final int FADING_EDGE_NONE = 0x00000000;
775
776    /**
777     * <p>This view shows horizontal fading edges.</p>
778     * {@hide}
779     */
780    static final int FADING_EDGE_HORIZONTAL = 0x00001000;
781
782    /**
783     * <p>This view shows vertical fading edges.</p>
784     * {@hide}
785     */
786    static final int FADING_EDGE_VERTICAL = 0x00002000;
787
788    /**
789     * <p>Mask for use with setFlags indicating bits used for indicating which
790     * fading edges are enabled.</p>
791     * {@hide}
792     */
793    static final int FADING_EDGE_MASK = 0x00003000;
794
795    /**
796     * <p>Indicates this view can be clicked. When clickable, a View reacts
797     * to clicks by notifying the OnClickListener.<p>
798     * {@hide}
799     */
800    static final int CLICKABLE = 0x00004000;
801
802    /**
803     * <p>Indicates this view is caching its drawing into a bitmap.</p>
804     * {@hide}
805     */
806    static final int DRAWING_CACHE_ENABLED = 0x00008000;
807
808    /**
809     * <p>Indicates that no icicle should be saved for this view.<p>
810     * {@hide}
811     */
812    static final int SAVE_DISABLED = 0x000010000;
813
814    /**
815     * <p>Mask for use with setFlags indicating bits used for the saveEnabled
816     * property.</p>
817     * {@hide}
818     */
819    static final int SAVE_DISABLED_MASK = 0x000010000;
820
821    /**
822     * <p>Indicates that no drawing cache should ever be created for this view.<p>
823     * {@hide}
824     */
825    static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
826
827    /**
828     * <p>Indicates this view can take / keep focus when int touch mode.</p>
829     * {@hide}
830     */
831    static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
832
833    /**
834     * <p>Enables low quality mode for the drawing cache.</p>
835     */
836    public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
837
838    /**
839     * <p>Enables high quality mode for the drawing cache.</p>
840     */
841    public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
842
843    /**
844     * <p>Enables automatic quality mode for the drawing cache.</p>
845     */
846    public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
847
848    private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
849            DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
850    };
851
852    /**
853     * <p>Mask for use with setFlags indicating bits used for the cache
854     * quality property.</p>
855     * {@hide}
856     */
857    static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
858
859    /**
860     * <p>
861     * Indicates this view can be long clicked. When long clickable, a View
862     * reacts to long clicks by notifying the OnLongClickListener or showing a
863     * context menu.
864     * </p>
865     * {@hide}
866     */
867    static final int LONG_CLICKABLE = 0x00200000;
868
869    /**
870     * <p>Indicates that this view gets its drawable states from its direct parent
871     * and ignores its original internal states.</p>
872     *
873     * @hide
874     */
875    static final int DUPLICATE_PARENT_STATE = 0x00400000;
876
877    /**
878     * The scrollbar style to display the scrollbars inside the content area,
879     * without increasing the padding. The scrollbars will be overlaid with
880     * translucency on the view's content.
881     */
882    public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
883
884    /**
885     * The scrollbar style to display the scrollbars inside the padded area,
886     * increasing the padding of the view. The scrollbars will not overlap the
887     * content area of the view.
888     */
889    public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
890
891    /**
892     * The scrollbar style to display the scrollbars at the edge of the view,
893     * without increasing the padding. The scrollbars will be overlaid with
894     * translucency.
895     */
896    public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
897
898    /**
899     * The scrollbar style to display the scrollbars at the edge of the view,
900     * increasing the padding of the view. The scrollbars will only overlap the
901     * background, if any.
902     */
903    public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
904
905    /**
906     * Mask to check if the scrollbar style is overlay or inset.
907     * {@hide}
908     */
909    static final int SCROLLBARS_INSET_MASK = 0x01000000;
910
911    /**
912     * Mask to check if the scrollbar style is inside or outside.
913     * {@hide}
914     */
915    static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
916
917    /**
918     * Mask for scrollbar style.
919     * {@hide}
920     */
921    static final int SCROLLBARS_STYLE_MASK = 0x03000000;
922
923    /**
924     * View flag indicating that the screen should remain on while the
925     * window containing this view is visible to the user.  This effectively
926     * takes care of automatically setting the WindowManager's
927     * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
928     */
929    public static final int KEEP_SCREEN_ON = 0x04000000;
930
931    /**
932     * View flag indicating whether this view should have sound effects enabled
933     * for events such as clicking and touching.
934     */
935    public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
936
937    /**
938     * View flag indicating whether this view should have haptic feedback
939     * enabled for events such as long presses.
940     */
941    public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
942
943    /**
944     * <p>Indicates that the view hierarchy should stop saving state when
945     * it reaches this view.  If state saving is initiated immediately at
946     * the view, it will be allowed.
947     * {@hide}
948     */
949    static final int PARENT_SAVE_DISABLED = 0x20000000;
950
951    /**
952     * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p>
953     * {@hide}
954     */
955    static final int PARENT_SAVE_DISABLED_MASK = 0x20000000;
956
957    /**
958     * Horizontal direction of this view is from Left to Right.
959     * Use with {@link #setLayoutDirection}.
960     */
961    public static final int LAYOUT_DIRECTION_LTR = 0x00000000;
962
963    /**
964     * Horizontal direction of this view is from Right to Left.
965     * Use with {@link #setLayoutDirection}.
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     */
973    public static final int LAYOUT_DIRECTION_INHERIT = 0x80000000;
974
975    /**
976     * Horizontal direction of this view is from deduced from the default language
977     * script for the locale. Use with {@link #setLayoutDirection}.
978     */
979    public static final int LAYOUT_DIRECTION_LOCALE = 0xC0000000;
980
981    /**
982     * Mask for use with setFlags indicating bits used for horizontalDirection.
983     * {@hide}
984     */
985    static final int LAYOUT_DIRECTION_MASK = 0xC0000000;
986
987    /*
988     * Array of horizontal direction flags for mapping attribute "horizontalDirection" to correct
989     * flag value.
990     * {@hide}
991     */
992    private static final int[] LAYOUT_DIRECTION_FLAGS = {LAYOUT_DIRECTION_LTR,
993        LAYOUT_DIRECTION_RTL, LAYOUT_DIRECTION_INHERIT, LAYOUT_DIRECTION_LOCALE};
994
995    /**
996     * Default horizontalDirection.
997     * {@hide}
998     */
999    private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT;
1000
1001    /**
1002     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1003     * should add all focusable Views regardless if they are focusable in touch mode.
1004     */
1005    public static final int FOCUSABLES_ALL = 0x00000000;
1006
1007    /**
1008     * View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
1009     * should add only Views focusable in touch mode.
1010     */
1011    public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
1012
1013    /**
1014     * Use with {@link #focusSearch(int)}. Move focus to the previous selectable
1015     * item.
1016     */
1017    public static final int FOCUS_BACKWARD = 0x00000001;
1018
1019    /**
1020     * Use with {@link #focusSearch(int)}. Move focus to the next selectable
1021     * item.
1022     */
1023    public static final int FOCUS_FORWARD = 0x00000002;
1024
1025    /**
1026     * Use with {@link #focusSearch(int)}. Move focus to the left.
1027     */
1028    public static final int FOCUS_LEFT = 0x00000011;
1029
1030    /**
1031     * Use with {@link #focusSearch(int)}. Move focus up.
1032     */
1033    public static final int FOCUS_UP = 0x00000021;
1034
1035    /**
1036     * Use with {@link #focusSearch(int)}. Move focus to the right.
1037     */
1038    public static final int FOCUS_RIGHT = 0x00000042;
1039
1040    /**
1041     * Use with {@link #focusSearch(int)}. Move focus down.
1042     */
1043    public static final int FOCUS_DOWN = 0x00000082;
1044
1045    /**
1046     * Bits of {@link #getMeasuredWidthAndState()} and
1047     * {@link #getMeasuredWidthAndState()} that provide the actual measured size.
1048     */
1049    public static final int MEASURED_SIZE_MASK = 0x00ffffff;
1050
1051    /**
1052     * Bits of {@link #getMeasuredWidthAndState()} and
1053     * {@link #getMeasuredWidthAndState()} that provide the additional state bits.
1054     */
1055    public static final int MEASURED_STATE_MASK = 0xff000000;
1056
1057    /**
1058     * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits
1059     * for functions that combine both width and height into a single int,
1060     * such as {@link #getMeasuredState()} and the childState argument of
1061     * {@link #resolveSizeAndState(int, int, int)}.
1062     */
1063    public static final int MEASURED_HEIGHT_STATE_SHIFT = 16;
1064
1065    /**
1066     * Bit of {@link #getMeasuredWidthAndState()} and
1067     * {@link #getMeasuredWidthAndState()} that indicates the measured size
1068     * is smaller that the space the view would like to have.
1069     */
1070    public static final int MEASURED_STATE_TOO_SMALL = 0x01000000;
1071
1072    /**
1073     * Base View state sets
1074     */
1075    // Singles
1076    /**
1077     * Indicates the view has no states set. States are used with
1078     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1079     * view depending on its state.
1080     *
1081     * @see android.graphics.drawable.Drawable
1082     * @see #getDrawableState()
1083     */
1084    protected static final int[] EMPTY_STATE_SET;
1085    /**
1086     * Indicates the view is enabled. States are used with
1087     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1088     * view depending on its state.
1089     *
1090     * @see android.graphics.drawable.Drawable
1091     * @see #getDrawableState()
1092     */
1093    protected static final int[] ENABLED_STATE_SET;
1094    /**
1095     * Indicates the view is focused. States are used with
1096     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1097     * view depending on its state.
1098     *
1099     * @see android.graphics.drawable.Drawable
1100     * @see #getDrawableState()
1101     */
1102    protected static final int[] FOCUSED_STATE_SET;
1103    /**
1104     * Indicates the view is selected. States are used with
1105     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1106     * view depending on its state.
1107     *
1108     * @see android.graphics.drawable.Drawable
1109     * @see #getDrawableState()
1110     */
1111    protected static final int[] SELECTED_STATE_SET;
1112    /**
1113     * Indicates the view is pressed. States are used with
1114     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1115     * view depending on its state.
1116     *
1117     * @see android.graphics.drawable.Drawable
1118     * @see #getDrawableState()
1119     * @hide
1120     */
1121    protected static final int[] PRESSED_STATE_SET;
1122    /**
1123     * Indicates the view's window has focus. States are used with
1124     * {@link android.graphics.drawable.Drawable} to change the drawing of the
1125     * view depending on its state.
1126     *
1127     * @see android.graphics.drawable.Drawable
1128     * @see #getDrawableState()
1129     */
1130    protected static final int[] WINDOW_FOCUSED_STATE_SET;
1131    // Doubles
1132    /**
1133     * Indicates the view is enabled and has the focus.
1134     *
1135     * @see #ENABLED_STATE_SET
1136     * @see #FOCUSED_STATE_SET
1137     */
1138    protected static final int[] ENABLED_FOCUSED_STATE_SET;
1139    /**
1140     * Indicates the view is enabled and selected.
1141     *
1142     * @see #ENABLED_STATE_SET
1143     * @see #SELECTED_STATE_SET
1144     */
1145    protected static final int[] ENABLED_SELECTED_STATE_SET;
1146    /**
1147     * Indicates the view is enabled and that its window has focus.
1148     *
1149     * @see #ENABLED_STATE_SET
1150     * @see #WINDOW_FOCUSED_STATE_SET
1151     */
1152    protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET;
1153    /**
1154     * Indicates the view is focused and selected.
1155     *
1156     * @see #FOCUSED_STATE_SET
1157     * @see #SELECTED_STATE_SET
1158     */
1159    protected static final int[] FOCUSED_SELECTED_STATE_SET;
1160    /**
1161     * Indicates the view has the focus and that its window has the focus.
1162     *
1163     * @see #FOCUSED_STATE_SET
1164     * @see #WINDOW_FOCUSED_STATE_SET
1165     */
1166    protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET;
1167    /**
1168     * Indicates the view is selected and that its window has the focus.
1169     *
1170     * @see #SELECTED_STATE_SET
1171     * @see #WINDOW_FOCUSED_STATE_SET
1172     */
1173    protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET;
1174    // Triples
1175    /**
1176     * Indicates the view is enabled, focused and selected.
1177     *
1178     * @see #ENABLED_STATE_SET
1179     * @see #FOCUSED_STATE_SET
1180     * @see #SELECTED_STATE_SET
1181     */
1182    protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET;
1183    /**
1184     * Indicates the view is enabled, focused and its window has the focus.
1185     *
1186     * @see #ENABLED_STATE_SET
1187     * @see #FOCUSED_STATE_SET
1188     * @see #WINDOW_FOCUSED_STATE_SET
1189     */
1190    protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1191    /**
1192     * Indicates the view is enabled, selected and its window has the focus.
1193     *
1194     * @see #ENABLED_STATE_SET
1195     * @see #SELECTED_STATE_SET
1196     * @see #WINDOW_FOCUSED_STATE_SET
1197     */
1198    protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1199    /**
1200     * Indicates the view is focused, selected and its window has the focus.
1201     *
1202     * @see #FOCUSED_STATE_SET
1203     * @see #SELECTED_STATE_SET
1204     * @see #WINDOW_FOCUSED_STATE_SET
1205     */
1206    protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1207    /**
1208     * Indicates the view is enabled, focused, selected and its window
1209     * has the focus.
1210     *
1211     * @see #ENABLED_STATE_SET
1212     * @see #FOCUSED_STATE_SET
1213     * @see #SELECTED_STATE_SET
1214     * @see #WINDOW_FOCUSED_STATE_SET
1215     */
1216    protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1217    /**
1218     * Indicates the view is pressed and its window has the focus.
1219     *
1220     * @see #PRESSED_STATE_SET
1221     * @see #WINDOW_FOCUSED_STATE_SET
1222     */
1223    protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET;
1224    /**
1225     * Indicates the view is pressed and selected.
1226     *
1227     * @see #PRESSED_STATE_SET
1228     * @see #SELECTED_STATE_SET
1229     */
1230    protected static final int[] PRESSED_SELECTED_STATE_SET;
1231    /**
1232     * Indicates the view is pressed, selected and its window has the focus.
1233     *
1234     * @see #PRESSED_STATE_SET
1235     * @see #SELECTED_STATE_SET
1236     * @see #WINDOW_FOCUSED_STATE_SET
1237     */
1238    protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1239    /**
1240     * Indicates the view is pressed and focused.
1241     *
1242     * @see #PRESSED_STATE_SET
1243     * @see #FOCUSED_STATE_SET
1244     */
1245    protected static final int[] PRESSED_FOCUSED_STATE_SET;
1246    /**
1247     * Indicates the view is pressed, focused and its window has the focus.
1248     *
1249     * @see #PRESSED_STATE_SET
1250     * @see #FOCUSED_STATE_SET
1251     * @see #WINDOW_FOCUSED_STATE_SET
1252     */
1253    protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1254    /**
1255     * Indicates the view is pressed, focused and selected.
1256     *
1257     * @see #PRESSED_STATE_SET
1258     * @see #SELECTED_STATE_SET
1259     * @see #FOCUSED_STATE_SET
1260     */
1261    protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET;
1262    /**
1263     * Indicates the view is pressed, focused, selected and its window has the focus.
1264     *
1265     * @see #PRESSED_STATE_SET
1266     * @see #FOCUSED_STATE_SET
1267     * @see #SELECTED_STATE_SET
1268     * @see #WINDOW_FOCUSED_STATE_SET
1269     */
1270    protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1271    /**
1272     * Indicates the view is pressed and enabled.
1273     *
1274     * @see #PRESSED_STATE_SET
1275     * @see #ENABLED_STATE_SET
1276     */
1277    protected static final int[] PRESSED_ENABLED_STATE_SET;
1278    /**
1279     * Indicates the view is pressed, enabled and its window has the focus.
1280     *
1281     * @see #PRESSED_STATE_SET
1282     * @see #ENABLED_STATE_SET
1283     * @see #WINDOW_FOCUSED_STATE_SET
1284     */
1285    protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET;
1286    /**
1287     * Indicates the view is pressed, enabled and selected.
1288     *
1289     * @see #PRESSED_STATE_SET
1290     * @see #ENABLED_STATE_SET
1291     * @see #SELECTED_STATE_SET
1292     */
1293    protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET;
1294    /**
1295     * Indicates the view is pressed, enabled, selected and its window has the
1296     * focus.
1297     *
1298     * @see #PRESSED_STATE_SET
1299     * @see #ENABLED_STATE_SET
1300     * @see #SELECTED_STATE_SET
1301     * @see #WINDOW_FOCUSED_STATE_SET
1302     */
1303    protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1304    /**
1305     * Indicates the view is pressed, enabled and focused.
1306     *
1307     * @see #PRESSED_STATE_SET
1308     * @see #ENABLED_STATE_SET
1309     * @see #FOCUSED_STATE_SET
1310     */
1311    protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET;
1312    /**
1313     * Indicates the view is pressed, enabled, focused and its window has the
1314     * focus.
1315     *
1316     * @see #PRESSED_STATE_SET
1317     * @see #ENABLED_STATE_SET
1318     * @see #FOCUSED_STATE_SET
1319     * @see #WINDOW_FOCUSED_STATE_SET
1320     */
1321    protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET;
1322    /**
1323     * Indicates the view is pressed, enabled, focused and selected.
1324     *
1325     * @see #PRESSED_STATE_SET
1326     * @see #ENABLED_STATE_SET
1327     * @see #SELECTED_STATE_SET
1328     * @see #FOCUSED_STATE_SET
1329     */
1330    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET;
1331    /**
1332     * Indicates the view is pressed, enabled, focused, selected and its window
1333     * has the focus.
1334     *
1335     * @see #PRESSED_STATE_SET
1336     * @see #ENABLED_STATE_SET
1337     * @see #SELECTED_STATE_SET
1338     * @see #FOCUSED_STATE_SET
1339     * @see #WINDOW_FOCUSED_STATE_SET
1340     */
1341    protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET;
1342
1343    /**
1344     * The order here is very important to {@link #getDrawableState()}
1345     */
1346    private static final int[][] VIEW_STATE_SETS;
1347
1348    static final int VIEW_STATE_WINDOW_FOCUSED = 1;
1349    static final int VIEW_STATE_SELECTED = 1 << 1;
1350    static final int VIEW_STATE_FOCUSED = 1 << 2;
1351    static final int VIEW_STATE_ENABLED = 1 << 3;
1352    static final int VIEW_STATE_PRESSED = 1 << 4;
1353    static final int VIEW_STATE_ACTIVATED = 1 << 5;
1354    static final int VIEW_STATE_ACCELERATED = 1 << 6;
1355    static final int VIEW_STATE_HOVERED = 1 << 7;
1356    static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8;
1357    static final int VIEW_STATE_DRAG_HOVERED = 1 << 9;
1358
1359    static final int[] VIEW_STATE_IDS = new int[] {
1360        R.attr.state_window_focused,    VIEW_STATE_WINDOW_FOCUSED,
1361        R.attr.state_selected,          VIEW_STATE_SELECTED,
1362        R.attr.state_focused,           VIEW_STATE_FOCUSED,
1363        R.attr.state_enabled,           VIEW_STATE_ENABLED,
1364        R.attr.state_pressed,           VIEW_STATE_PRESSED,
1365        R.attr.state_activated,         VIEW_STATE_ACTIVATED,
1366        R.attr.state_accelerated,       VIEW_STATE_ACCELERATED,
1367        R.attr.state_hovered,           VIEW_STATE_HOVERED,
1368        R.attr.state_drag_can_accept,   VIEW_STATE_DRAG_CAN_ACCEPT,
1369        R.attr.state_drag_hovered,      VIEW_STATE_DRAG_HOVERED,
1370    };
1371
1372    static {
1373        if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) {
1374            throw new IllegalStateException(
1375                    "VIEW_STATE_IDs array length does not match ViewDrawableStates style array");
1376        }
1377        int[] orderedIds = new int[VIEW_STATE_IDS.length];
1378        for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) {
1379            int viewState = R.styleable.ViewDrawableStates[i];
1380            for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) {
1381                if (VIEW_STATE_IDS[j] == viewState) {
1382                    orderedIds[i * 2] = viewState;
1383                    orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1];
1384                }
1385            }
1386        }
1387        final int NUM_BITS = VIEW_STATE_IDS.length / 2;
1388        VIEW_STATE_SETS = new int[1 << NUM_BITS][];
1389        for (int i = 0; i < VIEW_STATE_SETS.length; i++) {
1390            int numBits = Integer.bitCount(i);
1391            int[] set = new int[numBits];
1392            int pos = 0;
1393            for (int j = 0; j < orderedIds.length; j += 2) {
1394                if ((i & orderedIds[j+1]) != 0) {
1395                    set[pos++] = orderedIds[j];
1396                }
1397            }
1398            VIEW_STATE_SETS[i] = set;
1399        }
1400
1401        EMPTY_STATE_SET = VIEW_STATE_SETS[0];
1402        WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED];
1403        SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED];
1404        SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1405                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED];
1406        FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED];
1407        FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1408                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED];
1409        FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1410                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED];
1411        FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1412                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1413                | VIEW_STATE_FOCUSED];
1414        ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED];
1415        ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1416                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED];
1417        ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1418                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED];
1419        ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1420                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1421                | VIEW_STATE_ENABLED];
1422        ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1423                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED];
1424        ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1425                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1426                | VIEW_STATE_ENABLED];
1427        ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1428                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1429                | VIEW_STATE_ENABLED];
1430        ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1431                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1432                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED];
1433
1434        PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED];
1435        PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1436                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED];
1437        PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1438                VIEW_STATE_SELECTED | VIEW_STATE_PRESSED];
1439        PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1440                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1441                | VIEW_STATE_PRESSED];
1442        PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1443                VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1444        PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1445                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1446                | VIEW_STATE_PRESSED];
1447        PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1448                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1449                | VIEW_STATE_PRESSED];
1450        PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1451                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1452                | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED];
1453        PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[
1454                VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1455        PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1456                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED
1457                | VIEW_STATE_PRESSED];
1458        PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1459                VIEW_STATE_SELECTED | VIEW_STATE_ENABLED
1460                | VIEW_STATE_PRESSED];
1461        PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1462                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1463                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1464        PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1465                VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED
1466                | VIEW_STATE_PRESSED];
1467        PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1468                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED
1469                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1470        PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[
1471                VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED
1472                | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED];
1473        PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[
1474                VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED
1475                | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED
1476                | VIEW_STATE_PRESSED];
1477    }
1478
1479    /**
1480     * Accessibility event types that are dispatched for text population.
1481     */
1482    private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES =
1483            AccessibilityEvent.TYPE_VIEW_CLICKED
1484            | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED
1485            | AccessibilityEvent.TYPE_VIEW_SELECTED
1486            | AccessibilityEvent.TYPE_VIEW_FOCUSED
1487            | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
1488            | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER
1489            | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
1490            | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED
1491            | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
1492
1493    /**
1494     * Temporary Rect currently for use in setBackground().  This will probably
1495     * be extended in the future to hold our own class with more than just
1496     * a Rect. :)
1497     */
1498    static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
1499
1500    /**
1501     * Temporary flag, used to enable processing of View properties in the native DisplayList
1502     * object instead of during draw(). Soon to be enabled by default for hardware-accelerated
1503     * apps.
1504     * @hide
1505     */
1506    protected static final boolean USE_DISPLAY_LIST_PROPERTIES = false;
1507
1508    /**
1509     * Map used to store views' tags.
1510     */
1511    private SparseArray<Object> mKeyedTags;
1512
1513    /**
1514     * The next available accessiiblity id.
1515     */
1516    private static int sNextAccessibilityViewId;
1517
1518    /**
1519     * The animation currently associated with this view.
1520     * @hide
1521     */
1522    protected Animation mCurrentAnimation = null;
1523
1524    /**
1525     * Width as measured during measure pass.
1526     * {@hide}
1527     */
1528    @ViewDebug.ExportedProperty(category = "measurement")
1529    int mMeasuredWidth;
1530
1531    /**
1532     * Height as measured during measure pass.
1533     * {@hide}
1534     */
1535    @ViewDebug.ExportedProperty(category = "measurement")
1536    int mMeasuredHeight;
1537
1538    /**
1539     * Flag to indicate that this view was marked INVALIDATED, or had its display list
1540     * invalidated, prior to the current drawing iteration. If true, the view must re-draw
1541     * its display list. This flag, used only when hw accelerated, allows us to clear the
1542     * flag while retaining this information until it's needed (at getDisplayList() time and
1543     * in drawChild(), when we decide to draw a view's children's display lists into our own).
1544     *
1545     * {@hide}
1546     */
1547    boolean mRecreateDisplayList = false;
1548
1549    /**
1550     * The view's identifier.
1551     * {@hide}
1552     *
1553     * @see #setId(int)
1554     * @see #getId()
1555     */
1556    @ViewDebug.ExportedProperty(resolveId = true)
1557    int mID = NO_ID;
1558
1559    /**
1560     * The stable ID of this view for accessibility purposes.
1561     */
1562    int mAccessibilityViewId = NO_ID;
1563
1564    /**
1565     * The view's tag.
1566     * {@hide}
1567     *
1568     * @see #setTag(Object)
1569     * @see #getTag()
1570     */
1571    protected Object mTag;
1572
1573    // for mPrivateFlags:
1574    /** {@hide} */
1575    static final int WANTS_FOCUS                    = 0x00000001;
1576    /** {@hide} */
1577    static final int FOCUSED                        = 0x00000002;
1578    /** {@hide} */
1579    static final int SELECTED                       = 0x00000004;
1580    /** {@hide} */
1581    static final int IS_ROOT_NAMESPACE              = 0x00000008;
1582    /** {@hide} */
1583    static final int HAS_BOUNDS                     = 0x00000010;
1584    /** {@hide} */
1585    static final int DRAWN                          = 0x00000020;
1586    /**
1587     * When this flag is set, this view is running an animation on behalf of its
1588     * children and should therefore not cancel invalidate requests, even if they
1589     * lie outside of this view's bounds.
1590     *
1591     * {@hide}
1592     */
1593    static final int DRAW_ANIMATION                 = 0x00000040;
1594    /** {@hide} */
1595    static final int SKIP_DRAW                      = 0x00000080;
1596    /** {@hide} */
1597    static final int ONLY_DRAWS_BACKGROUND          = 0x00000100;
1598    /** {@hide} */
1599    static final int REQUEST_TRANSPARENT_REGIONS    = 0x00000200;
1600    /** {@hide} */
1601    static final int DRAWABLE_STATE_DIRTY           = 0x00000400;
1602    /** {@hide} */
1603    static final int MEASURED_DIMENSION_SET         = 0x00000800;
1604    /** {@hide} */
1605    static final int FORCE_LAYOUT                   = 0x00001000;
1606    /** {@hide} */
1607    static final int LAYOUT_REQUIRED                = 0x00002000;
1608
1609    private static final int PRESSED                = 0x00004000;
1610
1611    /** {@hide} */
1612    static final int DRAWING_CACHE_VALID            = 0x00008000;
1613    /**
1614     * Flag used to indicate that this view should be drawn once more (and only once
1615     * more) after its animation has completed.
1616     * {@hide}
1617     */
1618    static final int ANIMATION_STARTED              = 0x00010000;
1619
1620    private static final int SAVE_STATE_CALLED      = 0x00020000;
1621
1622    /**
1623     * Indicates that the View returned true when onSetAlpha() was called and that
1624     * the alpha must be restored.
1625     * {@hide}
1626     */
1627    static final int ALPHA_SET                      = 0x00040000;
1628
1629    /**
1630     * Set by {@link #setScrollContainer(boolean)}.
1631     */
1632    static final int SCROLL_CONTAINER               = 0x00080000;
1633
1634    /**
1635     * Set by {@link #setScrollContainer(boolean)}.
1636     */
1637    static final int SCROLL_CONTAINER_ADDED         = 0x00100000;
1638
1639    /**
1640     * View flag indicating whether this view was invalidated (fully or partially.)
1641     *
1642     * @hide
1643     */
1644    static final int DIRTY                          = 0x00200000;
1645
1646    /**
1647     * View flag indicating whether this view was invalidated by an opaque
1648     * invalidate request.
1649     *
1650     * @hide
1651     */
1652    static final int DIRTY_OPAQUE                   = 0x00400000;
1653
1654    /**
1655     * Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
1656     *
1657     * @hide
1658     */
1659    static final int DIRTY_MASK                     = 0x00600000;
1660
1661    /**
1662     * Indicates whether the background is opaque.
1663     *
1664     * @hide
1665     */
1666    static final int OPAQUE_BACKGROUND              = 0x00800000;
1667
1668    /**
1669     * Indicates whether the scrollbars are opaque.
1670     *
1671     * @hide
1672     */
1673    static final int OPAQUE_SCROLLBARS              = 0x01000000;
1674
1675    /**
1676     * Indicates whether the view is opaque.
1677     *
1678     * @hide
1679     */
1680    static final int OPAQUE_MASK                    = 0x01800000;
1681
1682    /**
1683     * Indicates a prepressed state;
1684     * the short time between ACTION_DOWN and recognizing
1685     * a 'real' press. Prepressed is used to recognize quick taps
1686     * even when they are shorter than ViewConfiguration.getTapTimeout().
1687     *
1688     * @hide
1689     */
1690    private static final int PREPRESSED             = 0x02000000;
1691
1692    /**
1693     * Indicates whether the view is temporarily detached.
1694     *
1695     * @hide
1696     */
1697    static final int CANCEL_NEXT_UP_EVENT = 0x04000000;
1698
1699    /**
1700     * Indicates that we should awaken scroll bars once attached
1701     *
1702     * @hide
1703     */
1704    private static final int AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000;
1705
1706    /**
1707     * Indicates that the view has received HOVER_ENTER.  Cleared on HOVER_EXIT.
1708     * @hide
1709     */
1710    private static final int HOVERED              = 0x10000000;
1711
1712    /**
1713     * Indicates that pivotX or pivotY were explicitly set and we should not assume the center
1714     * for transform operations
1715     *
1716     * @hide
1717     */
1718    private static final int PIVOT_EXPLICITLY_SET = 0x20000000;
1719
1720    /** {@hide} */
1721    static final int ACTIVATED                    = 0x40000000;
1722
1723    /**
1724     * Indicates that this view was specifically invalidated, not just dirtied because some
1725     * child view was invalidated. The flag is used to determine when we need to recreate
1726     * a view's display list (as opposed to just returning a reference to its existing
1727     * display list).
1728     *
1729     * @hide
1730     */
1731    static final int INVALIDATED                  = 0x80000000;
1732
1733    /* Masks for mPrivateFlags2 */
1734
1735    /**
1736     * Indicates that this view has reported that it can accept the current drag's content.
1737     * Cleared when the drag operation concludes.
1738     * @hide
1739     */
1740    static final int DRAG_CAN_ACCEPT              = 0x00000001;
1741
1742    /**
1743     * Indicates that this view is currently directly under the drag location in a
1744     * drag-and-drop operation involving content that it can accept.  Cleared when
1745     * the drag exits the view, or when the drag operation concludes.
1746     * @hide
1747     */
1748    static final int DRAG_HOVERED                 = 0x00000002;
1749
1750    /**
1751     * Indicates whether the view layout direction has been resolved and drawn to the
1752     * right-to-left direction.
1753     *
1754     * @hide
1755     */
1756    static final int LAYOUT_DIRECTION_RESOLVED_RTL = 0x00000004;
1757
1758    /**
1759     * Indicates whether the view layout direction has been resolved.
1760     *
1761     * @hide
1762     */
1763    static final int LAYOUT_DIRECTION_RESOLVED = 0x00000008;
1764
1765
1766    /**
1767     * Indicates that the view is tracking some sort of transient state
1768     * that the app should not need to be aware of, but that the framework
1769     * should take special care to preserve.
1770     *
1771     * @hide
1772     */
1773    static final int HAS_TRANSIENT_STATE = 0x00000010;
1774
1775
1776    /* End of masks for mPrivateFlags2 */
1777
1778    static final int DRAG_MASK = DRAG_CAN_ACCEPT | DRAG_HOVERED;
1779
1780    /**
1781     * Always allow a user to over-scroll this view, provided it is a
1782     * view that can scroll.
1783     *
1784     * @see #getOverScrollMode()
1785     * @see #setOverScrollMode(int)
1786     */
1787    public static final int OVER_SCROLL_ALWAYS = 0;
1788
1789    /**
1790     * Allow a user to over-scroll this view only if the content is large
1791     * enough to meaningfully scroll, provided it is a view that can scroll.
1792     *
1793     * @see #getOverScrollMode()
1794     * @see #setOverScrollMode(int)
1795     */
1796    public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1;
1797
1798    /**
1799     * Never allow a user to over-scroll this view.
1800     *
1801     * @see #getOverScrollMode()
1802     * @see #setOverScrollMode(int)
1803     */
1804    public static final int OVER_SCROLL_NEVER = 2;
1805
1806    /**
1807     * View has requested the system UI (status bar) to be visible (the default).
1808     *
1809     * @see #setSystemUiVisibility(int)
1810     */
1811    public static final int SYSTEM_UI_FLAG_VISIBLE = 0;
1812
1813    /**
1814     * View has requested the system UI to enter an unobtrusive "low profile" mode.
1815     *
1816     * This is for use in games, book readers, video players, or any other "immersive" application
1817     * where the usual system chrome is deemed too distracting.
1818     *
1819     * In low profile mode, the status bar and/or navigation icons may dim.
1820     *
1821     * @see #setSystemUiVisibility(int)
1822     */
1823    public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001;
1824
1825    /**
1826     * View has requested that the system navigation be temporarily hidden.
1827     *
1828     * This is an even less obtrusive state than that called for by
1829     * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls
1830     * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause
1831     * those to disappear. This is useful (in conjunction with the
1832     * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and
1833     * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN}
1834     * window flags) for displaying content using every last pixel on the display.
1835     *
1836     * There is a limitation: because navigation controls are so important, the least user
1837     * interaction will cause them to reappear immediately.
1838     *
1839     * @see #setSystemUiVisibility(int)
1840     */
1841    public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002;
1842
1843    /**
1844     * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead.
1845     */
1846    public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE;
1847
1848    /**
1849     * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead.
1850     */
1851    public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE;
1852
1853    /**
1854     * @hide
1855     *
1856     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1857     * out of the public fields to keep the undefined bits out of the developer's way.
1858     *
1859     * Flag to make the status bar not expandable.  Unless you also
1860     * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show.
1861     */
1862    public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000;
1863
1864    /**
1865     * @hide
1866     *
1867     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1868     * out of the public fields to keep the undefined bits out of the developer's way.
1869     *
1870     * Flag to hide notification icons and scrolling ticker text.
1871     */
1872    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000;
1873
1874    /**
1875     * @hide
1876     *
1877     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1878     * out of the public fields to keep the undefined bits out of the developer's way.
1879     *
1880     * Flag to disable incoming notification alerts.  This will not block
1881     * icons, but it will block sound, vibrating and other visual or aural notifications.
1882     */
1883    public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000;
1884
1885    /**
1886     * @hide
1887     *
1888     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1889     * out of the public fields to keep the undefined bits out of the developer's way.
1890     *
1891     * Flag to hide only the scrolling ticker.  Note that
1892     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies
1893     * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}.
1894     */
1895    public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000;
1896
1897    /**
1898     * @hide
1899     *
1900     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1901     * out of the public fields to keep the undefined bits out of the developer's way.
1902     *
1903     * Flag to hide the center system info area.
1904     */
1905    public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000;
1906
1907    /**
1908     * @hide
1909     *
1910     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1911     * out of the public fields to keep the undefined bits out of the developer's way.
1912     *
1913     * Flag to hide only the home button.  Don't use this
1914     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1915     */
1916    public static final int STATUS_BAR_DISABLE_HOME = 0x00200000;
1917
1918    /**
1919     * @hide
1920     *
1921     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1922     * out of the public fields to keep the undefined bits out of the developer's way.
1923     *
1924     * Flag to hide only the back button. Don't use this
1925     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1926     */
1927    public static final int STATUS_BAR_DISABLE_BACK = 0x00400000;
1928
1929    /**
1930     * @hide
1931     *
1932     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1933     * out of the public fields to keep the undefined bits out of the developer's way.
1934     *
1935     * Flag to hide only the clock.  You might use this if your activity has
1936     * its own clock making the status bar's clock redundant.
1937     */
1938    public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000;
1939
1940    /**
1941     * @hide
1942     *
1943     * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked
1944     * out of the public fields to keep the undefined bits out of the developer's way.
1945     *
1946     * Flag to hide only the recent apps button. Don't use this
1947     * unless you're a special part of the system UI (i.e., setup wizard, keyguard).
1948     */
1949    public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000;
1950
1951    /**
1952     * @hide
1953     *
1954     * NOTE: This flag may only be used in subtreeSystemUiVisibility, etc. etc.
1955     *
1956     * This hides HOME and RECENT and is provided for compatibility with interim implementations.
1957     */
1958    @Deprecated
1959    public static final int STATUS_BAR_DISABLE_NAVIGATION =
1960            STATUS_BAR_DISABLE_HOME | STATUS_BAR_DISABLE_RECENT;
1961
1962    /**
1963     * @hide
1964     */
1965    public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF;
1966
1967    /**
1968     * These are the system UI flags that can be cleared by events outside
1969     * of an application.  Currently this is just the ability to tap on the
1970     * screen while hiding the navigation bar to have it return.
1971     * @hide
1972     */
1973    public static final int SYSTEM_UI_CLEARABLE_FLAGS =
1974            SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION;
1975
1976    /**
1977     * Find views that render the specified text.
1978     *
1979     * @see #findViewsWithText(ArrayList, CharSequence, int)
1980     */
1981    public static final int FIND_VIEWS_WITH_TEXT = 0x00000001;
1982
1983    /**
1984     * Find find views that contain the specified content description.
1985     *
1986     * @see #findViewsWithText(ArrayList, CharSequence, int)
1987     */
1988    public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002;
1989
1990    /**
1991     * Find views that contain {@link AccessibilityNodeProvider}. Such
1992     * a View is a root of virtual view hierarchy and may contain the searched
1993     * text. If this flag is set Views with providers are automatically
1994     * added and it is a responsibility of the client to call the APIs of
1995     * the provider to determine whether the virtual tree rooted at this View
1996     * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s
1997     * represeting the virtual views with this text.
1998     *
1999     * @see #findViewsWithText(ArrayList, CharSequence, int)
2000     *
2001     * @hide
2002     */
2003    public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004;
2004
2005    /**
2006     * Indicates that the screen has changed state and is now off.
2007     *
2008     * @see #onScreenStateChanged(int)
2009     */
2010    public static final int SCREEN_STATE_OFF = 0x0;
2011
2012    /**
2013     * Indicates that the screen has changed state and is now on.
2014     *
2015     * @see #onScreenStateChanged(int)
2016     */
2017    public static final int SCREEN_STATE_ON = 0x1;
2018
2019    /**
2020     * Controls the over-scroll mode for this view.
2021     * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)},
2022     * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS},
2023     * and {@link #OVER_SCROLL_NEVER}.
2024     */
2025    private int mOverScrollMode;
2026
2027    /**
2028     * The parent this view is attached to.
2029     * {@hide}
2030     *
2031     * @see #getParent()
2032     */
2033    protected ViewParent mParent;
2034
2035    /**
2036     * {@hide}
2037     */
2038    AttachInfo mAttachInfo;
2039
2040    /**
2041     * {@hide}
2042     */
2043    @ViewDebug.ExportedProperty(flagMapping = {
2044        @ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
2045                name = "FORCE_LAYOUT"),
2046        @ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
2047                name = "LAYOUT_REQUIRED"),
2048        @ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
2049            name = "DRAWING_CACHE_INVALID", outputIf = false),
2050        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
2051        @ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
2052        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
2053        @ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
2054    })
2055    int mPrivateFlags;
2056    int mPrivateFlags2;
2057
2058    /**
2059     * This view's request for the visibility of the status bar.
2060     * @hide
2061     */
2062    @ViewDebug.ExportedProperty(flagMapping = {
2063        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE,
2064                                equals = SYSTEM_UI_FLAG_LOW_PROFILE,
2065                                name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true),
2066        @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2067                                equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION,
2068                                name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true),
2069        @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK,
2070                                equals = SYSTEM_UI_FLAG_VISIBLE,
2071                                name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true)
2072    })
2073    int mSystemUiVisibility;
2074
2075    /**
2076     * Count of how many windows this view has been attached to.
2077     */
2078    int mWindowAttachCount;
2079
2080    /**
2081     * The layout parameters associated with this view and used by the parent
2082     * {@link android.view.ViewGroup} to determine how this view should be
2083     * laid out.
2084     * {@hide}
2085     */
2086    protected ViewGroup.LayoutParams mLayoutParams;
2087
2088    /**
2089     * The view flags hold various views states.
2090     * {@hide}
2091     */
2092    @ViewDebug.ExportedProperty
2093    int mViewFlags;
2094
2095    static class TransformationInfo {
2096        /**
2097         * The transform matrix for the View. This transform is calculated internally
2098         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2099         * is used by default. Do *not* use this variable directly; instead call
2100         * getMatrix(), which will automatically recalculate the matrix if necessary
2101         * to get the correct matrix based on the latest rotation and scale properties.
2102         */
2103        private final Matrix mMatrix = new Matrix();
2104
2105        /**
2106         * The transform matrix for the View. This transform is calculated internally
2107         * based on the rotation, scaleX, and scaleY properties. The identity matrix
2108         * is used by default. Do *not* use this variable directly; instead call
2109         * getInverseMatrix(), which will automatically recalculate the matrix if necessary
2110         * to get the correct matrix based on the latest rotation and scale properties.
2111         */
2112        private Matrix mInverseMatrix;
2113
2114        /**
2115         * An internal variable that tracks whether we need to recalculate the
2116         * transform matrix, based on whether the rotation or scaleX/Y properties
2117         * have changed since the matrix was last calculated.
2118         */
2119        boolean mMatrixDirty = false;
2120
2121        /**
2122         * An internal variable that tracks whether we need to recalculate the
2123         * transform matrix, based on whether the rotation or scaleX/Y properties
2124         * have changed since the matrix was last calculated.
2125         */
2126        private boolean mInverseMatrixDirty = true;
2127
2128        /**
2129         * A variable that tracks whether we need to recalculate the
2130         * transform matrix, based on whether the rotation or scaleX/Y properties
2131         * have changed since the matrix was last calculated. This variable
2132         * is only valid after a call to updateMatrix() or to a function that
2133         * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix().
2134         */
2135        private boolean mMatrixIsIdentity = true;
2136
2137        /**
2138         * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set.
2139         */
2140        private Camera mCamera = null;
2141
2142        /**
2143         * This matrix is used when computing the matrix for 3D rotations.
2144         */
2145        private Matrix matrix3D = null;
2146
2147        /**
2148         * These prev values are used to recalculate a centered pivot point when necessary. The
2149         * pivot point is only used in matrix operations (when rotation, scale, or translation are
2150         * set), so thes values are only used then as well.
2151         */
2152        private int mPrevWidth = -1;
2153        private int mPrevHeight = -1;
2154
2155        /**
2156         * The degrees rotation around the vertical axis through the pivot point.
2157         */
2158        @ViewDebug.ExportedProperty
2159        float mRotationY = 0f;
2160
2161        /**
2162         * The degrees rotation around the horizontal axis through the pivot point.
2163         */
2164        @ViewDebug.ExportedProperty
2165        float mRotationX = 0f;
2166
2167        /**
2168         * The degrees rotation around the pivot point.
2169         */
2170        @ViewDebug.ExportedProperty
2171        float mRotation = 0f;
2172
2173        /**
2174         * The amount of translation of the object away from its left property (post-layout).
2175         */
2176        @ViewDebug.ExportedProperty
2177        float mTranslationX = 0f;
2178
2179        /**
2180         * The amount of translation of the object away from its top property (post-layout).
2181         */
2182        @ViewDebug.ExportedProperty
2183        float mTranslationY = 0f;
2184
2185        /**
2186         * The amount of scale in the x direction around the pivot point. A
2187         * value of 1 means no scaling is applied.
2188         */
2189        @ViewDebug.ExportedProperty
2190        float mScaleX = 1f;
2191
2192        /**
2193         * The amount of scale in the y direction around the pivot point. A
2194         * value of 1 means no scaling is applied.
2195         */
2196        @ViewDebug.ExportedProperty
2197        float mScaleY = 1f;
2198
2199        /**
2200         * The x location of the point around which the view is rotated and scaled.
2201         */
2202        @ViewDebug.ExportedProperty
2203        float mPivotX = 0f;
2204
2205        /**
2206         * The y location of the point around which the view is rotated and scaled.
2207         */
2208        @ViewDebug.ExportedProperty
2209        float mPivotY = 0f;
2210
2211        /**
2212         * The opacity of the View. This is a value from 0 to 1, where 0 means
2213         * completely transparent and 1 means completely opaque.
2214         */
2215        @ViewDebug.ExportedProperty
2216        float mAlpha = 1f;
2217    }
2218
2219    TransformationInfo mTransformationInfo;
2220
2221    private boolean mLastIsOpaque;
2222
2223    /**
2224     * Convenience value to check for float values that are close enough to zero to be considered
2225     * zero.
2226     */
2227    private static final float NONZERO_EPSILON = .001f;
2228
2229    /**
2230     * The distance in pixels from the left edge of this view's parent
2231     * to the left edge of this view.
2232     * {@hide}
2233     */
2234    @ViewDebug.ExportedProperty(category = "layout")
2235    protected int mLeft;
2236    /**
2237     * The distance in pixels from the left edge of this view's parent
2238     * to the right edge of this view.
2239     * {@hide}
2240     */
2241    @ViewDebug.ExportedProperty(category = "layout")
2242    protected int mRight;
2243    /**
2244     * The distance in pixels from the top edge of this view's parent
2245     * to the top edge of this view.
2246     * {@hide}
2247     */
2248    @ViewDebug.ExportedProperty(category = "layout")
2249    protected int mTop;
2250    /**
2251     * The distance in pixels from the top edge of this view's parent
2252     * to the bottom edge of this view.
2253     * {@hide}
2254     */
2255    @ViewDebug.ExportedProperty(category = "layout")
2256    protected int mBottom;
2257
2258    /**
2259     * The offset, in pixels, by which the content of this view is scrolled
2260     * horizontally.
2261     * {@hide}
2262     */
2263    @ViewDebug.ExportedProperty(category = "scrolling")
2264    protected int mScrollX;
2265    /**
2266     * The offset, in pixels, by which the content of this view is scrolled
2267     * vertically.
2268     * {@hide}
2269     */
2270    @ViewDebug.ExportedProperty(category = "scrolling")
2271    protected int mScrollY;
2272
2273    /**
2274     * The left padding in pixels, that is the distance in pixels between the
2275     * left edge of this view and the left edge of its content.
2276     * {@hide}
2277     */
2278    @ViewDebug.ExportedProperty(category = "padding")
2279    protected int mPaddingLeft;
2280    /**
2281     * The right padding in pixels, that is the distance in pixels between the
2282     * right edge of this view and the right edge of its content.
2283     * {@hide}
2284     */
2285    @ViewDebug.ExportedProperty(category = "padding")
2286    protected int mPaddingRight;
2287    /**
2288     * The top padding in pixels, that is the distance in pixels between the
2289     * top edge of this view and the top edge of its content.
2290     * {@hide}
2291     */
2292    @ViewDebug.ExportedProperty(category = "padding")
2293    protected int mPaddingTop;
2294    /**
2295     * The bottom padding in pixels, that is the distance in pixels between the
2296     * bottom edge of this view and the bottom edge of its content.
2297     * {@hide}
2298     */
2299    @ViewDebug.ExportedProperty(category = "padding")
2300    protected int mPaddingBottom;
2301
2302    /**
2303     * Briefly describes the view and is primarily used for accessibility support.
2304     */
2305    private CharSequence mContentDescription;
2306
2307    /**
2308     * Cache the paddingRight set by the user to append to the scrollbar's size.
2309     *
2310     * @hide
2311     */
2312    @ViewDebug.ExportedProperty(category = "padding")
2313    protected int mUserPaddingRight;
2314
2315    /**
2316     * Cache the paddingBottom set by the user to append to the scrollbar's size.
2317     *
2318     * @hide
2319     */
2320    @ViewDebug.ExportedProperty(category = "padding")
2321    protected int mUserPaddingBottom;
2322
2323    /**
2324     * Cache the paddingLeft set by the user to append to the scrollbar's size.
2325     *
2326     * @hide
2327     */
2328    @ViewDebug.ExportedProperty(category = "padding")
2329    protected int mUserPaddingLeft;
2330
2331    /**
2332     * Cache if the user padding is relative.
2333     *
2334     */
2335    @ViewDebug.ExportedProperty(category = "padding")
2336    boolean mUserPaddingRelative;
2337
2338    /**
2339     * Cache the paddingStart set by the user to append to the scrollbar's size.
2340     *
2341     */
2342    @ViewDebug.ExportedProperty(category = "padding")
2343    int mUserPaddingStart;
2344
2345    /**
2346     * Cache the paddingEnd set by the user to append to the scrollbar's size.
2347     *
2348     */
2349    @ViewDebug.ExportedProperty(category = "padding")
2350    int mUserPaddingEnd;
2351
2352    /**
2353     * @hide
2354     */
2355    int mOldWidthMeasureSpec = Integer.MIN_VALUE;
2356    /**
2357     * @hide
2358     */
2359    int mOldHeightMeasureSpec = Integer.MIN_VALUE;
2360
2361    private Drawable mBGDrawable;
2362
2363    private int mBackgroundResource;
2364    private boolean mBackgroundSizeChanged;
2365
2366    static class ListenerInfo {
2367        /**
2368         * Listener used to dispatch focus change events.
2369         * This field should be made private, so it is hidden from the SDK.
2370         * {@hide}
2371         */
2372        protected OnFocusChangeListener mOnFocusChangeListener;
2373
2374        /**
2375         * Listeners for layout change events.
2376         */
2377        private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners;
2378
2379        /**
2380         * Listeners for attach events.
2381         */
2382        private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners;
2383
2384        /**
2385         * Listener used to dispatch click events.
2386         * This field should be made private, so it is hidden from the SDK.
2387         * {@hide}
2388         */
2389        public OnClickListener mOnClickListener;
2390
2391        /**
2392         * Listener used to dispatch long click events.
2393         * This field should be made private, so it is hidden from the SDK.
2394         * {@hide}
2395         */
2396        protected OnLongClickListener mOnLongClickListener;
2397
2398        /**
2399         * Listener used to build the context menu.
2400         * This field should be made private, so it is hidden from the SDK.
2401         * {@hide}
2402         */
2403        protected OnCreateContextMenuListener mOnCreateContextMenuListener;
2404
2405        private OnKeyListener mOnKeyListener;
2406
2407        private OnTouchListener mOnTouchListener;
2408
2409        private OnHoverListener mOnHoverListener;
2410
2411        private OnGenericMotionListener mOnGenericMotionListener;
2412
2413        private OnDragListener mOnDragListener;
2414
2415        private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener;
2416    }
2417
2418    ListenerInfo mListenerInfo;
2419
2420    /**
2421     * The application environment this view lives in.
2422     * This field should be made private, so it is hidden from the SDK.
2423     * {@hide}
2424     */
2425    protected Context mContext;
2426
2427    private final Resources mResources;
2428
2429    private ScrollabilityCache mScrollCache;
2430
2431    private int[] mDrawableState = null;
2432
2433    /**
2434     * Set to true when drawing cache is enabled and cannot be created.
2435     *
2436     * @hide
2437     */
2438    public boolean mCachingFailed;
2439
2440    private Bitmap mDrawingCache;
2441    private Bitmap mUnscaledDrawingCache;
2442    private HardwareLayer mHardwareLayer;
2443    DisplayList mDisplayList;
2444
2445    /**
2446     * When this view has focus and the next focus is {@link #FOCUS_LEFT},
2447     * the user may specify which view to go to next.
2448     */
2449    private int mNextFocusLeftId = View.NO_ID;
2450
2451    /**
2452     * When this view has focus and the next focus is {@link #FOCUS_RIGHT},
2453     * the user may specify which view to go to next.
2454     */
2455    private int mNextFocusRightId = View.NO_ID;
2456
2457    /**
2458     * When this view has focus and the next focus is {@link #FOCUS_UP},
2459     * the user may specify which view to go to next.
2460     */
2461    private int mNextFocusUpId = View.NO_ID;
2462
2463    /**
2464     * When this view has focus and the next focus is {@link #FOCUS_DOWN},
2465     * the user may specify which view to go to next.
2466     */
2467    private int mNextFocusDownId = View.NO_ID;
2468
2469    /**
2470     * When this view has focus and the next focus is {@link #FOCUS_FORWARD},
2471     * the user may specify which view to go to next.
2472     */
2473    int mNextFocusForwardId = View.NO_ID;
2474
2475    private CheckForLongPress mPendingCheckForLongPress;
2476    private CheckForTap mPendingCheckForTap = null;
2477    private PerformClick mPerformClick;
2478    private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent;
2479
2480    private UnsetPressedState mUnsetPressedState;
2481
2482    /**
2483     * Whether the long press's action has been invoked.  The tap's action is invoked on the
2484     * up event while a long press is invoked as soon as the long press duration is reached, so
2485     * a long press could be performed before the tap is checked, in which case the tap's action
2486     * should not be invoked.
2487     */
2488    private boolean mHasPerformedLongPress;
2489
2490    /**
2491     * The minimum height of the view. We'll try our best to have the height
2492     * of this view to at least this amount.
2493     */
2494    @ViewDebug.ExportedProperty(category = "measurement")
2495    private int mMinHeight;
2496
2497    /**
2498     * The minimum width of the view. We'll try our best to have the width
2499     * of this view to at least this amount.
2500     */
2501    @ViewDebug.ExportedProperty(category = "measurement")
2502    private int mMinWidth;
2503
2504    /**
2505     * The delegate to handle touch events that are physically in this view
2506     * but should be handled by another view.
2507     */
2508    private TouchDelegate mTouchDelegate = null;
2509
2510    /**
2511     * Solid color to use as a background when creating the drawing cache. Enables
2512     * the cache to use 16 bit bitmaps instead of 32 bit.
2513     */
2514    private int mDrawingCacheBackgroundColor = 0;
2515
2516    /**
2517     * Special tree observer used when mAttachInfo is null.
2518     */
2519    private ViewTreeObserver mFloatingTreeObserver;
2520
2521    /**
2522     * Cache the touch slop from the context that created the view.
2523     */
2524    private int mTouchSlop;
2525
2526    /**
2527     * Object that handles automatic animation of view properties.
2528     */
2529    private ViewPropertyAnimator mAnimator = null;
2530
2531    /**
2532     * Flag indicating that a drag can cross window boundaries.  When
2533     * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called
2534     * with this flag set, all visible applications will be able to participate
2535     * in the drag operation and receive the dragged content.
2536     *
2537     * @hide
2538     */
2539    public static final int DRAG_FLAG_GLOBAL = 1;
2540
2541    /**
2542     * Vertical scroll factor cached by {@link #getVerticalScrollFactor}.
2543     */
2544    private float mVerticalScrollFactor;
2545
2546    /**
2547     * Position of the vertical scroll bar.
2548     */
2549    private int mVerticalScrollbarPosition;
2550
2551    /**
2552     * Position the scroll bar at the default position as determined by the system.
2553     */
2554    public static final int SCROLLBAR_POSITION_DEFAULT = 0;
2555
2556    /**
2557     * Position the scroll bar along the left edge.
2558     */
2559    public static final int SCROLLBAR_POSITION_LEFT = 1;
2560
2561    /**
2562     * Position the scroll bar along the right edge.
2563     */
2564    public static final int SCROLLBAR_POSITION_RIGHT = 2;
2565
2566    /**
2567     * Indicates that the view does not have a layer.
2568     *
2569     * @see #getLayerType()
2570     * @see #setLayerType(int, android.graphics.Paint)
2571     * @see #LAYER_TYPE_SOFTWARE
2572     * @see #LAYER_TYPE_HARDWARE
2573     */
2574    public static final int LAYER_TYPE_NONE = 0;
2575
2576    /**
2577     * <p>Indicates that the view has a software layer. A software layer is backed
2578     * by a bitmap and causes the view to be rendered using Android's software
2579     * rendering pipeline, even if hardware acceleration is enabled.</p>
2580     *
2581     * <p>Software layers have various usages:</p>
2582     * <p>When the application is not using hardware acceleration, a software layer
2583     * is useful to apply a specific color filter and/or blending mode and/or
2584     * translucency to a view and all its children.</p>
2585     * <p>When the application is using hardware acceleration, a software layer
2586     * is useful to render drawing primitives not supported by the hardware
2587     * accelerated pipeline. It can also be used to cache a complex view tree
2588     * into a texture and reduce the complexity of drawing operations. For instance,
2589     * when animating a complex view tree with a translation, a software layer can
2590     * be used to render the view tree only once.</p>
2591     * <p>Software layers should be avoided when the affected view tree updates
2592     * often. Every update will require to re-render the software layer, which can
2593     * potentially be slow (particularly when hardware acceleration is turned on
2594     * since the layer will have to be uploaded into a hardware texture after every
2595     * update.)</p>
2596     *
2597     * @see #getLayerType()
2598     * @see #setLayerType(int, android.graphics.Paint)
2599     * @see #LAYER_TYPE_NONE
2600     * @see #LAYER_TYPE_HARDWARE
2601     */
2602    public static final int LAYER_TYPE_SOFTWARE = 1;
2603
2604    /**
2605     * <p>Indicates that the view has a hardware layer. A hardware layer is backed
2606     * by a hardware specific texture (generally Frame Buffer Objects or FBO on
2607     * OpenGL hardware) and causes the view to be rendered using Android's hardware
2608     * rendering pipeline, but only if hardware acceleration is turned on for the
2609     * view hierarchy. When hardware acceleration is turned off, hardware layers
2610     * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
2611     *
2612     * <p>A hardware layer is useful to apply a specific color filter and/or
2613     * blending mode and/or translucency to a view and all its children.</p>
2614     * <p>A hardware layer can be used to cache a complex view tree into a
2615     * texture and reduce the complexity of drawing operations. For instance,
2616     * when animating a complex view tree with a translation, a hardware layer can
2617     * be used to render the view tree only once.</p>
2618     * <p>A hardware layer can also be used to increase the rendering quality when
2619     * rotation transformations are applied on a view. It can also be used to
2620     * prevent potential clipping issues when applying 3D transforms on a view.</p>
2621     *
2622     * @see #getLayerType()
2623     * @see #setLayerType(int, android.graphics.Paint)
2624     * @see #LAYER_TYPE_NONE
2625     * @see #LAYER_TYPE_SOFTWARE
2626     */
2627    public static final int LAYER_TYPE_HARDWARE = 2;
2628
2629    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
2630            @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"),
2631            @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"),
2632            @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE")
2633    })
2634    int mLayerType = LAYER_TYPE_NONE;
2635    Paint mLayerPaint;
2636    Rect mLocalDirtyRect;
2637
2638    /**
2639     * Set to true when the view is sending hover accessibility events because it
2640     * is the innermost hovered view.
2641     */
2642    private boolean mSendingHoverAccessibilityEvents;
2643
2644    /**
2645     * Delegate for injecting accessiblity functionality.
2646     */
2647    AccessibilityDelegate mAccessibilityDelegate;
2648
2649    /**
2650     * Text direction is inherited thru {@link ViewGroup}
2651     */
2652    public static final int TEXT_DIRECTION_INHERIT = 0;
2653
2654    /**
2655     * Text direction is using "first strong algorithm". The first strong directional character
2656     * determines the paragraph direction. If there is no strong directional character, the
2657     * paragraph direction is the view's resolved layout direction.
2658     *
2659     */
2660    public static final int TEXT_DIRECTION_FIRST_STRONG = 1;
2661
2662    /**
2663     * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains
2664     * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters.
2665     * If there are neither, the paragraph direction is the view's resolved layout direction.
2666     *
2667     */
2668    public static final int TEXT_DIRECTION_ANY_RTL = 2;
2669
2670    /**
2671     * Text direction is forced to LTR.
2672     *
2673     */
2674    public static final int TEXT_DIRECTION_LTR = 3;
2675
2676    /**
2677     * Text direction is forced to RTL.
2678     *
2679     */
2680    public static final int TEXT_DIRECTION_RTL = 4;
2681
2682    /**
2683     * Text direction is coming from the system Locale.
2684     *
2685     */
2686    public static final int TEXT_DIRECTION_LOCALE = 5;
2687
2688    /**
2689     * Default text direction is inherited
2690     *
2691     */
2692    protected static int DEFAULT_TEXT_DIRECTION = TEXT_DIRECTION_INHERIT;
2693
2694    /**
2695     * The text direction that has been defined by {@link #setTextDirection(int)}.
2696     *
2697     */
2698    @ViewDebug.ExportedProperty(category = "text", mapping = {
2699            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2700            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2701            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2702            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2703            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2704            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2705    })
2706    private int mTextDirection = DEFAULT_TEXT_DIRECTION;
2707
2708    /**
2709     * The resolved text direction.  This needs resolution if the value is
2710     * TEXT_DIRECTION_INHERIT.  The resolution matches mTextDirection if it is
2711     * not TEXT_DIRECTION_INHERIT, otherwise resolution proceeds up the parent
2712     * chain of the view.
2713     *
2714     */
2715    @ViewDebug.ExportedProperty(category = "text", mapping = {
2716            @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"),
2717            @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"),
2718            @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"),
2719            @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"),
2720            @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"),
2721            @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE")
2722    })
2723    private int mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
2724
2725    /**
2726     * Consistency verifier for debugging purposes.
2727     * @hide
2728     */
2729    protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier =
2730            InputEventConsistencyVerifier.isInstrumentationEnabled() ?
2731                    new InputEventConsistencyVerifier(this, 0) : null;
2732
2733    /**
2734     * Simple constructor to use when creating a view from code.
2735     *
2736     * @param context The Context the view is running in, through which it can
2737     *        access the current theme, resources, etc.
2738     */
2739    public View(Context context) {
2740        mContext = context;
2741        mResources = context != null ? context.getResources() : null;
2742        mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | LAYOUT_DIRECTION_INHERIT;
2743        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
2744        setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
2745        mUserPaddingStart = -1;
2746        mUserPaddingEnd = -1;
2747        mUserPaddingRelative = false;
2748    }
2749
2750    /**
2751     * Constructor that is called when inflating a view from XML. This is called
2752     * when a view is being constructed from an XML file, supplying attributes
2753     * that were specified in the XML file. This version uses a default style of
2754     * 0, so the only attribute values applied are those in the Context's Theme
2755     * and the given AttributeSet.
2756     *
2757     * <p>
2758     * The method onFinishInflate() will be called after all children have been
2759     * added.
2760     *
2761     * @param context The Context the view is running in, through which it can
2762     *        access the current theme, resources, etc.
2763     * @param attrs The attributes of the XML tag that is inflating the view.
2764     * @see #View(Context, AttributeSet, int)
2765     */
2766    public View(Context context, AttributeSet attrs) {
2767        this(context, attrs, 0);
2768    }
2769
2770    /**
2771     * Perform inflation from XML and apply a class-specific base style. This
2772     * constructor of View allows subclasses to use their own base style when
2773     * they are inflating. For example, a Button class's constructor would call
2774     * this version of the super class constructor and supply
2775     * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
2776     * the theme's button style to modify all of the base view attributes (in
2777     * particular its background) as well as the Button class's attributes.
2778     *
2779     * @param context The Context the view is running in, through which it can
2780     *        access the current theme, resources, etc.
2781     * @param attrs The attributes of the XML tag that is inflating the view.
2782     * @param defStyle The default style to apply to this view. If 0, no style
2783     *        will be applied (beyond what is included in the theme). This may
2784     *        either be an attribute resource, whose value will be retrieved
2785     *        from the current theme, or an explicit style resource.
2786     * @see #View(Context, AttributeSet)
2787     */
2788    public View(Context context, AttributeSet attrs, int defStyle) {
2789        this(context);
2790
2791        TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
2792                defStyle, 0);
2793
2794        Drawable background = null;
2795
2796        int leftPadding = -1;
2797        int topPadding = -1;
2798        int rightPadding = -1;
2799        int bottomPadding = -1;
2800        int startPadding = -1;
2801        int endPadding = -1;
2802
2803        int padding = -1;
2804
2805        int viewFlagValues = 0;
2806        int viewFlagMasks = 0;
2807
2808        boolean setScrollContainer = false;
2809
2810        int x = 0;
2811        int y = 0;
2812
2813        float tx = 0;
2814        float ty = 0;
2815        float rotation = 0;
2816        float rotationX = 0;
2817        float rotationY = 0;
2818        float sx = 1f;
2819        float sy = 1f;
2820        boolean transformSet = false;
2821
2822        int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
2823
2824        int overScrollMode = mOverScrollMode;
2825        final int N = a.getIndexCount();
2826        for (int i = 0; i < N; i++) {
2827            int attr = a.getIndex(i);
2828            switch (attr) {
2829                case com.android.internal.R.styleable.View_background:
2830                    background = a.getDrawable(attr);
2831                    break;
2832                case com.android.internal.R.styleable.View_padding:
2833                    padding = a.getDimensionPixelSize(attr, -1);
2834                    break;
2835                 case com.android.internal.R.styleable.View_paddingLeft:
2836                    leftPadding = a.getDimensionPixelSize(attr, -1);
2837                    break;
2838                case com.android.internal.R.styleable.View_paddingTop:
2839                    topPadding = a.getDimensionPixelSize(attr, -1);
2840                    break;
2841                case com.android.internal.R.styleable.View_paddingRight:
2842                    rightPadding = a.getDimensionPixelSize(attr, -1);
2843                    break;
2844                case com.android.internal.R.styleable.View_paddingBottom:
2845                    bottomPadding = a.getDimensionPixelSize(attr, -1);
2846                    break;
2847                case com.android.internal.R.styleable.View_paddingStart:
2848                    startPadding = a.getDimensionPixelSize(attr, -1);
2849                    break;
2850                case com.android.internal.R.styleable.View_paddingEnd:
2851                    endPadding = a.getDimensionPixelSize(attr, -1);
2852                    break;
2853                case com.android.internal.R.styleable.View_scrollX:
2854                    x = a.getDimensionPixelOffset(attr, 0);
2855                    break;
2856                case com.android.internal.R.styleable.View_scrollY:
2857                    y = a.getDimensionPixelOffset(attr, 0);
2858                    break;
2859                case com.android.internal.R.styleable.View_alpha:
2860                    setAlpha(a.getFloat(attr, 1f));
2861                    break;
2862                case com.android.internal.R.styleable.View_transformPivotX:
2863                    setPivotX(a.getDimensionPixelOffset(attr, 0));
2864                    break;
2865                case com.android.internal.R.styleable.View_transformPivotY:
2866                    setPivotY(a.getDimensionPixelOffset(attr, 0));
2867                    break;
2868                case com.android.internal.R.styleable.View_translationX:
2869                    tx = a.getDimensionPixelOffset(attr, 0);
2870                    transformSet = true;
2871                    break;
2872                case com.android.internal.R.styleable.View_translationY:
2873                    ty = a.getDimensionPixelOffset(attr, 0);
2874                    transformSet = true;
2875                    break;
2876                case com.android.internal.R.styleable.View_rotation:
2877                    rotation = a.getFloat(attr, 0);
2878                    transformSet = true;
2879                    break;
2880                case com.android.internal.R.styleable.View_rotationX:
2881                    rotationX = a.getFloat(attr, 0);
2882                    transformSet = true;
2883                    break;
2884                case com.android.internal.R.styleable.View_rotationY:
2885                    rotationY = a.getFloat(attr, 0);
2886                    transformSet = true;
2887                    break;
2888                case com.android.internal.R.styleable.View_scaleX:
2889                    sx = a.getFloat(attr, 1f);
2890                    transformSet = true;
2891                    break;
2892                case com.android.internal.R.styleable.View_scaleY:
2893                    sy = a.getFloat(attr, 1f);
2894                    transformSet = true;
2895                    break;
2896                case com.android.internal.R.styleable.View_id:
2897                    mID = a.getResourceId(attr, NO_ID);
2898                    break;
2899                case com.android.internal.R.styleable.View_tag:
2900                    mTag = a.getText(attr);
2901                    break;
2902                case com.android.internal.R.styleable.View_fitsSystemWindows:
2903                    if (a.getBoolean(attr, false)) {
2904                        viewFlagValues |= FITS_SYSTEM_WINDOWS;
2905                        viewFlagMasks |= FITS_SYSTEM_WINDOWS;
2906                    }
2907                    break;
2908                case com.android.internal.R.styleable.View_focusable:
2909                    if (a.getBoolean(attr, false)) {
2910                        viewFlagValues |= FOCUSABLE;
2911                        viewFlagMasks |= FOCUSABLE_MASK;
2912                    }
2913                    break;
2914                case com.android.internal.R.styleable.View_focusableInTouchMode:
2915                    if (a.getBoolean(attr, false)) {
2916                        viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
2917                        viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
2918                    }
2919                    break;
2920                case com.android.internal.R.styleable.View_clickable:
2921                    if (a.getBoolean(attr, false)) {
2922                        viewFlagValues |= CLICKABLE;
2923                        viewFlagMasks |= CLICKABLE;
2924                    }
2925                    break;
2926                case com.android.internal.R.styleable.View_longClickable:
2927                    if (a.getBoolean(attr, false)) {
2928                        viewFlagValues |= LONG_CLICKABLE;
2929                        viewFlagMasks |= LONG_CLICKABLE;
2930                    }
2931                    break;
2932                case com.android.internal.R.styleable.View_saveEnabled:
2933                    if (!a.getBoolean(attr, true)) {
2934                        viewFlagValues |= SAVE_DISABLED;
2935                        viewFlagMasks |= SAVE_DISABLED_MASK;
2936                    }
2937                    break;
2938                case com.android.internal.R.styleable.View_duplicateParentState:
2939                    if (a.getBoolean(attr, false)) {
2940                        viewFlagValues |= DUPLICATE_PARENT_STATE;
2941                        viewFlagMasks |= DUPLICATE_PARENT_STATE;
2942                    }
2943                    break;
2944                case com.android.internal.R.styleable.View_visibility:
2945                    final int visibility = a.getInt(attr, 0);
2946                    if (visibility != 0) {
2947                        viewFlagValues |= VISIBILITY_FLAGS[visibility];
2948                        viewFlagMasks |= VISIBILITY_MASK;
2949                    }
2950                    break;
2951                case com.android.internal.R.styleable.View_layoutDirection:
2952                    // Clear any HORIZONTAL_DIRECTION flag already set
2953                    viewFlagValues &= ~LAYOUT_DIRECTION_MASK;
2954                    // Set the HORIZONTAL_DIRECTION flags depending on the value of the attribute
2955                    final int layoutDirection = a.getInt(attr, -1);
2956                    if (layoutDirection != -1) {
2957                        viewFlagValues |= LAYOUT_DIRECTION_FLAGS[layoutDirection];
2958                    } else {
2959                        // Set to default (LAYOUT_DIRECTION_INHERIT)
2960                        viewFlagValues |= LAYOUT_DIRECTION_DEFAULT;
2961                    }
2962                    viewFlagMasks |= LAYOUT_DIRECTION_MASK;
2963                    break;
2964                case com.android.internal.R.styleable.View_drawingCacheQuality:
2965                    final int cacheQuality = a.getInt(attr, 0);
2966                    if (cacheQuality != 0) {
2967                        viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
2968                        viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
2969                    }
2970                    break;
2971                case com.android.internal.R.styleable.View_contentDescription:
2972                    mContentDescription = a.getString(attr);
2973                    break;
2974                case com.android.internal.R.styleable.View_soundEffectsEnabled:
2975                    if (!a.getBoolean(attr, true)) {
2976                        viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
2977                        viewFlagMasks |= SOUND_EFFECTS_ENABLED;
2978                    }
2979                    break;
2980                case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
2981                    if (!a.getBoolean(attr, true)) {
2982                        viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
2983                        viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
2984                    }
2985                    break;
2986                case R.styleable.View_scrollbars:
2987                    final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
2988                    if (scrollbars != SCROLLBARS_NONE) {
2989                        viewFlagValues |= scrollbars;
2990                        viewFlagMasks |= SCROLLBARS_MASK;
2991                        initializeScrollbars(a);
2992                    }
2993                    break;
2994                //noinspection deprecation
2995                case R.styleable.View_fadingEdge:
2996                    if (context.getApplicationInfo().targetSdkVersion >= ICE_CREAM_SANDWICH) {
2997                        // Ignore the attribute starting with ICS
2998                        break;
2999                    }
3000                    // With builds < ICS, fall through and apply fading edges
3001                case R.styleable.View_requiresFadingEdge:
3002                    final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
3003                    if (fadingEdge != FADING_EDGE_NONE) {
3004                        viewFlagValues |= fadingEdge;
3005                        viewFlagMasks |= FADING_EDGE_MASK;
3006                        initializeFadingEdge(a);
3007                    }
3008                    break;
3009                case R.styleable.View_scrollbarStyle:
3010                    scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
3011                    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3012                        viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
3013                        viewFlagMasks |= SCROLLBARS_STYLE_MASK;
3014                    }
3015                    break;
3016                case R.styleable.View_isScrollContainer:
3017                    setScrollContainer = true;
3018                    if (a.getBoolean(attr, false)) {
3019                        setScrollContainer(true);
3020                    }
3021                    break;
3022                case com.android.internal.R.styleable.View_keepScreenOn:
3023                    if (a.getBoolean(attr, false)) {
3024                        viewFlagValues |= KEEP_SCREEN_ON;
3025                        viewFlagMasks |= KEEP_SCREEN_ON;
3026                    }
3027                    break;
3028                case R.styleable.View_filterTouchesWhenObscured:
3029                    if (a.getBoolean(attr, false)) {
3030                        viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
3031                        viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
3032                    }
3033                    break;
3034                case R.styleable.View_nextFocusLeft:
3035                    mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
3036                    break;
3037                case R.styleable.View_nextFocusRight:
3038                    mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
3039                    break;
3040                case R.styleable.View_nextFocusUp:
3041                    mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
3042                    break;
3043                case R.styleable.View_nextFocusDown:
3044                    mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
3045                    break;
3046                case R.styleable.View_nextFocusForward:
3047                    mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
3048                    break;
3049                case R.styleable.View_minWidth:
3050                    mMinWidth = a.getDimensionPixelSize(attr, 0);
3051                    break;
3052                case R.styleable.View_minHeight:
3053                    mMinHeight = a.getDimensionPixelSize(attr, 0);
3054                    break;
3055                case R.styleable.View_onClick:
3056                    if (context.isRestricted()) {
3057                        throw new IllegalStateException("The android:onClick attribute cannot "
3058                                + "be used within a restricted context");
3059                    }
3060
3061                    final String handlerName = a.getString(attr);
3062                    if (handlerName != null) {
3063                        setOnClickListener(new OnClickListener() {
3064                            private Method mHandler;
3065
3066                            public void onClick(View v) {
3067                                if (mHandler == null) {
3068                                    try {
3069                                        mHandler = getContext().getClass().getMethod(handlerName,
3070                                                View.class);
3071                                    } catch (NoSuchMethodException e) {
3072                                        int id = getId();
3073                                        String idText = id == NO_ID ? "" : " with id '"
3074                                                + getContext().getResources().getResourceEntryName(
3075                                                    id) + "'";
3076                                        throw new IllegalStateException("Could not find a method " +
3077                                                handlerName + "(View) in the activity "
3078                                                + getContext().getClass() + " for onClick handler"
3079                                                + " on view " + View.this.getClass() + idText, e);
3080                                    }
3081                                }
3082
3083                                try {
3084                                    mHandler.invoke(getContext(), View.this);
3085                                } catch (IllegalAccessException e) {
3086                                    throw new IllegalStateException("Could not execute non "
3087                                            + "public method of the activity", e);
3088                                } catch (InvocationTargetException e) {
3089                                    throw new IllegalStateException("Could not execute "
3090                                            + "method of the activity", e);
3091                                }
3092                            }
3093                        });
3094                    }
3095                    break;
3096                case R.styleable.View_overScrollMode:
3097                    overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
3098                    break;
3099                case R.styleable.View_verticalScrollbarPosition:
3100                    mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
3101                    break;
3102                case R.styleable.View_layerType:
3103                    setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
3104                    break;
3105                case R.styleable.View_textDirection:
3106                    mTextDirection = a.getInt(attr, DEFAULT_TEXT_DIRECTION);
3107                    break;
3108            }
3109        }
3110
3111        a.recycle();
3112
3113        setOverScrollMode(overScrollMode);
3114
3115        if (background != null) {
3116            setBackgroundDrawable(background);
3117        }
3118
3119        // Cache user padding as we cannot fully resolve padding here (we dont have yet the resolved
3120        // layout direction). Those cached values will be used later during padding resolution.
3121        mUserPaddingStart = startPadding;
3122        mUserPaddingEnd = endPadding;
3123
3124        updateUserPaddingRelative();
3125
3126        if (padding >= 0) {
3127            leftPadding = padding;
3128            topPadding = padding;
3129            rightPadding = padding;
3130            bottomPadding = padding;
3131        }
3132
3133        // If the user specified the padding (either with android:padding or
3134        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
3135        // use the default padding or the padding from the background drawable
3136        // (stored at this point in mPadding*)
3137        setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
3138                topPadding >= 0 ? topPadding : mPaddingTop,
3139                rightPadding >= 0 ? rightPadding : mPaddingRight,
3140                bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
3141
3142        if (viewFlagMasks != 0) {
3143            setFlags(viewFlagValues, viewFlagMasks);
3144        }
3145
3146        // Needs to be called after mViewFlags is set
3147        if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
3148            recomputePadding();
3149        }
3150
3151        if (x != 0 || y != 0) {
3152            scrollTo(x, y);
3153        }
3154
3155        if (transformSet) {
3156            setTranslationX(tx);
3157            setTranslationY(ty);
3158            setRotation(rotation);
3159            setRotationX(rotationX);
3160            setRotationY(rotationY);
3161            setScaleX(sx);
3162            setScaleY(sy);
3163        }
3164
3165        if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
3166            setScrollContainer(true);
3167        }
3168
3169        computeOpaqueFlags();
3170    }
3171
3172    private void updateUserPaddingRelative() {
3173        mUserPaddingRelative = (mUserPaddingStart >= 0 || mUserPaddingEnd >= 0);
3174    }
3175
3176    /**
3177     * Non-public constructor for use in testing
3178     */
3179    View() {
3180        mResources = null;
3181    }
3182
3183    /**
3184     * <p>
3185     * Initializes the fading edges from a given set of styled attributes. This
3186     * method should be called by subclasses that need fading edges and when an
3187     * instance of these subclasses is created programmatically rather than
3188     * being inflated from XML. This method is automatically called when the XML
3189     * is inflated.
3190     * </p>
3191     *
3192     * @param a the styled attributes set to initialize the fading edges from
3193     */
3194    protected void initializeFadingEdge(TypedArray a) {
3195        initScrollCache();
3196
3197        mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
3198                R.styleable.View_fadingEdgeLength,
3199                ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
3200    }
3201
3202    /**
3203     * Returns the size of the vertical faded edges used to indicate that more
3204     * content in this view is visible.
3205     *
3206     * @return The size in pixels of the vertical faded edge or 0 if vertical
3207     *         faded edges are not enabled for this view.
3208     * @attr ref android.R.styleable#View_fadingEdgeLength
3209     */
3210    public int getVerticalFadingEdgeLength() {
3211        if (isVerticalFadingEdgeEnabled()) {
3212            ScrollabilityCache cache = mScrollCache;
3213            if (cache != null) {
3214                return cache.fadingEdgeLength;
3215            }
3216        }
3217        return 0;
3218    }
3219
3220    /**
3221     * Set the size of the faded edge used to indicate that more content in this
3222     * view is available.  Will not change whether the fading edge is enabled; use
3223     * {@link #setVerticalFadingEdgeEnabled(boolean)} or
3224     * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge
3225     * for the vertical or horizontal fading edges.
3226     *
3227     * @param length The size in pixels of the faded edge used to indicate that more
3228     *        content in this view is visible.
3229     */
3230    public void setFadingEdgeLength(int length) {
3231        initScrollCache();
3232        mScrollCache.fadingEdgeLength = length;
3233    }
3234
3235    /**
3236     * Returns the size of the horizontal faded edges used to indicate that more
3237     * content in this view is visible.
3238     *
3239     * @return The size in pixels of the horizontal faded edge or 0 if horizontal
3240     *         faded edges are not enabled for this view.
3241     * @attr ref android.R.styleable#View_fadingEdgeLength
3242     */
3243    public int getHorizontalFadingEdgeLength() {
3244        if (isHorizontalFadingEdgeEnabled()) {
3245            ScrollabilityCache cache = mScrollCache;
3246            if (cache != null) {
3247                return cache.fadingEdgeLength;
3248            }
3249        }
3250        return 0;
3251    }
3252
3253    /**
3254     * Returns the width of the vertical scrollbar.
3255     *
3256     * @return The width in pixels of the vertical scrollbar or 0 if there
3257     *         is no vertical scrollbar.
3258     */
3259    public int getVerticalScrollbarWidth() {
3260        ScrollabilityCache cache = mScrollCache;
3261        if (cache != null) {
3262            ScrollBarDrawable scrollBar = cache.scrollBar;
3263            if (scrollBar != null) {
3264                int size = scrollBar.getSize(true);
3265                if (size <= 0) {
3266                    size = cache.scrollBarSize;
3267                }
3268                return size;
3269            }
3270            return 0;
3271        }
3272        return 0;
3273    }
3274
3275    /**
3276     * Returns the height of the horizontal scrollbar.
3277     *
3278     * @return The height in pixels of the horizontal scrollbar or 0 if
3279     *         there is no horizontal scrollbar.
3280     */
3281    protected int getHorizontalScrollbarHeight() {
3282        ScrollabilityCache cache = mScrollCache;
3283        if (cache != null) {
3284            ScrollBarDrawable scrollBar = cache.scrollBar;
3285            if (scrollBar != null) {
3286                int size = scrollBar.getSize(false);
3287                if (size <= 0) {
3288                    size = cache.scrollBarSize;
3289                }
3290                return size;
3291            }
3292            return 0;
3293        }
3294        return 0;
3295    }
3296
3297    /**
3298     * <p>
3299     * Initializes the scrollbars from a given set of styled attributes. This
3300     * method should be called by subclasses that need scrollbars and when an
3301     * instance of these subclasses is created programmatically rather than
3302     * being inflated from XML. This method is automatically called when the XML
3303     * is inflated.
3304     * </p>
3305     *
3306     * @param a the styled attributes set to initialize the scrollbars from
3307     */
3308    protected void initializeScrollbars(TypedArray a) {
3309        initScrollCache();
3310
3311        final ScrollabilityCache scrollabilityCache = mScrollCache;
3312
3313        if (scrollabilityCache.scrollBar == null) {
3314            scrollabilityCache.scrollBar = new ScrollBarDrawable();
3315        }
3316
3317        final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true);
3318
3319        if (!fadeScrollbars) {
3320            scrollabilityCache.state = ScrollabilityCache.ON;
3321        }
3322        scrollabilityCache.fadeScrollBars = fadeScrollbars;
3323
3324
3325        scrollabilityCache.scrollBarFadeDuration = a.getInt(
3326                R.styleable.View_scrollbarFadeDuration, ViewConfiguration
3327                        .getScrollBarFadeDuration());
3328        scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt(
3329                R.styleable.View_scrollbarDefaultDelayBeforeFade,
3330                ViewConfiguration.getScrollDefaultDelay());
3331
3332
3333        scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
3334                com.android.internal.R.styleable.View_scrollbarSize,
3335                ViewConfiguration.get(mContext).getScaledScrollBarSize());
3336
3337        Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
3338        scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
3339
3340        Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
3341        if (thumb != null) {
3342            scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
3343        }
3344
3345        boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
3346                false);
3347        if (alwaysDraw) {
3348            scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
3349        }
3350
3351        track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
3352        scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
3353
3354        thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
3355        if (thumb != null) {
3356            scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
3357        }
3358
3359        alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
3360                false);
3361        if (alwaysDraw) {
3362            scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
3363        }
3364
3365        // Re-apply user/background padding so that scrollbar(s) get added
3366        resolvePadding();
3367    }
3368
3369    /**
3370     * <p>
3371     * Initalizes the scrollability cache if necessary.
3372     * </p>
3373     */
3374    private void initScrollCache() {
3375        if (mScrollCache == null) {
3376            mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this);
3377        }
3378    }
3379
3380    /**
3381     * Set the position of the vertical scroll bar. Should be one of
3382     * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or
3383     * {@link #SCROLLBAR_POSITION_RIGHT}.
3384     *
3385     * @param position Where the vertical scroll bar should be positioned.
3386     */
3387    public void setVerticalScrollbarPosition(int position) {
3388        if (mVerticalScrollbarPosition != position) {
3389            mVerticalScrollbarPosition = position;
3390            computeOpaqueFlags();
3391            resolvePadding();
3392        }
3393    }
3394
3395    /**
3396     * @return The position where the vertical scroll bar will show, if applicable.
3397     * @see #setVerticalScrollbarPosition(int)
3398     */
3399    public int getVerticalScrollbarPosition() {
3400        return mVerticalScrollbarPosition;
3401    }
3402
3403    ListenerInfo getListenerInfo() {
3404        if (mListenerInfo != null) {
3405            return mListenerInfo;
3406        }
3407        mListenerInfo = new ListenerInfo();
3408        return mListenerInfo;
3409    }
3410
3411    /**
3412     * Register a callback to be invoked when focus of this view changed.
3413     *
3414     * @param l The callback that will run.
3415     */
3416    public void setOnFocusChangeListener(OnFocusChangeListener l) {
3417        getListenerInfo().mOnFocusChangeListener = l;
3418    }
3419
3420    /**
3421     * Add a listener that will be called when the bounds of the view change due to
3422     * layout processing.
3423     *
3424     * @param listener The listener that will be called when layout bounds change.
3425     */
3426    public void addOnLayoutChangeListener(OnLayoutChangeListener listener) {
3427        ListenerInfo li = getListenerInfo();
3428        if (li.mOnLayoutChangeListeners == null) {
3429            li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>();
3430        }
3431        if (!li.mOnLayoutChangeListeners.contains(listener)) {
3432            li.mOnLayoutChangeListeners.add(listener);
3433        }
3434    }
3435
3436    /**
3437     * Remove a listener for layout changes.
3438     *
3439     * @param listener The listener for layout bounds change.
3440     */
3441    public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) {
3442        ListenerInfo li = mListenerInfo;
3443        if (li == null || li.mOnLayoutChangeListeners == null) {
3444            return;
3445        }
3446        li.mOnLayoutChangeListeners.remove(listener);
3447    }
3448
3449    /**
3450     * Add a listener for attach state changes.
3451     *
3452     * This listener will be called whenever this view is attached or detached
3453     * from a window. Remove the listener using
3454     * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}.
3455     *
3456     * @param listener Listener to attach
3457     * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener)
3458     */
3459    public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3460        ListenerInfo li = getListenerInfo();
3461        if (li.mOnAttachStateChangeListeners == null) {
3462            li.mOnAttachStateChangeListeners
3463                    = new CopyOnWriteArrayList<OnAttachStateChangeListener>();
3464        }
3465        li.mOnAttachStateChangeListeners.add(listener);
3466    }
3467
3468    /**
3469     * Remove a listener for attach state changes. The listener will receive no further
3470     * notification of window attach/detach events.
3471     *
3472     * @param listener Listener to remove
3473     * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener)
3474     */
3475    public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) {
3476        ListenerInfo li = mListenerInfo;
3477        if (li == null || li.mOnAttachStateChangeListeners == null) {
3478            return;
3479        }
3480        li.mOnAttachStateChangeListeners.remove(listener);
3481    }
3482
3483    /**
3484     * Returns the focus-change callback registered for this view.
3485     *
3486     * @return The callback, or null if one is not registered.
3487     */
3488    public OnFocusChangeListener getOnFocusChangeListener() {
3489        ListenerInfo li = mListenerInfo;
3490        return li != null ? li.mOnFocusChangeListener : null;
3491    }
3492
3493    /**
3494     * Register a callback to be invoked when this view is clicked. If this view is not
3495     * clickable, it becomes clickable.
3496     *
3497     * @param l The callback that will run
3498     *
3499     * @see #setClickable(boolean)
3500     */
3501    public void setOnClickListener(OnClickListener l) {
3502        if (!isClickable()) {
3503            setClickable(true);
3504        }
3505        getListenerInfo().mOnClickListener = l;
3506    }
3507
3508    /**
3509     * Return whether this view has an attached OnClickListener.  Returns
3510     * true if there is a listener, false if there is none.
3511     */
3512    public boolean hasOnClickListeners() {
3513        ListenerInfo li = mListenerInfo;
3514        return (li != null && li.mOnClickListener != null);
3515    }
3516
3517    /**
3518     * Register a callback to be invoked when this view is clicked and held. If this view is not
3519     * long clickable, it becomes long clickable.
3520     *
3521     * @param l The callback that will run
3522     *
3523     * @see #setLongClickable(boolean)
3524     */
3525    public void setOnLongClickListener(OnLongClickListener l) {
3526        if (!isLongClickable()) {
3527            setLongClickable(true);
3528        }
3529        getListenerInfo().mOnLongClickListener = l;
3530    }
3531
3532    /**
3533     * Register a callback to be invoked when the context menu for this view is
3534     * being built. If this view is not long clickable, it becomes long clickable.
3535     *
3536     * @param l The callback that will run
3537     *
3538     */
3539    public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
3540        if (!isLongClickable()) {
3541            setLongClickable(true);
3542        }
3543        getListenerInfo().mOnCreateContextMenuListener = l;
3544    }
3545
3546    /**
3547     * Call this view's OnClickListener, if it is defined.  Performs all normal
3548     * actions associated with clicking: reporting accessibility event, playing
3549     * a sound, etc.
3550     *
3551     * @return True there was an assigned OnClickListener that was called, false
3552     *         otherwise is returned.
3553     */
3554    public boolean performClick() {
3555        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
3556
3557        ListenerInfo li = mListenerInfo;
3558        if (li != null && li.mOnClickListener != null) {
3559            playSoundEffect(SoundEffectConstants.CLICK);
3560            li.mOnClickListener.onClick(this);
3561            return true;
3562        }
3563
3564        return false;
3565    }
3566
3567    /**
3568     * Directly call any attached OnClickListener.  Unlike {@link #performClick()},
3569     * this only calls the listener, and does not do any associated clicking
3570     * actions like reporting an accessibility event.
3571     *
3572     * @return True there was an assigned OnClickListener that was called, false
3573     *         otherwise is returned.
3574     */
3575    public boolean callOnClick() {
3576        ListenerInfo li = mListenerInfo;
3577        if (li != null && li.mOnClickListener != null) {
3578            li.mOnClickListener.onClick(this);
3579            return true;
3580        }
3581        return false;
3582    }
3583
3584    /**
3585     * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the
3586     * OnLongClickListener did not consume the event.
3587     *
3588     * @return True if one of the above receivers consumed the event, false otherwise.
3589     */
3590    public boolean performLongClick() {
3591        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
3592
3593        boolean handled = false;
3594        ListenerInfo li = mListenerInfo;
3595        if (li != null && li.mOnLongClickListener != null) {
3596            handled = li.mOnLongClickListener.onLongClick(View.this);
3597        }
3598        if (!handled) {
3599            handled = showContextMenu();
3600        }
3601        if (handled) {
3602            performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
3603        }
3604        return handled;
3605    }
3606
3607    /**
3608     * Performs button-related actions during a touch down event.
3609     *
3610     * @param event The event.
3611     * @return True if the down was consumed.
3612     *
3613     * @hide
3614     */
3615    protected boolean performButtonActionOnTouchDown(MotionEvent event) {
3616        if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) {
3617            if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) {
3618                return true;
3619            }
3620        }
3621        return false;
3622    }
3623
3624    /**
3625     * Bring up the context menu for this view.
3626     *
3627     * @return Whether a context menu was displayed.
3628     */
3629    public boolean showContextMenu() {
3630        return getParent().showContextMenuForChild(this);
3631    }
3632
3633    /**
3634     * Bring up the context menu for this view, referring to the item under the specified point.
3635     *
3636     * @param x The referenced x coordinate.
3637     * @param y The referenced y coordinate.
3638     * @param metaState The keyboard modifiers that were pressed.
3639     * @return Whether a context menu was displayed.
3640     *
3641     * @hide
3642     */
3643    public boolean showContextMenu(float x, float y, int metaState) {
3644        return showContextMenu();
3645    }
3646
3647    /**
3648     * Start an action mode.
3649     *
3650     * @param callback Callback that will control the lifecycle of the action mode
3651     * @return The new action mode if it is started, null otherwise
3652     *
3653     * @see ActionMode
3654     */
3655    public ActionMode startActionMode(ActionMode.Callback callback) {
3656        ViewParent parent = getParent();
3657        if (parent == null) return null;
3658        return parent.startActionModeForChild(this, callback);
3659    }
3660
3661    /**
3662     * Register a callback to be invoked when a key is pressed in this view.
3663     * @param l the key listener to attach to this view
3664     */
3665    public void setOnKeyListener(OnKeyListener l) {
3666        getListenerInfo().mOnKeyListener = l;
3667    }
3668
3669    /**
3670     * Register a callback to be invoked when a touch event is sent to this view.
3671     * @param l the touch listener to attach to this view
3672     */
3673    public void setOnTouchListener(OnTouchListener l) {
3674        getListenerInfo().mOnTouchListener = l;
3675    }
3676
3677    /**
3678     * Register a callback to be invoked when a generic motion event is sent to this view.
3679     * @param l the generic motion listener to attach to this view
3680     */
3681    public void setOnGenericMotionListener(OnGenericMotionListener l) {
3682        getListenerInfo().mOnGenericMotionListener = l;
3683    }
3684
3685    /**
3686     * Register a callback to be invoked when a hover event is sent to this view.
3687     * @param l the hover listener to attach to this view
3688     */
3689    public void setOnHoverListener(OnHoverListener l) {
3690        getListenerInfo().mOnHoverListener = l;
3691    }
3692
3693    /**
3694     * Register a drag event listener callback object for this View. The parameter is
3695     * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a
3696     * View, the system calls the
3697     * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method.
3698     * @param l An implementation of {@link android.view.View.OnDragListener}.
3699     */
3700    public void setOnDragListener(OnDragListener l) {
3701        getListenerInfo().mOnDragListener = l;
3702    }
3703
3704    /**
3705     * Give this view focus. This will cause
3706     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called.
3707     *
3708     * Note: this does not check whether this {@link View} should get focus, it just
3709     * gives it focus no matter what.  It should only be called internally by framework
3710     * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
3711     *
3712     * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
3713     *        {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which
3714     *        focus moved when requestFocus() is called. It may not always
3715     *        apply, in which case use the default View.FOCUS_DOWN.
3716     * @param previouslyFocusedRect The rectangle of the view that had focus
3717     *        prior in this View's coordinate system.
3718     */
3719    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
3720        if (DBG) {
3721            System.out.println(this + " requestFocus()");
3722        }
3723
3724        if ((mPrivateFlags & FOCUSED) == 0) {
3725            mPrivateFlags |= FOCUSED;
3726
3727            if (mParent != null) {
3728                mParent.requestChildFocus(this, this);
3729            }
3730
3731            onFocusChanged(true, direction, previouslyFocusedRect);
3732            refreshDrawableState();
3733        }
3734    }
3735
3736    /**
3737     * Request that a rectangle of this view be visible on the screen,
3738     * scrolling if necessary just enough.
3739     *
3740     * <p>A View should call this if it maintains some notion of which part
3741     * of its content is interesting.  For example, a text editing view
3742     * should call this when its cursor moves.
3743     *
3744     * @param rectangle The rectangle.
3745     * @return Whether any parent scrolled.
3746     */
3747    public boolean requestRectangleOnScreen(Rect rectangle) {
3748        return requestRectangleOnScreen(rectangle, false);
3749    }
3750
3751    /**
3752     * Request that a rectangle of this view be visible on the screen,
3753     * scrolling if necessary just enough.
3754     *
3755     * <p>A View should call this if it maintains some notion of which part
3756     * of its content is interesting.  For example, a text editing view
3757     * should call this when its cursor moves.
3758     *
3759     * <p>When <code>immediate</code> is set to true, scrolling will not be
3760     * animated.
3761     *
3762     * @param rectangle The rectangle.
3763     * @param immediate True to forbid animated scrolling, false otherwise
3764     * @return Whether any parent scrolled.
3765     */
3766    public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
3767        View child = this;
3768        ViewParent parent = mParent;
3769        boolean scrolled = false;
3770        while (parent != null) {
3771            scrolled |= parent.requestChildRectangleOnScreen(child,
3772                    rectangle, immediate);
3773
3774            // offset rect so next call has the rectangle in the
3775            // coordinate system of its direct child.
3776            rectangle.offset(child.getLeft(), child.getTop());
3777            rectangle.offset(-child.getScrollX(), -child.getScrollY());
3778
3779            if (!(parent instanceof View)) {
3780                break;
3781            }
3782
3783            child = (View) parent;
3784            parent = child.getParent();
3785        }
3786        return scrolled;
3787    }
3788
3789    /**
3790     * Called when this view wants to give up focus. If focus is cleared
3791     * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called.
3792     * <p>
3793     * <strong>Note:</strong> When a View clears focus the framework is trying
3794     * to give focus to the first focusable View from the top. Hence, if this
3795     * View is the first from the top that can take focus, then its focus will
3796     * not be cleared nor will the focus change callback be invoked.
3797     * </p>
3798     */
3799    public void clearFocus() {
3800        if (DBG) {
3801            System.out.println(this + " clearFocus()");
3802        }
3803
3804        if ((mPrivateFlags & FOCUSED) != 0) {
3805            mPrivateFlags &= ~FOCUSED;
3806
3807            if (mParent != null) {
3808                mParent.clearChildFocus(this);
3809            }
3810
3811            onFocusChanged(false, 0, null);
3812            refreshDrawableState();
3813        }
3814    }
3815
3816    /**
3817     * Called to clear the focus of a view that is about to be removed.
3818     * Doesn't call clearChildFocus, which prevents this view from taking
3819     * focus again before it has been removed from the parent
3820     */
3821    void clearFocusForRemoval() {
3822        if ((mPrivateFlags & FOCUSED) != 0) {
3823            mPrivateFlags &= ~FOCUSED;
3824
3825            onFocusChanged(false, 0, null);
3826            refreshDrawableState();
3827
3828            // The view cleared focus and invoked the callbacks, so  now is the
3829            // time to give focus to the the first focusable from the top to
3830            // ensure that the gain focus is announced after clear focus.
3831            getRootView().requestFocus(FOCUS_FORWARD);
3832        }
3833    }
3834
3835    /**
3836     * Called internally by the view system when a new view is getting focus.
3837     * This is what clears the old focus.
3838     */
3839    void unFocus() {
3840        if (DBG) {
3841            System.out.println(this + " unFocus()");
3842        }
3843
3844        if ((mPrivateFlags & FOCUSED) != 0) {
3845            mPrivateFlags &= ~FOCUSED;
3846
3847            onFocusChanged(false, 0, null);
3848            refreshDrawableState();
3849        }
3850    }
3851
3852    /**
3853     * Returns true if this view has focus iteself, or is the ancestor of the
3854     * view that has focus.
3855     *
3856     * @return True if this view has or contains focus, false otherwise.
3857     */
3858    @ViewDebug.ExportedProperty(category = "focus")
3859    public boolean hasFocus() {
3860        return (mPrivateFlags & FOCUSED) != 0;
3861    }
3862
3863    /**
3864     * Returns true if this view is focusable or if it contains a reachable View
3865     * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
3866     * is a View whose parents do not block descendants focus.
3867     *
3868     * Only {@link #VISIBLE} views are considered focusable.
3869     *
3870     * @return True if the view is focusable or if the view contains a focusable
3871     *         View, false otherwise.
3872     *
3873     * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
3874     */
3875    public boolean hasFocusable() {
3876        return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
3877    }
3878
3879    /**
3880     * Called by the view system when the focus state of this view changes.
3881     * When the focus change event is caused by directional navigation, direction
3882     * and previouslyFocusedRect provide insight into where the focus is coming from.
3883     * When overriding, be sure to call up through to the super class so that
3884     * the standard focus handling will occur.
3885     *
3886     * @param gainFocus True if the View has focus; false otherwise.
3887     * @param direction The direction focus has moved when requestFocus()
3888     *                  is called to give this view focus. Values are
3889     *                  {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT},
3890     *                  {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}.
3891     *                  It may not always apply, in which case use the default.
3892     * @param previouslyFocusedRect The rectangle, in this view's coordinate
3893     *        system, of the previously focused view.  If applicable, this will be
3894     *        passed in as finer grained information about where the focus is coming
3895     *        from (in addition to direction).  Will be <code>null</code> otherwise.
3896     */
3897    protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
3898        if (gainFocus) {
3899            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
3900        }
3901
3902        InputMethodManager imm = InputMethodManager.peekInstance();
3903        if (!gainFocus) {
3904            if (isPressed()) {
3905                setPressed(false);
3906            }
3907            if (imm != null && mAttachInfo != null
3908                    && mAttachInfo.mHasWindowFocus) {
3909                imm.focusOut(this);
3910            }
3911            onFocusLost();
3912        } else if (imm != null && mAttachInfo != null
3913                && mAttachInfo.mHasWindowFocus) {
3914            imm.focusIn(this);
3915        }
3916
3917        invalidate(true);
3918        ListenerInfo li = mListenerInfo;
3919        if (li != null && li.mOnFocusChangeListener != null) {
3920            li.mOnFocusChangeListener.onFocusChange(this, gainFocus);
3921        }
3922
3923        if (mAttachInfo != null) {
3924            mAttachInfo.mKeyDispatchState.reset(this);
3925        }
3926    }
3927
3928    /**
3929     * Sends an accessibility event of the given type. If accessiiblity is
3930     * not enabled this method has no effect. The default implementation calls
3931     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first
3932     * to populate information about the event source (this View), then calls
3933     * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to
3934     * populate the text content of the event source including its descendants,
3935     * and last calls
3936     * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)}
3937     * on its parent to resuest sending of the event to interested parties.
3938     * <p>
3939     * If an {@link AccessibilityDelegate} has been specified via calling
3940     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3941     * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is
3942     * responsible for handling this call.
3943     * </p>
3944     *
3945     * @param eventType The type of the event to send, as defined by several types from
3946     * {@link android.view.accessibility.AccessibilityEvent}, such as
3947     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or
3948     * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}.
3949     *
3950     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
3951     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
3952     * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)
3953     * @see AccessibilityDelegate
3954     */
3955    public void sendAccessibilityEvent(int eventType) {
3956        if (mAccessibilityDelegate != null) {
3957            mAccessibilityDelegate.sendAccessibilityEvent(this, eventType);
3958        } else {
3959            sendAccessibilityEventInternal(eventType);
3960        }
3961    }
3962
3963    /**
3964     * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT}
3965     * {@link AccessibilityEvent} to make an announcement which is related to some
3966     * sort of a context change for which none of the events representing UI transitions
3967     * is a good fit. For example, announcing a new page in a book. If accessibility
3968     * is not enabled this method does nothing.
3969     *
3970     * @param text The announcement text.
3971     */
3972    public void announceForAccessibility(CharSequence text) {
3973        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3974            AccessibilityEvent event = AccessibilityEvent.obtain(
3975                    AccessibilityEvent.TYPE_ANNOUNCEMENT);
3976            event.getText().add(text);
3977            sendAccessibilityEventUnchecked(event);
3978        }
3979    }
3980
3981    /**
3982     * @see #sendAccessibilityEvent(int)
3983     *
3984     * Note: Called from the default {@link AccessibilityDelegate}.
3985     */
3986    void sendAccessibilityEventInternal(int eventType) {
3987        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
3988            sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
3989        }
3990    }
3991
3992    /**
3993     * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but
3994     * takes as an argument an empty {@link AccessibilityEvent} and does not
3995     * perform a check whether accessibility is enabled.
3996     * <p>
3997     * If an {@link AccessibilityDelegate} has been specified via calling
3998     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
3999     * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)}
4000     * is responsible for handling this call.
4001     * </p>
4002     *
4003     * @param event The event to send.
4004     *
4005     * @see #sendAccessibilityEvent(int)
4006     */
4007    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
4008        if (mAccessibilityDelegate != null) {
4009           mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event);
4010        } else {
4011            sendAccessibilityEventUncheckedInternal(event);
4012        }
4013    }
4014
4015    /**
4016     * @see #sendAccessibilityEventUnchecked(AccessibilityEvent)
4017     *
4018     * Note: Called from the default {@link AccessibilityDelegate}.
4019     */
4020    void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) {
4021        if (!isShown()) {
4022            return;
4023        }
4024        onInitializeAccessibilityEvent(event);
4025        // Only a subset of accessibility events populates text content.
4026        if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) {
4027            dispatchPopulateAccessibilityEvent(event);
4028        }
4029        // In the beginning we called #isShown(), so we know that getParent() is not null.
4030        getParent().requestSendAccessibilityEvent(this, event);
4031    }
4032
4033    /**
4034     * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then
4035     * to its children for adding their text content to the event. Note that the
4036     * event text is populated in a separate dispatch path since we add to the
4037     * event not only the text of the source but also the text of all its descendants.
4038     * A typical implementation will call
4039     * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view
4040     * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4041     * on each child. Override this method if custom population of the event text
4042     * content is required.
4043     * <p>
4044     * If an {@link AccessibilityDelegate} has been specified via calling
4045     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4046     * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)}
4047     * is responsible for handling this call.
4048     * </p>
4049     * <p>
4050     * <em>Note:</em> Accessibility events of certain types are not dispatched for
4051     * populating the event text via this method. For details refer to {@link AccessibilityEvent}.
4052     * </p>
4053     *
4054     * @param event The event.
4055     *
4056     * @return True if the event population was completed.
4057     */
4058    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
4059        if (mAccessibilityDelegate != null) {
4060            return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event);
4061        } else {
4062            return dispatchPopulateAccessibilityEventInternal(event);
4063        }
4064    }
4065
4066    /**
4067     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4068     *
4069     * Note: Called from the default {@link AccessibilityDelegate}.
4070     */
4071    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4072        onPopulateAccessibilityEvent(event);
4073        return false;
4074    }
4075
4076    /**
4077     * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)}
4078     * giving a chance to this View to populate the accessibility event with its
4079     * text content. While this method is free to modify event
4080     * attributes other than text content, doing so should normally be performed in
4081     * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}.
4082     * <p>
4083     * Example: Adding formatted date string to an accessibility event in addition
4084     *          to the text added by the super implementation:
4085     * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4086     *     super.onPopulateAccessibilityEvent(event);
4087     *     final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY;
4088     *     String selectedDateUtterance = DateUtils.formatDateTime(mContext,
4089     *         mCurrentDate.getTimeInMillis(), flags);
4090     *     event.getText().add(selectedDateUtterance);
4091     * }</pre>
4092     * <p>
4093     * If an {@link AccessibilityDelegate} has been specified via calling
4094     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4095     * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)}
4096     * is responsible for handling this call.
4097     * </p>
4098     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4099     * information to the event, in case the default implementation has basic information to add.
4100     * </p>
4101     *
4102     * @param event The accessibility event which to populate.
4103     *
4104     * @see #sendAccessibilityEvent(int)
4105     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4106     */
4107    public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
4108        if (mAccessibilityDelegate != null) {
4109            mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event);
4110        } else {
4111            onPopulateAccessibilityEventInternal(event);
4112        }
4113    }
4114
4115    /**
4116     * @see #onPopulateAccessibilityEvent(AccessibilityEvent)
4117     *
4118     * Note: Called from the default {@link AccessibilityDelegate}.
4119     */
4120    void onPopulateAccessibilityEventInternal(AccessibilityEvent event) {
4121
4122    }
4123
4124    /**
4125     * Initializes an {@link AccessibilityEvent} with information about
4126     * this View which is the event source. In other words, the source of
4127     * an accessibility event is the view whose state change triggered firing
4128     * the event.
4129     * <p>
4130     * Example: Setting the password property of an event in addition
4131     *          to properties set by the super implementation:
4132     * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4133     *     super.onInitializeAccessibilityEvent(event);
4134     *     event.setPassword(true);
4135     * }</pre>
4136     * <p>
4137     * If an {@link AccessibilityDelegate} has been specified via calling
4138     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4139     * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)}
4140     * is responsible for handling this call.
4141     * </p>
4142     * <p class="note"><strong>Note:</strong> Always call the super implementation before adding
4143     * information to the event, in case the default implementation has basic information to add.
4144     * </p>
4145     * @param event The event to initialize.
4146     *
4147     * @see #sendAccessibilityEvent(int)
4148     * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent)
4149     */
4150    public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
4151        if (mAccessibilityDelegate != null) {
4152            mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event);
4153        } else {
4154            onInitializeAccessibilityEventInternal(event);
4155        }
4156    }
4157
4158    /**
4159     * @see #onInitializeAccessibilityEvent(AccessibilityEvent)
4160     *
4161     * Note: Called from the default {@link AccessibilityDelegate}.
4162     */
4163    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
4164        event.setSource(this);
4165        event.setClassName(View.class.getName());
4166        event.setPackageName(getContext().getPackageName());
4167        event.setEnabled(isEnabled());
4168        event.setContentDescription(mContentDescription);
4169
4170        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
4171            ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
4172            getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD,
4173                    FOCUSABLES_ALL);
4174            event.setItemCount(focusablesTempList.size());
4175            event.setCurrentItemIndex(focusablesTempList.indexOf(this));
4176            focusablesTempList.clear();
4177        }
4178    }
4179
4180    /**
4181     * Returns an {@link AccessibilityNodeInfo} representing this view from the
4182     * point of view of an {@link android.accessibilityservice.AccessibilityService}.
4183     * This method is responsible for obtaining an accessibility node info from a
4184     * pool of reusable instances and calling
4185     * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to
4186     * initialize the former.
4187     * <p>
4188     * Note: The client is responsible for recycling the obtained instance by calling
4189     *       {@link AccessibilityNodeInfo#recycle()} to minimize object creation.
4190     * </p>
4191     *
4192     * @return A populated {@link AccessibilityNodeInfo}.
4193     *
4194     * @see AccessibilityNodeInfo
4195     */
4196    public AccessibilityNodeInfo createAccessibilityNodeInfo() {
4197        AccessibilityNodeProvider provider = getAccessibilityNodeProvider();
4198        if (provider != null) {
4199            return provider.createAccessibilityNodeInfo(View.NO_ID);
4200        } else {
4201            AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this);
4202            onInitializeAccessibilityNodeInfo(info);
4203            return info;
4204        }
4205    }
4206
4207    /**
4208     * Initializes an {@link AccessibilityNodeInfo} with information about this view.
4209     * The base implementation sets:
4210     * <ul>
4211     *   <li>{@link AccessibilityNodeInfo#setParent(View)},</li>
4212     *   <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li>
4213     *   <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li>
4214     *   <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li>
4215     *   <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li>
4216     *   <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li>
4217     *   <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li>
4218     *   <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li>
4219     *   <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li>
4220     *   <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
4221     *   <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
4222     *   <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
4223     * </ul>
4224     * <p>
4225     * Subclasses should override this method, call the super implementation,
4226     * and set additional attributes.
4227     * </p>
4228     * <p>
4229     * If an {@link AccessibilityDelegate} has been specified via calling
4230     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4231     * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}
4232     * is responsible for handling this call.
4233     * </p>
4234     *
4235     * @param info The instance to initialize.
4236     */
4237    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
4238        if (mAccessibilityDelegate != null) {
4239            mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info);
4240        } else {
4241            onInitializeAccessibilityNodeInfoInternal(info);
4242        }
4243    }
4244
4245    /**
4246     * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
4247     *
4248     * Note: Called from the default {@link AccessibilityDelegate}.
4249     */
4250    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
4251        Rect bounds = mAttachInfo.mTmpInvalRect;
4252        getDrawingRect(bounds);
4253        info.setBoundsInParent(bounds);
4254
4255        int[] locationOnScreen = mAttachInfo.mInvalidateChildLocation;
4256        getLocationOnScreen(locationOnScreen);
4257        bounds.offsetTo(0, 0);
4258        bounds.offset(locationOnScreen[0], locationOnScreen[1]);
4259        info.setBoundsInScreen(bounds);
4260
4261        if ((mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
4262            ViewParent parent = getParent();
4263            if (parent instanceof View) {
4264                View parentView = (View) parent;
4265                info.setParent(parentView);
4266            }
4267        }
4268
4269        info.setPackageName(mContext.getPackageName());
4270        info.setClassName(View.class.getName());
4271        info.setContentDescription(getContentDescription());
4272
4273        info.setEnabled(isEnabled());
4274        info.setClickable(isClickable());
4275        info.setFocusable(isFocusable());
4276        info.setFocused(isFocused());
4277        info.setSelected(isSelected());
4278        info.setLongClickable(isLongClickable());
4279
4280        // TODO: These make sense only if we are in an AdapterView but all
4281        // views can be selected. Maybe from accessiiblity perspective
4282        // we should report as selectable view in an AdapterView.
4283        info.addAction(AccessibilityNodeInfo.ACTION_SELECT);
4284        info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION);
4285
4286        if (isFocusable()) {
4287            if (isFocused()) {
4288                info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS);
4289            } else {
4290                info.addAction(AccessibilityNodeInfo.ACTION_FOCUS);
4291            }
4292        }
4293    }
4294
4295    /**
4296     * Sets a delegate for implementing accessibility support via compositon as
4297     * opposed to inheritance. The delegate's primary use is for implementing
4298     * backwards compatible widgets. For more details see {@link AccessibilityDelegate}.
4299     *
4300     * @param delegate The delegate instance.
4301     *
4302     * @see AccessibilityDelegate
4303     */
4304    public void setAccessibilityDelegate(AccessibilityDelegate delegate) {
4305        mAccessibilityDelegate = delegate;
4306    }
4307
4308    /**
4309     * Gets the provider for managing a virtual view hierarchy rooted at this View
4310     * and reported to {@link android.accessibilityservice.AccessibilityService}s
4311     * that explore the window content.
4312     * <p>
4313     * If this method returns an instance, this instance is responsible for managing
4314     * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this
4315     * View including the one representing the View itself. Similarly the returned
4316     * instance is responsible for performing accessibility actions on any virtual
4317     * view or the root view itself.
4318     * </p>
4319     * <p>
4320     * If an {@link AccessibilityDelegate} has been specified via calling
4321     * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its
4322     * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)}
4323     * is responsible for handling this call.
4324     * </p>
4325     *
4326     * @return The provider.
4327     *
4328     * @see AccessibilityNodeProvider
4329     */
4330    public AccessibilityNodeProvider getAccessibilityNodeProvider() {
4331        if (mAccessibilityDelegate != null) {
4332            return mAccessibilityDelegate.getAccessibilityNodeProvider(this);
4333        } else {
4334            return null;
4335        }
4336    }
4337
4338    /**
4339     * Gets the unique identifier of this view on the screen for accessibility purposes.
4340     * If this {@link View} is not attached to any window, {@value #NO_ID} is returned.
4341     *
4342     * @return The view accessibility id.
4343     *
4344     * @hide
4345     */
4346    public int getAccessibilityViewId() {
4347        if (mAccessibilityViewId == NO_ID) {
4348            mAccessibilityViewId = sNextAccessibilityViewId++;
4349        }
4350        return mAccessibilityViewId;
4351    }
4352
4353    /**
4354     * Gets the unique identifier of the window in which this View reseides.
4355     *
4356     * @return The window accessibility id.
4357     *
4358     * @hide
4359     */
4360    public int getAccessibilityWindowId() {
4361        return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID;
4362    }
4363
4364    /**
4365     * Gets the {@link View} description. It briefly describes the view and is
4366     * primarily used for accessibility support. Set this property to enable
4367     * better accessibility support for your application. This is especially
4368     * true for views that do not have textual representation (For example,
4369     * ImageButton).
4370     *
4371     * @return The content descriptiopn.
4372     *
4373     * @attr ref android.R.styleable#View_contentDescription
4374     */
4375    public CharSequence getContentDescription() {
4376        return mContentDescription;
4377    }
4378
4379    /**
4380     * Sets the {@link View} description. It briefly describes the view and is
4381     * primarily used for accessibility support. Set this property to enable
4382     * better accessibility support for your application. This is especially
4383     * true for views that do not have textual representation (For example,
4384     * ImageButton).
4385     *
4386     * @param contentDescription The content description.
4387     *
4388     * @attr ref android.R.styleable#View_contentDescription
4389     */
4390    @RemotableViewMethod
4391    public void setContentDescription(CharSequence contentDescription) {
4392        mContentDescription = contentDescription;
4393    }
4394
4395    /**
4396     * Invoked whenever this view loses focus, either by losing window focus or by losing
4397     * focus within its window. This method can be used to clear any state tied to the
4398     * focus. For instance, if a button is held pressed with the trackball and the window
4399     * loses focus, this method can be used to cancel the press.
4400     *
4401     * Subclasses of View overriding this method should always call super.onFocusLost().
4402     *
4403     * @see #onFocusChanged(boolean, int, android.graphics.Rect)
4404     * @see #onWindowFocusChanged(boolean)
4405     *
4406     * @hide pending API council approval
4407     */
4408    protected void onFocusLost() {
4409        resetPressedState();
4410    }
4411
4412    private void resetPressedState() {
4413        if ((mViewFlags & ENABLED_MASK) == DISABLED) {
4414            return;
4415        }
4416
4417        if (isPressed()) {
4418            setPressed(false);
4419
4420            if (!mHasPerformedLongPress) {
4421                removeLongPressCallback();
4422            }
4423        }
4424    }
4425
4426    /**
4427     * Returns true if this view has focus
4428     *
4429     * @return True if this view has focus, false otherwise.
4430     */
4431    @ViewDebug.ExportedProperty(category = "focus")
4432    public boolean isFocused() {
4433        return (mPrivateFlags & FOCUSED) != 0;
4434    }
4435
4436    /**
4437     * Find the view in the hierarchy rooted at this view that currently has
4438     * focus.
4439     *
4440     * @return The view that currently has focus, or null if no focused view can
4441     *         be found.
4442     */
4443    public View findFocus() {
4444        return (mPrivateFlags & FOCUSED) != 0 ? this : null;
4445    }
4446
4447    /**
4448     * Change whether this view is one of the set of scrollable containers in
4449     * its window.  This will be used to determine whether the window can
4450     * resize or must pan when a soft input area is open -- scrollable
4451     * containers allow the window to use resize mode since the container
4452     * will appropriately shrink.
4453     */
4454    public void setScrollContainer(boolean isScrollContainer) {
4455        if (isScrollContainer) {
4456            if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
4457                mAttachInfo.mScrollContainers.add(this);
4458                mPrivateFlags |= SCROLL_CONTAINER_ADDED;
4459            }
4460            mPrivateFlags |= SCROLL_CONTAINER;
4461        } else {
4462            if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
4463                mAttachInfo.mScrollContainers.remove(this);
4464            }
4465            mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
4466        }
4467    }
4468
4469    /**
4470     * Returns the quality of the drawing cache.
4471     *
4472     * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4473     *         {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4474     *
4475     * @see #setDrawingCacheQuality(int)
4476     * @see #setDrawingCacheEnabled(boolean)
4477     * @see #isDrawingCacheEnabled()
4478     *
4479     * @attr ref android.R.styleable#View_drawingCacheQuality
4480     */
4481    public int getDrawingCacheQuality() {
4482        return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
4483    }
4484
4485    /**
4486     * Set the drawing cache quality of this view. This value is used only when the
4487     * drawing cache is enabled
4488     *
4489     * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
4490     *        {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
4491     *
4492     * @see #getDrawingCacheQuality()
4493     * @see #setDrawingCacheEnabled(boolean)
4494     * @see #isDrawingCacheEnabled()
4495     *
4496     * @attr ref android.R.styleable#View_drawingCacheQuality
4497     */
4498    public void setDrawingCacheQuality(int quality) {
4499        setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
4500    }
4501
4502    /**
4503     * Returns whether the screen should remain on, corresponding to the current
4504     * value of {@link #KEEP_SCREEN_ON}.
4505     *
4506     * @return Returns true if {@link #KEEP_SCREEN_ON} is set.
4507     *
4508     * @see #setKeepScreenOn(boolean)
4509     *
4510     * @attr ref android.R.styleable#View_keepScreenOn
4511     */
4512    public boolean getKeepScreenOn() {
4513        return (mViewFlags & KEEP_SCREEN_ON) != 0;
4514    }
4515
4516    /**
4517     * Controls whether the screen should remain on, modifying the
4518     * value of {@link #KEEP_SCREEN_ON}.
4519     *
4520     * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
4521     *
4522     * @see #getKeepScreenOn()
4523     *
4524     * @attr ref android.R.styleable#View_keepScreenOn
4525     */
4526    public void setKeepScreenOn(boolean keepScreenOn) {
4527        setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
4528    }
4529
4530    /**
4531     * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4532     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4533     *
4534     * @attr ref android.R.styleable#View_nextFocusLeft
4535     */
4536    public int getNextFocusLeftId() {
4537        return mNextFocusLeftId;
4538    }
4539
4540    /**
4541     * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}.
4542     * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should
4543     * decide automatically.
4544     *
4545     * @attr ref android.R.styleable#View_nextFocusLeft
4546     */
4547    public void setNextFocusLeftId(int nextFocusLeftId) {
4548        mNextFocusLeftId = nextFocusLeftId;
4549    }
4550
4551    /**
4552     * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4553     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4554     *
4555     * @attr ref android.R.styleable#View_nextFocusRight
4556     */
4557    public int getNextFocusRightId() {
4558        return mNextFocusRightId;
4559    }
4560
4561    /**
4562     * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}.
4563     * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should
4564     * decide automatically.
4565     *
4566     * @attr ref android.R.styleable#View_nextFocusRight
4567     */
4568    public void setNextFocusRightId(int nextFocusRightId) {
4569        mNextFocusRightId = nextFocusRightId;
4570    }
4571
4572    /**
4573     * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4574     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4575     *
4576     * @attr ref android.R.styleable#View_nextFocusUp
4577     */
4578    public int getNextFocusUpId() {
4579        return mNextFocusUpId;
4580    }
4581
4582    /**
4583     * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}.
4584     * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should
4585     * decide automatically.
4586     *
4587     * @attr ref android.R.styleable#View_nextFocusUp
4588     */
4589    public void setNextFocusUpId(int nextFocusUpId) {
4590        mNextFocusUpId = nextFocusUpId;
4591    }
4592
4593    /**
4594     * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4595     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4596     *
4597     * @attr ref android.R.styleable#View_nextFocusDown
4598     */
4599    public int getNextFocusDownId() {
4600        return mNextFocusDownId;
4601    }
4602
4603    /**
4604     * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}.
4605     * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should
4606     * decide automatically.
4607     *
4608     * @attr ref android.R.styleable#View_nextFocusDown
4609     */
4610    public void setNextFocusDownId(int nextFocusDownId) {
4611        mNextFocusDownId = nextFocusDownId;
4612    }
4613
4614    /**
4615     * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4616     * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically.
4617     *
4618     * @attr ref android.R.styleable#View_nextFocusForward
4619     */
4620    public int getNextFocusForwardId() {
4621        return mNextFocusForwardId;
4622    }
4623
4624    /**
4625     * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}.
4626     * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should
4627     * decide automatically.
4628     *
4629     * @attr ref android.R.styleable#View_nextFocusForward
4630     */
4631    public void setNextFocusForwardId(int nextFocusForwardId) {
4632        mNextFocusForwardId = nextFocusForwardId;
4633    }
4634
4635    /**
4636     * Returns the visibility of this view and all of its ancestors
4637     *
4638     * @return True if this view and all of its ancestors are {@link #VISIBLE}
4639     */
4640    public boolean isShown() {
4641        View current = this;
4642        //noinspection ConstantConditions
4643        do {
4644            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
4645                return false;
4646            }
4647            ViewParent parent = current.mParent;
4648            if (parent == null) {
4649                return false; // We are not attached to the view root
4650            }
4651            if (!(parent instanceof View)) {
4652                return true;
4653            }
4654            current = (View) parent;
4655        } while (current != null);
4656
4657        return false;
4658    }
4659
4660    /**
4661     * Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
4662     * is set
4663     *
4664     * @param insets Insets for system windows
4665     *
4666     * @return True if this view applied the insets, false otherwise
4667     */
4668    protected boolean fitSystemWindows(Rect insets) {
4669        if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
4670            mPaddingLeft = insets.left;
4671            mPaddingTop = insets.top;
4672            mPaddingRight = insets.right;
4673            mPaddingBottom = insets.bottom;
4674            requestLayout();
4675            return true;
4676        }
4677        return false;
4678    }
4679
4680    /**
4681     * Set whether or not this view should account for system screen decorations
4682     * such as the status bar and inset its content. This allows this view to be
4683     * positioned in absolute screen coordinates and remain visible to the user.
4684     *
4685     * <p>This should only be used by top-level window decor views.
4686     *
4687     * @param fitSystemWindows true to inset content for system screen decorations, false for
4688     *                         default behavior.
4689     *
4690     * @attr ref android.R.styleable#View_fitsSystemWindows
4691     */
4692    public void setFitsSystemWindows(boolean fitSystemWindows) {
4693        setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);
4694    }
4695
4696    /**
4697     * Check for the FITS_SYSTEM_WINDOWS flag. If this method returns true, this view
4698     * will account for system screen decorations such as the status bar and inset its
4699     * content. This allows the view to be positioned in absolute screen coordinates
4700     * and remain visible to the user.
4701     *
4702     * @return true if this view will adjust its content bounds for system screen decorations.
4703     *
4704     * @attr ref android.R.styleable#View_fitsSystemWindows
4705     */
4706    public boolean fitsSystemWindows() {
4707        return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS;
4708    }
4709
4710    /**
4711     * Returns the visibility status for this view.
4712     *
4713     * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4714     * @attr ref android.R.styleable#View_visibility
4715     */
4716    @ViewDebug.ExportedProperty(mapping = {
4717        @ViewDebug.IntToString(from = VISIBLE,   to = "VISIBLE"),
4718        @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
4719        @ViewDebug.IntToString(from = GONE,      to = "GONE")
4720    })
4721    public int getVisibility() {
4722        return mViewFlags & VISIBILITY_MASK;
4723    }
4724
4725    /**
4726     * Set the enabled state of this view.
4727     *
4728     * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
4729     * @attr ref android.R.styleable#View_visibility
4730     */
4731    @RemotableViewMethod
4732    public void setVisibility(int visibility) {
4733        setFlags(visibility, VISIBILITY_MASK);
4734        if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
4735    }
4736
4737    /**
4738     * Returns the enabled status for this view. The interpretation of the
4739     * enabled state varies by subclass.
4740     *
4741     * @return True if this view is enabled, false otherwise.
4742     */
4743    @ViewDebug.ExportedProperty
4744    public boolean isEnabled() {
4745        return (mViewFlags & ENABLED_MASK) == ENABLED;
4746    }
4747
4748    /**
4749     * Set the enabled state of this view. The interpretation of the enabled
4750     * state varies by subclass.
4751     *
4752     * @param enabled True if this view is enabled, false otherwise.
4753     */
4754    @RemotableViewMethod
4755    public void setEnabled(boolean enabled) {
4756        if (enabled == isEnabled()) return;
4757
4758        setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
4759
4760        /*
4761         * The View most likely has to change its appearance, so refresh
4762         * the drawable state.
4763         */
4764        refreshDrawableState();
4765
4766        // Invalidate too, since the default behavior for views is to be
4767        // be drawn at 50% alpha rather than to change the drawable.
4768        invalidate(true);
4769    }
4770
4771    /**
4772     * Set whether this view can receive the focus.
4773     *
4774     * Setting this to false will also ensure that this view is not focusable
4775     * in touch mode.
4776     *
4777     * @param focusable If true, this view can receive the focus.
4778     *
4779     * @see #setFocusableInTouchMode(boolean)
4780     * @attr ref android.R.styleable#View_focusable
4781     */
4782    public void setFocusable(boolean focusable) {
4783        if (!focusable) {
4784            setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
4785        }
4786        setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
4787    }
4788
4789    /**
4790     * Set whether this view can receive focus while in touch mode.
4791     *
4792     * Setting this to true will also ensure that this view is focusable.
4793     *
4794     * @param focusableInTouchMode If true, this view can receive the focus while
4795     *   in touch mode.
4796     *
4797     * @see #setFocusable(boolean)
4798     * @attr ref android.R.styleable#View_focusableInTouchMode
4799     */
4800    public void setFocusableInTouchMode(boolean focusableInTouchMode) {
4801        // Focusable in touch mode should always be set before the focusable flag
4802        // otherwise, setting the focusable flag will trigger a focusableViewAvailable()
4803        // which, in touch mode, will not successfully request focus on this view
4804        // because the focusable in touch mode flag is not set
4805        setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
4806        if (focusableInTouchMode) {
4807            setFlags(FOCUSABLE, FOCUSABLE_MASK);
4808        }
4809    }
4810
4811    /**
4812     * Set whether this view should have sound effects enabled for events such as
4813     * clicking and touching.
4814     *
4815     * <p>You may wish to disable sound effects for a view if you already play sounds,
4816     * for instance, a dial key that plays dtmf tones.
4817     *
4818     * @param soundEffectsEnabled whether sound effects are enabled for this view.
4819     * @see #isSoundEffectsEnabled()
4820     * @see #playSoundEffect(int)
4821     * @attr ref android.R.styleable#View_soundEffectsEnabled
4822     */
4823    public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
4824        setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
4825    }
4826
4827    /**
4828     * @return whether this view should have sound effects enabled for events such as
4829     *     clicking and touching.
4830     *
4831     * @see #setSoundEffectsEnabled(boolean)
4832     * @see #playSoundEffect(int)
4833     * @attr ref android.R.styleable#View_soundEffectsEnabled
4834     */
4835    @ViewDebug.ExportedProperty
4836    public boolean isSoundEffectsEnabled() {
4837        return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
4838    }
4839
4840    /**
4841     * Set whether this view should have haptic feedback for events such as
4842     * long presses.
4843     *
4844     * <p>You may wish to disable haptic feedback if your view already controls
4845     * its own haptic feedback.
4846     *
4847     * @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
4848     * @see #isHapticFeedbackEnabled()
4849     * @see #performHapticFeedback(int)
4850     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4851     */
4852    public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
4853        setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
4854    }
4855
4856    /**
4857     * @return whether this view should have haptic feedback enabled for events
4858     * long presses.
4859     *
4860     * @see #setHapticFeedbackEnabled(boolean)
4861     * @see #performHapticFeedback(int)
4862     * @attr ref android.R.styleable#View_hapticFeedbackEnabled
4863     */
4864    @ViewDebug.ExportedProperty
4865    public boolean isHapticFeedbackEnabled() {
4866        return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
4867    }
4868
4869    /**
4870     * Returns the layout direction for this view.
4871     *
4872     * @return One of {@link #LAYOUT_DIRECTION_LTR},
4873     *   {@link #LAYOUT_DIRECTION_RTL},
4874     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4875     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4876     * @attr ref android.R.styleable#View_layoutDirection
4877     */
4878    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4879        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "LTR"),
4880        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RTL"),
4881        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"),
4882        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE,  to = "LOCALE")
4883    })
4884    public int getLayoutDirection() {
4885        return mViewFlags & LAYOUT_DIRECTION_MASK;
4886    }
4887
4888    /**
4889     * Set the layout direction for this view. This will propagate a reset of layout direction
4890     * resolution to the view's children and resolve layout direction for this view.
4891     *
4892     * @param layoutDirection One of {@link #LAYOUT_DIRECTION_LTR},
4893     *   {@link #LAYOUT_DIRECTION_RTL},
4894     *   {@link #LAYOUT_DIRECTION_INHERIT} or
4895     *   {@link #LAYOUT_DIRECTION_LOCALE}.
4896     *
4897     * @attr ref android.R.styleable#View_layoutDirection
4898     */
4899    @RemotableViewMethod
4900    public void setLayoutDirection(int layoutDirection) {
4901        if (getLayoutDirection() != layoutDirection) {
4902            resetResolvedLayoutDirection();
4903            // Setting the flag will also request a layout.
4904            setFlags(layoutDirection, LAYOUT_DIRECTION_MASK);
4905        }
4906    }
4907
4908    /**
4909     * Returns the resolved layout direction for this view.
4910     *
4911     * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns
4912     * {@link #LAYOUT_DIRECTION_LTR} id the layout direction is not RTL.
4913     */
4914    @ViewDebug.ExportedProperty(category = "layout", mapping = {
4915        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR,     to = "RESOLVED_DIRECTION_LTR"),
4916        @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL,     to = "RESOLVED_DIRECTION_RTL")
4917    })
4918    public int getResolvedLayoutDirection() {
4919        resolveLayoutDirectionIfNeeded();
4920        return ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED_RTL) == LAYOUT_DIRECTION_RESOLVED_RTL) ?
4921                LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR;
4922    }
4923
4924    /**
4925     * <p>Indicates whether or not this view's layout is right-to-left. This is resolved from
4926     * layout attribute and/or the inherited value from the parent.</p>
4927     *
4928     * @return true if the layout is right-to-left.
4929     */
4930    @ViewDebug.ExportedProperty(category = "layout")
4931    public boolean isLayoutRtl() {
4932        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL);
4933    }
4934
4935    /**
4936     * Indicates whether the view is currently tracking transient state that the
4937     * app should not need to concern itself with saving and restoring, but that
4938     * the framework should take special note to preserve when possible.
4939     *
4940     * @return true if the view has transient state
4941     */
4942    @ViewDebug.ExportedProperty(category = "layout")
4943    public boolean hasTransientState() {
4944        return (mPrivateFlags2 & HAS_TRANSIENT_STATE) == HAS_TRANSIENT_STATE;
4945    }
4946
4947    /**
4948     * Set whether this view is currently tracking transient state that the
4949     * framework should attempt to preserve when possible.
4950     *
4951     * @param hasTransientState true if this view has transient state
4952     */
4953    public void setHasTransientState(boolean hasTransientState) {
4954        if (hasTransientState() == hasTransientState) return;
4955
4956        mPrivateFlags2 = (mPrivateFlags2 & ~HAS_TRANSIENT_STATE) |
4957                (hasTransientState ? HAS_TRANSIENT_STATE : 0);
4958        if (mParent != null) {
4959            try {
4960                mParent.childHasTransientStateChanged(this, hasTransientState);
4961            } catch (AbstractMethodError e) {
4962                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
4963                        " does not fully implement ViewParent", e);
4964            }
4965        }
4966    }
4967
4968    /**
4969     * If this view doesn't do any drawing on its own, set this flag to
4970     * allow further optimizations. By default, this flag is not set on
4971     * View, but could be set on some View subclasses such as ViewGroup.
4972     *
4973     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
4974     * you should clear this flag.
4975     *
4976     * @param willNotDraw whether or not this View draw on its own
4977     */
4978    public void setWillNotDraw(boolean willNotDraw) {
4979        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
4980    }
4981
4982    /**
4983     * Returns whether or not this View draws on its own.
4984     *
4985     * @return true if this view has nothing to draw, false otherwise
4986     */
4987    @ViewDebug.ExportedProperty(category = "drawing")
4988    public boolean willNotDraw() {
4989        return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
4990    }
4991
4992    /**
4993     * When a View's drawing cache is enabled, drawing is redirected to an
4994     * offscreen bitmap. Some views, like an ImageView, must be able to
4995     * bypass this mechanism if they already draw a single bitmap, to avoid
4996     * unnecessary usage of the memory.
4997     *
4998     * @param willNotCacheDrawing true if this view does not cache its
4999     *        drawing, false otherwise
5000     */
5001    public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
5002        setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
5003    }
5004
5005    /**
5006     * Returns whether or not this View can cache its drawing or not.
5007     *
5008     * @return true if this view does not cache its drawing, false otherwise
5009     */
5010    @ViewDebug.ExportedProperty(category = "drawing")
5011    public boolean willNotCacheDrawing() {
5012        return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
5013    }
5014
5015    /**
5016     * Indicates whether this view reacts to click events or not.
5017     *
5018     * @return true if the view is clickable, false otherwise
5019     *
5020     * @see #setClickable(boolean)
5021     * @attr ref android.R.styleable#View_clickable
5022     */
5023    @ViewDebug.ExportedProperty
5024    public boolean isClickable() {
5025        return (mViewFlags & CLICKABLE) == CLICKABLE;
5026    }
5027
5028    /**
5029     * Enables or disables click events for this view. When a view
5030     * is clickable it will change its state to "pressed" on every click.
5031     * Subclasses should set the view clickable to visually react to
5032     * user's clicks.
5033     *
5034     * @param clickable true to make the view clickable, false otherwise
5035     *
5036     * @see #isClickable()
5037     * @attr ref android.R.styleable#View_clickable
5038     */
5039    public void setClickable(boolean clickable) {
5040        setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
5041    }
5042
5043    /**
5044     * Indicates whether this view reacts to long click events or not.
5045     *
5046     * @return true if the view is long clickable, false otherwise
5047     *
5048     * @see #setLongClickable(boolean)
5049     * @attr ref android.R.styleable#View_longClickable
5050     */
5051    public boolean isLongClickable() {
5052        return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
5053    }
5054
5055    /**
5056     * Enables or disables long click events for this view. When a view is long
5057     * clickable it reacts to the user holding down the button for a longer
5058     * duration than a tap. This event can either launch the listener or a
5059     * context menu.
5060     *
5061     * @param longClickable true to make the view long clickable, false otherwise
5062     * @see #isLongClickable()
5063     * @attr ref android.R.styleable#View_longClickable
5064     */
5065    public void setLongClickable(boolean longClickable) {
5066        setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
5067    }
5068
5069    /**
5070     * Sets the pressed state for this view.
5071     *
5072     * @see #isClickable()
5073     * @see #setClickable(boolean)
5074     *
5075     * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
5076     *        the View's internal state from a previously set "pressed" state.
5077     */
5078    public void setPressed(boolean pressed) {
5079        final boolean needsRefresh = pressed != ((mPrivateFlags & PRESSED) == PRESSED);
5080
5081        if (pressed) {
5082            mPrivateFlags |= PRESSED;
5083        } else {
5084            mPrivateFlags &= ~PRESSED;
5085        }
5086
5087        if (needsRefresh) {
5088            refreshDrawableState();
5089        }
5090        dispatchSetPressed(pressed);
5091    }
5092
5093    /**
5094     * Dispatch setPressed to all of this View's children.
5095     *
5096     * @see #setPressed(boolean)
5097     *
5098     * @param pressed The new pressed state
5099     */
5100    protected void dispatchSetPressed(boolean pressed) {
5101    }
5102
5103    /**
5104     * Indicates whether the view is currently in pressed state. Unless
5105     * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
5106     * the pressed state.
5107     *
5108     * @see #setPressed(boolean)
5109     * @see #isClickable()
5110     * @see #setClickable(boolean)
5111     *
5112     * @return true if the view is currently pressed, false otherwise
5113     */
5114    public boolean isPressed() {
5115        return (mPrivateFlags & PRESSED) == PRESSED;
5116    }
5117
5118    /**
5119     * Indicates whether this view will save its state (that is,
5120     * whether its {@link #onSaveInstanceState} method will be called).
5121     *
5122     * @return Returns true if the view state saving is enabled, else false.
5123     *
5124     * @see #setSaveEnabled(boolean)
5125     * @attr ref android.R.styleable#View_saveEnabled
5126     */
5127    public boolean isSaveEnabled() {
5128        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
5129    }
5130
5131    /**
5132     * Controls whether the saving of this view's state is
5133     * enabled (that is, whether its {@link #onSaveInstanceState} method
5134     * will be called).  Note that even if freezing is enabled, the
5135     * view still must have an id assigned to it (via {@link #setId(int)})
5136     * for its state to be saved.  This flag can only disable the
5137     * saving of this view; any child views may still have their state saved.
5138     *
5139     * @param enabled Set to false to <em>disable</em> state saving, or true
5140     * (the default) to allow it.
5141     *
5142     * @see #isSaveEnabled()
5143     * @see #setId(int)
5144     * @see #onSaveInstanceState()
5145     * @attr ref android.R.styleable#View_saveEnabled
5146     */
5147    public void setSaveEnabled(boolean enabled) {
5148        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
5149    }
5150
5151    /**
5152     * Gets whether the framework should discard touches when the view's
5153     * window is obscured by another visible window.
5154     * Refer to the {@link View} security documentation for more details.
5155     *
5156     * @return True if touch filtering is enabled.
5157     *
5158     * @see #setFilterTouchesWhenObscured(boolean)
5159     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5160     */
5161    @ViewDebug.ExportedProperty
5162    public boolean getFilterTouchesWhenObscured() {
5163        return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0;
5164    }
5165
5166    /**
5167     * Sets whether the framework should discard touches when the view's
5168     * window is obscured by another visible window.
5169     * Refer to the {@link View} security documentation for more details.
5170     *
5171     * @param enabled True if touch filtering should be enabled.
5172     *
5173     * @see #getFilterTouchesWhenObscured
5174     * @attr ref android.R.styleable#View_filterTouchesWhenObscured
5175     */
5176    public void setFilterTouchesWhenObscured(boolean enabled) {
5177        setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED,
5178                FILTER_TOUCHES_WHEN_OBSCURED);
5179    }
5180
5181    /**
5182     * Indicates whether the entire hierarchy under this view will save its
5183     * state when a state saving traversal occurs from its parent.  The default
5184     * is true; if false, these views will not be saved unless
5185     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5186     *
5187     * @return Returns true if the view state saving from parent is enabled, else false.
5188     *
5189     * @see #setSaveFromParentEnabled(boolean)
5190     */
5191    public boolean isSaveFromParentEnabled() {
5192        return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED;
5193    }
5194
5195    /**
5196     * Controls whether the entire hierarchy under this view will save its
5197     * state when a state saving traversal occurs from its parent.  The default
5198     * is true; if false, these views will not be saved unless
5199     * {@link #saveHierarchyState(SparseArray)} is called directly on this view.
5200     *
5201     * @param enabled Set to false to <em>disable</em> state saving, or true
5202     * (the default) to allow it.
5203     *
5204     * @see #isSaveFromParentEnabled()
5205     * @see #setId(int)
5206     * @see #onSaveInstanceState()
5207     */
5208    public void setSaveFromParentEnabled(boolean enabled) {
5209        setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK);
5210    }
5211
5212
5213    /**
5214     * Returns whether this View is able to take focus.
5215     *
5216     * @return True if this view can take focus, or false otherwise.
5217     * @attr ref android.R.styleable#View_focusable
5218     */
5219    @ViewDebug.ExportedProperty(category = "focus")
5220    public final boolean isFocusable() {
5221        return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
5222    }
5223
5224    /**
5225     * When a view is focusable, it may not want to take focus when in touch mode.
5226     * For example, a button would like focus when the user is navigating via a D-pad
5227     * so that the user can click on it, but once the user starts touching the screen,
5228     * the button shouldn't take focus
5229     * @return Whether the view is focusable in touch mode.
5230     * @attr ref android.R.styleable#View_focusableInTouchMode
5231     */
5232    @ViewDebug.ExportedProperty
5233    public final boolean isFocusableInTouchMode() {
5234        return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
5235    }
5236
5237    /**
5238     * Find the nearest view in the specified direction that can take focus.
5239     * This does not actually give focus to that view.
5240     *
5241     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5242     *
5243     * @return The nearest focusable in the specified direction, or null if none
5244     *         can be found.
5245     */
5246    public View focusSearch(int direction) {
5247        if (mParent != null) {
5248            return mParent.focusSearch(this, direction);
5249        } else {
5250            return null;
5251        }
5252    }
5253
5254    /**
5255     * This method is the last chance for the focused view and its ancestors to
5256     * respond to an arrow key. This is called when the focused view did not
5257     * consume the key internally, nor could the view system find a new view in
5258     * the requested direction to give focus to.
5259     *
5260     * @param focused The currently focused view.
5261     * @param direction The direction focus wants to move. One of FOCUS_UP,
5262     *        FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
5263     * @return True if the this view consumed this unhandled move.
5264     */
5265    public boolean dispatchUnhandledMove(View focused, int direction) {
5266        return false;
5267    }
5268
5269    /**
5270     * If a user manually specified the next view id for a particular direction,
5271     * use the root to look up the view.
5272     * @param root The root view of the hierarchy containing this view.
5273     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD,
5274     * or FOCUS_BACKWARD.
5275     * @return The user specified next view, or null if there is none.
5276     */
5277    View findUserSetNextFocus(View root, int direction) {
5278        switch (direction) {
5279            case FOCUS_LEFT:
5280                if (mNextFocusLeftId == View.NO_ID) return null;
5281                return findViewInsideOutShouldExist(root, mNextFocusLeftId);
5282            case FOCUS_RIGHT:
5283                if (mNextFocusRightId == View.NO_ID) return null;
5284                return findViewInsideOutShouldExist(root, mNextFocusRightId);
5285            case FOCUS_UP:
5286                if (mNextFocusUpId == View.NO_ID) return null;
5287                return findViewInsideOutShouldExist(root, mNextFocusUpId);
5288            case FOCUS_DOWN:
5289                if (mNextFocusDownId == View.NO_ID) return null;
5290                return findViewInsideOutShouldExist(root, mNextFocusDownId);
5291            case FOCUS_FORWARD:
5292                if (mNextFocusForwardId == View.NO_ID) return null;
5293                return findViewInsideOutShouldExist(root, mNextFocusForwardId);
5294            case FOCUS_BACKWARD: {
5295                if (mID == View.NO_ID) return null;
5296                final int id = mID;
5297                return root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5298                    @Override
5299                    public boolean apply(View t) {
5300                        return t.mNextFocusForwardId == id;
5301                    }
5302                });
5303            }
5304        }
5305        return null;
5306    }
5307
5308    private View findViewInsideOutShouldExist(View root, final int childViewId) {
5309        View result = root.findViewByPredicateInsideOut(this, new Predicate<View>() {
5310            @Override
5311            public boolean apply(View t) {
5312                return t.mID == childViewId;
5313            }
5314        });
5315
5316        if (result == null) {
5317            Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
5318                    + "by user for id " + childViewId);
5319        }
5320        return result;
5321    }
5322
5323    /**
5324     * Find and return all focusable views that are descendants of this view,
5325     * possibly including this view if it is focusable itself.
5326     *
5327     * @param direction The direction of the focus
5328     * @return A list of focusable views
5329     */
5330    public ArrayList<View> getFocusables(int direction) {
5331        ArrayList<View> result = new ArrayList<View>(24);
5332        addFocusables(result, direction);
5333        return result;
5334    }
5335
5336    /**
5337     * Add any focusable views that are descendants of this view (possibly
5338     * including this view if it is focusable itself) to views.  If we are in touch mode,
5339     * only add views that are also focusable in touch mode.
5340     *
5341     * @param views Focusable views found so far
5342     * @param direction The direction of the focus
5343     */
5344    public void addFocusables(ArrayList<View> views, int direction) {
5345        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
5346    }
5347
5348    /**
5349     * Adds any focusable views that are descendants of this view (possibly
5350     * including this view if it is focusable itself) to views. This method
5351     * adds all focusable views regardless if we are in touch mode or
5352     * only views focusable in touch mode if we are in touch mode depending on
5353     * the focusable mode paramater.
5354     *
5355     * @param views Focusable views found so far or null if all we are interested is
5356     *        the number of focusables.
5357     * @param direction The direction of the focus.
5358     * @param focusableMode The type of focusables to be added.
5359     *
5360     * @see #FOCUSABLES_ALL
5361     * @see #FOCUSABLES_TOUCH_MODE
5362     */
5363    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
5364        if (!isFocusable()) {
5365            return;
5366        }
5367
5368        if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
5369                isInTouchMode() && !isFocusableInTouchMode()) {
5370            return;
5371        }
5372
5373        if (views != null) {
5374            views.add(this);
5375        }
5376    }
5377
5378    /**
5379     * Finds the Views that contain given text. The containment is case insensitive.
5380     * The search is performed by either the text that the View renders or the content
5381     * description that describes the view for accessibility purposes and the view does
5382     * not render or both. Clients can specify how the search is to be performed via
5383     * passing the {@link #FIND_VIEWS_WITH_TEXT} and
5384     * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags.
5385     *
5386     * @param outViews The output list of matching Views.
5387     * @param searched The text to match against.
5388     *
5389     * @see #FIND_VIEWS_WITH_TEXT
5390     * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION
5391     * @see #setContentDescription(CharSequence)
5392     */
5393    public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) {
5394        if (getAccessibilityNodeProvider() != null) {
5395            if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) {
5396                outViews.add(this);
5397            }
5398        } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0
5399                && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mContentDescription)) {
5400            String searchedLowerCase = searched.toString().toLowerCase();
5401            String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase();
5402            if (contentDescriptionLowerCase.contains(searchedLowerCase)) {
5403                outViews.add(this);
5404            }
5405        }
5406    }
5407
5408    /**
5409     * Find and return all touchable views that are descendants of this view,
5410     * possibly including this view if it is touchable itself.
5411     *
5412     * @return A list of touchable views
5413     */
5414    public ArrayList<View> getTouchables() {
5415        ArrayList<View> result = new ArrayList<View>();
5416        addTouchables(result);
5417        return result;
5418    }
5419
5420    /**
5421     * Add any touchable views that are descendants of this view (possibly
5422     * including this view if it is touchable itself) to views.
5423     *
5424     * @param views Touchable views found so far
5425     */
5426    public void addTouchables(ArrayList<View> views) {
5427        final int viewFlags = mViewFlags;
5428
5429        if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
5430                && (viewFlags & ENABLED_MASK) == ENABLED) {
5431            views.add(this);
5432        }
5433    }
5434
5435    /**
5436     * Call this to try to give focus to a specific view or to one of its
5437     * descendants.
5438     *
5439     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5440     * false), or if it is focusable and it is not focusable in touch mode
5441     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5442     *
5443     * See also {@link #focusSearch(int)}, which is what you call to say that you
5444     * have focus, and you want your parent to look for the next one.
5445     *
5446     * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
5447     * {@link #FOCUS_DOWN} and <code>null</code>.
5448     *
5449     * @return Whether this view or one of its descendants actually took focus.
5450     */
5451    public final boolean requestFocus() {
5452        return requestFocus(View.FOCUS_DOWN);
5453    }
5454
5455
5456    /**
5457     * Call this to try to give focus to a specific view or to one of its
5458     * descendants and give it a hint about what direction focus is heading.
5459     *
5460     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5461     * false), or if it is focusable and it is not focusable in touch mode
5462     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5463     *
5464     * See also {@link #focusSearch(int)}, which is what you call to say that you
5465     * have focus, and you want your parent to look for the next one.
5466     *
5467     * This is equivalent to calling {@link #requestFocus(int, Rect)} with
5468     * <code>null</code> set for the previously focused rectangle.
5469     *
5470     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5471     * @return Whether this view or one of its descendants actually took focus.
5472     */
5473    public final boolean requestFocus(int direction) {
5474        return requestFocus(direction, null);
5475    }
5476
5477    /**
5478     * Call this to try to give focus to a specific view or to one of its descendants
5479     * and give it hints about the direction and a specific rectangle that the focus
5480     * is coming from.  The rectangle can help give larger views a finer grained hint
5481     * about where focus is coming from, and therefore, where to show selection, or
5482     * forward focus change internally.
5483     *
5484     * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns
5485     * false), or if it is focusable and it is not focusable in touch mode
5486     * ({@link #isFocusableInTouchMode}) while the device is in touch mode.
5487     *
5488     * A View will not take focus if it is not visible.
5489     *
5490     * A View will not take focus if one of its parents has
5491     * {@link android.view.ViewGroup#getDescendantFocusability()} equal to
5492     * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
5493     *
5494     * See also {@link #focusSearch(int)}, which is what you call to say that you
5495     * have focus, and you want your parent to look for the next one.
5496     *
5497     * You may wish to override this method if your custom {@link View} has an internal
5498     * {@link View} that it wishes to forward the request to.
5499     *
5500     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
5501     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
5502     *        to give a finer grained hint about where focus is coming from.  May be null
5503     *        if there is no hint.
5504     * @return Whether this view or one of its descendants actually took focus.
5505     */
5506    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5507        // need to be focusable
5508        if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
5509                (mViewFlags & VISIBILITY_MASK) != VISIBLE) {
5510            return false;
5511        }
5512
5513        // need to be focusable in touch mode if in touch mode
5514        if (isInTouchMode() &&
5515            (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
5516               return false;
5517        }
5518
5519        // need to not have any parents blocking us
5520        if (hasAncestorThatBlocksDescendantFocus()) {
5521            return false;
5522        }
5523
5524        handleFocusGainInternal(direction, previouslyFocusedRect);
5525        return true;
5526    }
5527
5528    /**
5529     * Call this to try to give focus to a specific view or to one of its descendants. This is a
5530     * special variant of {@link #requestFocus() } that will allow views that are not focuable in
5531     * touch mode to request focus when they are touched.
5532     *
5533     * @return Whether this view or one of its descendants actually took focus.
5534     *
5535     * @see #isInTouchMode()
5536     *
5537     */
5538    public final boolean requestFocusFromTouch() {
5539        // Leave touch mode if we need to
5540        if (isInTouchMode()) {
5541            ViewRootImpl viewRoot = getViewRootImpl();
5542            if (viewRoot != null) {
5543                viewRoot.ensureTouchMode(false);
5544            }
5545        }
5546        return requestFocus(View.FOCUS_DOWN);
5547    }
5548
5549    /**
5550     * @return Whether any ancestor of this view blocks descendant focus.
5551     */
5552    private boolean hasAncestorThatBlocksDescendantFocus() {
5553        ViewParent ancestor = mParent;
5554        while (ancestor instanceof ViewGroup) {
5555            final ViewGroup vgAncestor = (ViewGroup) ancestor;
5556            if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
5557                return true;
5558            } else {
5559                ancestor = vgAncestor.getParent();
5560            }
5561        }
5562        return false;
5563    }
5564
5565    /**
5566     * @hide
5567     */
5568    public void dispatchStartTemporaryDetach() {
5569        onStartTemporaryDetach();
5570    }
5571
5572    /**
5573     * This is called when a container is going to temporarily detach a child, with
5574     * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
5575     * It will either be followed by {@link #onFinishTemporaryDetach()} or
5576     * {@link #onDetachedFromWindow()} when the container is done.
5577     */
5578    public void onStartTemporaryDetach() {
5579        removeUnsetPressCallback();
5580        mPrivateFlags |= CANCEL_NEXT_UP_EVENT;
5581    }
5582
5583    /**
5584     * @hide
5585     */
5586    public void dispatchFinishTemporaryDetach() {
5587        onFinishTemporaryDetach();
5588    }
5589
5590    /**
5591     * Called after {@link #onStartTemporaryDetach} when the container is done
5592     * changing the view.
5593     */
5594    public void onFinishTemporaryDetach() {
5595    }
5596
5597    /**
5598     * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState}
5599     * for this view's window.  Returns null if the view is not currently attached
5600     * to the window.  Normally you will not need to use this directly, but
5601     * just use the standard high-level event callbacks like
5602     * {@link #onKeyDown(int, KeyEvent)}.
5603     */
5604    public KeyEvent.DispatcherState getKeyDispatcherState() {
5605        return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null;
5606    }
5607
5608    /**
5609     * Dispatch a key event before it is processed by any input method
5610     * associated with the view hierarchy.  This can be used to intercept
5611     * key events in special situations before the IME consumes them; a
5612     * typical example would be handling the BACK key to update the application's
5613     * UI instead of allowing the IME to see it and close itself.
5614     *
5615     * @param event The key event to be dispatched.
5616     * @return True if the event was handled, false otherwise.
5617     */
5618    public boolean dispatchKeyEventPreIme(KeyEvent event) {
5619        return onKeyPreIme(event.getKeyCode(), event);
5620    }
5621
5622    /**
5623     * Dispatch a key event to the next view on the focus path. This path runs
5624     * from the top of the view tree down to the currently focused view. If this
5625     * view has focus, it will dispatch to itself. Otherwise it will dispatch
5626     * the next node down the focus path. This method also fires any key
5627     * listeners.
5628     *
5629     * @param event The key event to be dispatched.
5630     * @return True if the event was handled, false otherwise.
5631     */
5632    public boolean dispatchKeyEvent(KeyEvent event) {
5633        if (mInputEventConsistencyVerifier != null) {
5634            mInputEventConsistencyVerifier.onKeyEvent(event, 0);
5635        }
5636
5637        // Give any attached key listener a first crack at the event.
5638        //noinspection SimplifiableIfStatement
5639        ListenerInfo li = mListenerInfo;
5640        if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5641                && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
5642            return true;
5643        }
5644
5645        if (event.dispatch(this, mAttachInfo != null
5646                ? mAttachInfo.mKeyDispatchState : null, this)) {
5647            return true;
5648        }
5649
5650        if (mInputEventConsistencyVerifier != null) {
5651            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5652        }
5653        return false;
5654    }
5655
5656    /**
5657     * Dispatches a key shortcut event.
5658     *
5659     * @param event The key event to be dispatched.
5660     * @return True if the event was handled by the view, false otherwise.
5661     */
5662    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
5663        return onKeyShortcut(event.getKeyCode(), event);
5664    }
5665
5666    /**
5667     * Pass the touch screen motion event down to the target view, or this
5668     * view if it is the target.
5669     *
5670     * @param event The motion event to be dispatched.
5671     * @return True if the event was handled by the view, false otherwise.
5672     */
5673    public boolean dispatchTouchEvent(MotionEvent event) {
5674        if (mInputEventConsistencyVerifier != null) {
5675            mInputEventConsistencyVerifier.onTouchEvent(event, 0);
5676        }
5677
5678        if (onFilterTouchEventForSecurity(event)) {
5679            //noinspection SimplifiableIfStatement
5680            ListenerInfo li = mListenerInfo;
5681            if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
5682                    && li.mOnTouchListener.onTouch(this, event)) {
5683                return true;
5684            }
5685
5686            if (onTouchEvent(event)) {
5687                return true;
5688            }
5689        }
5690
5691        if (mInputEventConsistencyVerifier != null) {
5692            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5693        }
5694        return false;
5695    }
5696
5697    /**
5698     * Filter the touch event to apply security policies.
5699     *
5700     * @param event The motion event to be filtered.
5701     * @return True if the event should be dispatched, false if the event should be dropped.
5702     *
5703     * @see #getFilterTouchesWhenObscured
5704     */
5705    public boolean onFilterTouchEventForSecurity(MotionEvent event) {
5706        //noinspection RedundantIfStatement
5707        if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0
5708                && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) {
5709            // Window is obscured, drop this touch.
5710            return false;
5711        }
5712        return true;
5713    }
5714
5715    /**
5716     * Pass a trackball motion event down to the focused view.
5717     *
5718     * @param event The motion event to be dispatched.
5719     * @return True if the event was handled by the view, false otherwise.
5720     */
5721    public boolean dispatchTrackballEvent(MotionEvent event) {
5722        if (mInputEventConsistencyVerifier != null) {
5723            mInputEventConsistencyVerifier.onTrackballEvent(event, 0);
5724        }
5725
5726        return onTrackballEvent(event);
5727    }
5728
5729    /**
5730     * Dispatch a generic motion event.
5731     * <p>
5732     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
5733     * are delivered to the view under the pointer.  All other generic motion events are
5734     * delivered to the focused view.  Hover events are handled specially and are delivered
5735     * to {@link #onHoverEvent(MotionEvent)}.
5736     * </p>
5737     *
5738     * @param event The motion event to be dispatched.
5739     * @return True if the event was handled by the view, false otherwise.
5740     */
5741    public boolean dispatchGenericMotionEvent(MotionEvent event) {
5742        if (mInputEventConsistencyVerifier != null) {
5743            mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0);
5744        }
5745
5746        final int source = event.getSource();
5747        if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
5748            final int action = event.getAction();
5749            if (action == MotionEvent.ACTION_HOVER_ENTER
5750                    || action == MotionEvent.ACTION_HOVER_MOVE
5751                    || action == MotionEvent.ACTION_HOVER_EXIT) {
5752                if (dispatchHoverEvent(event)) {
5753                    return true;
5754                }
5755            } else if (dispatchGenericPointerEvent(event)) {
5756                return true;
5757            }
5758        } else if (dispatchGenericFocusedEvent(event)) {
5759            return true;
5760        }
5761
5762        if (dispatchGenericMotionEventInternal(event)) {
5763            return true;
5764        }
5765
5766        if (mInputEventConsistencyVerifier != null) {
5767            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5768        }
5769        return false;
5770    }
5771
5772    private boolean dispatchGenericMotionEventInternal(MotionEvent event) {
5773        //noinspection SimplifiableIfStatement
5774        ListenerInfo li = mListenerInfo;
5775        if (li != null && li.mOnGenericMotionListener != null
5776                && (mViewFlags & ENABLED_MASK) == ENABLED
5777                && li.mOnGenericMotionListener.onGenericMotion(this, event)) {
5778            return true;
5779        }
5780
5781        if (onGenericMotionEvent(event)) {
5782            return true;
5783        }
5784
5785        if (mInputEventConsistencyVerifier != null) {
5786            mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
5787        }
5788        return false;
5789    }
5790
5791    /**
5792     * Dispatch a hover event.
5793     * <p>
5794     * Do not call this method directly.
5795     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5796     * </p>
5797     *
5798     * @param event The motion event to be dispatched.
5799     * @return True if the event was handled by the view, false otherwise.
5800     */
5801    protected boolean dispatchHoverEvent(MotionEvent event) {
5802        //noinspection SimplifiableIfStatement
5803        ListenerInfo li = mListenerInfo;
5804        if (li != null && li.mOnHoverListener != null
5805                && (mViewFlags & ENABLED_MASK) == ENABLED
5806                && li.mOnHoverListener.onHover(this, event)) {
5807            return true;
5808        }
5809
5810        return onHoverEvent(event);
5811    }
5812
5813    /**
5814     * Returns true if the view has a child to which it has recently sent
5815     * {@link MotionEvent#ACTION_HOVER_ENTER}.  If this view is hovered and
5816     * it does not have a hovered child, then it must be the innermost hovered view.
5817     * @hide
5818     */
5819    protected boolean hasHoveredChild() {
5820        return false;
5821    }
5822
5823    /**
5824     * Dispatch a generic motion event to the view under the first pointer.
5825     * <p>
5826     * Do not call this method directly.
5827     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5828     * </p>
5829     *
5830     * @param event The motion event to be dispatched.
5831     * @return True if the event was handled by the view, false otherwise.
5832     */
5833    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
5834        return false;
5835    }
5836
5837    /**
5838     * Dispatch a generic motion event to the currently focused view.
5839     * <p>
5840     * Do not call this method directly.
5841     * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead.
5842     * </p>
5843     *
5844     * @param event The motion event to be dispatched.
5845     * @return True if the event was handled by the view, false otherwise.
5846     */
5847    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
5848        return false;
5849    }
5850
5851    /**
5852     * Dispatch a pointer event.
5853     * <p>
5854     * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all
5855     * other events to {@link #onGenericMotionEvent(MotionEvent)}.  This separation of concerns
5856     * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches
5857     * and should not be expected to handle other pointing device features.
5858     * </p>
5859     *
5860     * @param event The motion event to be dispatched.
5861     * @return True if the event was handled by the view, false otherwise.
5862     * @hide
5863     */
5864    public final boolean dispatchPointerEvent(MotionEvent event) {
5865        if (event.isTouchEvent()) {
5866            return dispatchTouchEvent(event);
5867        } else {
5868            return dispatchGenericMotionEvent(event);
5869        }
5870    }
5871
5872    /**
5873     * Called when the window containing this view gains or loses window focus.
5874     * ViewGroups should override to route to their children.
5875     *
5876     * @param hasFocus True if the window containing this view now has focus,
5877     *        false otherwise.
5878     */
5879    public void dispatchWindowFocusChanged(boolean hasFocus) {
5880        onWindowFocusChanged(hasFocus);
5881    }
5882
5883    /**
5884     * Called when the window containing this view gains or loses focus.  Note
5885     * that this is separate from view focus: to receive key events, both
5886     * your view and its window must have focus.  If a window is displayed
5887     * on top of yours that takes input focus, then your own window will lose
5888     * focus but the view focus will remain unchanged.
5889     *
5890     * @param hasWindowFocus True if the window containing this view now has
5891     *        focus, false otherwise.
5892     */
5893    public void onWindowFocusChanged(boolean hasWindowFocus) {
5894        InputMethodManager imm = InputMethodManager.peekInstance();
5895        if (!hasWindowFocus) {
5896            if (isPressed()) {
5897                setPressed(false);
5898            }
5899            if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5900                imm.focusOut(this);
5901            }
5902            removeLongPressCallback();
5903            removeTapCallback();
5904            onFocusLost();
5905        } else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
5906            imm.focusIn(this);
5907        }
5908        refreshDrawableState();
5909    }
5910
5911    /**
5912     * Returns true if this view is in a window that currently has window focus.
5913     * Note that this is not the same as the view itself having focus.
5914     *
5915     * @return True if this view is in a window that currently has window focus.
5916     */
5917    public boolean hasWindowFocus() {
5918        return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
5919    }
5920
5921    /**
5922     * Dispatch a view visibility change down the view hierarchy.
5923     * ViewGroups should override to route to their children.
5924     * @param changedView The view whose visibility changed. Could be 'this' or
5925     * an ancestor view.
5926     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5927     * {@link #INVISIBLE} or {@link #GONE}.
5928     */
5929    protected void dispatchVisibilityChanged(View changedView, int visibility) {
5930        onVisibilityChanged(changedView, visibility);
5931    }
5932
5933    /**
5934     * Called when the visibility of the view or an ancestor of the view is changed.
5935     * @param changedView The view whose visibility changed. Could be 'this' or
5936     * an ancestor view.
5937     * @param visibility The new visibility of changedView: {@link #VISIBLE},
5938     * {@link #INVISIBLE} or {@link #GONE}.
5939     */
5940    protected void onVisibilityChanged(View changedView, int visibility) {
5941        if (visibility == VISIBLE) {
5942            if (mAttachInfo != null) {
5943                initialAwakenScrollBars();
5944            } else {
5945                mPrivateFlags |= AWAKEN_SCROLL_BARS_ON_ATTACH;
5946            }
5947        }
5948    }
5949
5950    /**
5951     * Dispatch a hint about whether this view is displayed. For instance, when
5952     * a View moves out of the screen, it might receives a display hint indicating
5953     * the view is not displayed. Applications should not <em>rely</em> on this hint
5954     * as there is no guarantee that they will receive one.
5955     *
5956     * @param hint A hint about whether or not this view is displayed:
5957     * {@link #VISIBLE} or {@link #INVISIBLE}.
5958     */
5959    public void dispatchDisplayHint(int hint) {
5960        onDisplayHint(hint);
5961    }
5962
5963    /**
5964     * Gives this view a hint about whether is displayed or not. For instance, when
5965     * a View moves out of the screen, it might receives a display hint indicating
5966     * the view is not displayed. Applications should not <em>rely</em> on this hint
5967     * as there is no guarantee that they will receive one.
5968     *
5969     * @param hint A hint about whether or not this view is displayed:
5970     * {@link #VISIBLE} or {@link #INVISIBLE}.
5971     */
5972    protected void onDisplayHint(int hint) {
5973    }
5974
5975    /**
5976     * Dispatch a window visibility change down the view hierarchy.
5977     * ViewGroups should override to route to their children.
5978     *
5979     * @param visibility The new visibility of the window.
5980     *
5981     * @see #onWindowVisibilityChanged(int)
5982     */
5983    public void dispatchWindowVisibilityChanged(int visibility) {
5984        onWindowVisibilityChanged(visibility);
5985    }
5986
5987    /**
5988     * Called when the window containing has change its visibility
5989     * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}).  Note
5990     * that this tells you whether or not your window is being made visible
5991     * to the window manager; this does <em>not</em> tell you whether or not
5992     * your window is obscured by other windows on the screen, even if it
5993     * is itself visible.
5994     *
5995     * @param visibility The new visibility of the window.
5996     */
5997    protected void onWindowVisibilityChanged(int visibility) {
5998        if (visibility == VISIBLE) {
5999            initialAwakenScrollBars();
6000        }
6001    }
6002
6003    /**
6004     * Returns the current visibility of the window this view is attached to
6005     * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
6006     *
6007     * @return Returns the current visibility of the view's window.
6008     */
6009    public int getWindowVisibility() {
6010        return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
6011    }
6012
6013    /**
6014     * Retrieve the overall visible display size in which the window this view is
6015     * attached to has been positioned in.  This takes into account screen
6016     * decorations above the window, for both cases where the window itself
6017     * is being position inside of them or the window is being placed under
6018     * then and covered insets are used for the window to position its content
6019     * inside.  In effect, this tells you the available area where content can
6020     * be placed and remain visible to users.
6021     *
6022     * <p>This function requires an IPC back to the window manager to retrieve
6023     * the requested information, so should not be used in performance critical
6024     * code like drawing.
6025     *
6026     * @param outRect Filled in with the visible display frame.  If the view
6027     * is not attached to a window, this is simply the raw display size.
6028     */
6029    public void getWindowVisibleDisplayFrame(Rect outRect) {
6030        if (mAttachInfo != null) {
6031            try {
6032                mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
6033            } catch (RemoteException e) {
6034                return;
6035            }
6036            // XXX This is really broken, and probably all needs to be done
6037            // in the window manager, and we need to know more about whether
6038            // we want the area behind or in front of the IME.
6039            final Rect insets = mAttachInfo.mVisibleInsets;
6040            outRect.left += insets.left;
6041            outRect.top += insets.top;
6042            outRect.right -= insets.right;
6043            outRect.bottom -= insets.bottom;
6044            return;
6045        }
6046        Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
6047        d.getRectSize(outRect);
6048    }
6049
6050    /**
6051     * Dispatch a notification about a resource configuration change down
6052     * the view hierarchy.
6053     * ViewGroups should override to route to their children.
6054     *
6055     * @param newConfig The new resource configuration.
6056     *
6057     * @see #onConfigurationChanged(android.content.res.Configuration)
6058     */
6059    public void dispatchConfigurationChanged(Configuration newConfig) {
6060        onConfigurationChanged(newConfig);
6061    }
6062
6063    /**
6064     * Called when the current configuration of the resources being used
6065     * by the application have changed.  You can use this to decide when
6066     * to reload resources that can changed based on orientation and other
6067     * configuration characterstics.  You only need to use this if you are
6068     * not relying on the normal {@link android.app.Activity} mechanism of
6069     * recreating the activity instance upon a configuration change.
6070     *
6071     * @param newConfig The new resource configuration.
6072     */
6073    protected void onConfigurationChanged(Configuration newConfig) {
6074    }
6075
6076    /**
6077     * Private function to aggregate all per-view attributes in to the view
6078     * root.
6079     */
6080    void dispatchCollectViewAttributes(int visibility) {
6081        performCollectViewAttributes(visibility);
6082    }
6083
6084    void performCollectViewAttributes(int visibility) {
6085        if ((visibility & VISIBILITY_MASK) == VISIBLE && mAttachInfo != null) {
6086            if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) {
6087                mAttachInfo.mKeepScreenOn = true;
6088            }
6089            mAttachInfo.mSystemUiVisibility |= mSystemUiVisibility;
6090            ListenerInfo li = mListenerInfo;
6091            if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
6092                mAttachInfo.mHasSystemUiListeners = true;
6093            }
6094        }
6095    }
6096
6097    void needGlobalAttributesUpdate(boolean force) {
6098        final AttachInfo ai = mAttachInfo;
6099        if (ai != null) {
6100            if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0)
6101                    || ai.mHasSystemUiListeners) {
6102                ai.mRecomputeGlobalAttributes = true;
6103            }
6104        }
6105    }
6106
6107    /**
6108     * Returns whether the device is currently in touch mode.  Touch mode is entered
6109     * once the user begins interacting with the device by touch, and affects various
6110     * things like whether focus is always visible to the user.
6111     *
6112     * @return Whether the device is in touch mode.
6113     */
6114    @ViewDebug.ExportedProperty
6115    public boolean isInTouchMode() {
6116        if (mAttachInfo != null) {
6117            return mAttachInfo.mInTouchMode;
6118        } else {
6119            return ViewRootImpl.isInTouchMode();
6120        }
6121    }
6122
6123    /**
6124     * Returns the context the view is running in, through which it can
6125     * access the current theme, resources, etc.
6126     *
6127     * @return The view's Context.
6128     */
6129    @ViewDebug.CapturedViewProperty
6130    public final Context getContext() {
6131        return mContext;
6132    }
6133
6134    /**
6135     * Handle a key event before it is processed by any input method
6136     * associated with the view hierarchy.  This can be used to intercept
6137     * key events in special situations before the IME consumes them; a
6138     * typical example would be handling the BACK key to update the application's
6139     * UI instead of allowing the IME to see it and close itself.
6140     *
6141     * @param keyCode The value in event.getKeyCode().
6142     * @param event Description of the key event.
6143     * @return If you handled the event, return true. If you want to allow the
6144     *         event to be handled by the next receiver, return false.
6145     */
6146    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
6147        return false;
6148    }
6149
6150    /**
6151     * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent)
6152     * KeyEvent.Callback.onKeyDown()}: perform press of the view
6153     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
6154     * is released, if the view is enabled and clickable.
6155     *
6156     * @param keyCode A key code that represents the button pressed, from
6157     *                {@link android.view.KeyEvent}.
6158     * @param event   The KeyEvent object that defines the button action.
6159     */
6160    public boolean onKeyDown(int keyCode, KeyEvent event) {
6161        boolean result = false;
6162
6163        switch (keyCode) {
6164            case KeyEvent.KEYCODE_DPAD_CENTER:
6165            case KeyEvent.KEYCODE_ENTER: {
6166                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6167                    return true;
6168                }
6169                // Long clickable items don't necessarily have to be clickable
6170                if (((mViewFlags & CLICKABLE) == CLICKABLE ||
6171                        (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
6172                        (event.getRepeatCount() == 0)) {
6173                    setPressed(true);
6174                    checkForLongClick(0);
6175                    return true;
6176                }
6177                break;
6178            }
6179        }
6180        return result;
6181    }
6182
6183    /**
6184     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
6185     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
6186     * the event).
6187     */
6188    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
6189        return false;
6190    }
6191
6192    /**
6193     * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent)
6194     * KeyEvent.Callback.onKeyUp()}: perform clicking of the view
6195     * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
6196     * {@link KeyEvent#KEYCODE_ENTER} is released.
6197     *
6198     * @param keyCode A key code that represents the button pressed, from
6199     *                {@link android.view.KeyEvent}.
6200     * @param event   The KeyEvent object that defines the button action.
6201     */
6202    public boolean onKeyUp(int keyCode, KeyEvent event) {
6203        boolean result = false;
6204
6205        switch (keyCode) {
6206            case KeyEvent.KEYCODE_DPAD_CENTER:
6207            case KeyEvent.KEYCODE_ENTER: {
6208                if ((mViewFlags & ENABLED_MASK) == DISABLED) {
6209                    return true;
6210                }
6211                if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
6212                    setPressed(false);
6213
6214                    if (!mHasPerformedLongPress) {
6215                        // This is a tap, so remove the longpress check
6216                        removeLongPressCallback();
6217
6218                        result = performClick();
6219                    }
6220                }
6221                break;
6222            }
6223        }
6224        return result;
6225    }
6226
6227    /**
6228     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
6229     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
6230     * the event).
6231     *
6232     * @param keyCode     A key code that represents the button pressed, from
6233     *                    {@link android.view.KeyEvent}.
6234     * @param repeatCount The number of times the action was made.
6235     * @param event       The KeyEvent object that defines the button action.
6236     */
6237    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
6238        return false;
6239    }
6240
6241    /**
6242     * Called on the focused view when a key shortcut event is not handled.
6243     * Override this method to implement local key shortcuts for the View.
6244     * Key shortcuts can also be implemented by setting the
6245     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
6246     *
6247     * @param keyCode The value in event.getKeyCode().
6248     * @param event Description of the key event.
6249     * @return If you handled the event, return true. If you want to allow the
6250     *         event to be handled by the next receiver, return false.
6251     */
6252    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
6253        return false;
6254    }
6255
6256    /**
6257     * Check whether the called view is a text editor, in which case it
6258     * would make sense to automatically display a soft input window for
6259     * it.  Subclasses should override this if they implement
6260     * {@link #onCreateInputConnection(EditorInfo)} to return true if
6261     * a call on that method would return a non-null InputConnection, and
6262     * they are really a first-class editor that the user would normally
6263     * start typing on when the go into a window containing your view.
6264     *
6265     * <p>The default implementation always returns false.  This does
6266     * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
6267     * will not be called or the user can not otherwise perform edits on your
6268     * view; it is just a hint to the system that this is not the primary
6269     * purpose of this view.
6270     *
6271     * @return Returns true if this view is a text editor, else false.
6272     */
6273    public boolean onCheckIsTextEditor() {
6274        return false;
6275    }
6276
6277    /**
6278     * Create a new InputConnection for an InputMethod to interact
6279     * with the view.  The default implementation returns null, since it doesn't
6280     * support input methods.  You can override this to implement such support.
6281     * This is only needed for views that take focus and text input.
6282     *
6283     * <p>When implementing this, you probably also want to implement
6284     * {@link #onCheckIsTextEditor()} to indicate you will return a
6285     * non-null InputConnection.
6286     *
6287     * @param outAttrs Fill in with attribute information about the connection.
6288     */
6289    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
6290        return null;
6291    }
6292
6293    /**
6294     * Called by the {@link android.view.inputmethod.InputMethodManager}
6295     * when a view who is not the current
6296     * input connection target is trying to make a call on the manager.  The
6297     * default implementation returns false; you can override this to return
6298     * true for certain views if you are performing InputConnection proxying
6299     * to them.
6300     * @param view The View that is making the InputMethodManager call.
6301     * @return Return true to allow the call, false to reject.
6302     */
6303    public boolean checkInputConnectionProxy(View view) {
6304        return false;
6305    }
6306
6307    /**
6308     * Show the context menu for this view. It is not safe to hold on to the
6309     * menu after returning from this method.
6310     *
6311     * You should normally not overload this method. Overload
6312     * {@link #onCreateContextMenu(ContextMenu)} or define an
6313     * {@link OnCreateContextMenuListener} to add items to the context menu.
6314     *
6315     * @param menu The context menu to populate
6316     */
6317    public void createContextMenu(ContextMenu menu) {
6318        ContextMenuInfo menuInfo = getContextMenuInfo();
6319
6320        // Sets the current menu info so all items added to menu will have
6321        // my extra info set.
6322        ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
6323
6324        onCreateContextMenu(menu);
6325        ListenerInfo li = mListenerInfo;
6326        if (li != null && li.mOnCreateContextMenuListener != null) {
6327            li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
6328        }
6329
6330        // Clear the extra information so subsequent items that aren't mine don't
6331        // have my extra info.
6332        ((MenuBuilder)menu).setCurrentMenuInfo(null);
6333
6334        if (mParent != null) {
6335            mParent.createContextMenu(menu);
6336        }
6337    }
6338
6339    /**
6340     * Views should implement this if they have extra information to associate
6341     * with the context menu. The return result is supplied as a parameter to
6342     * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
6343     * callback.
6344     *
6345     * @return Extra information about the item for which the context menu
6346     *         should be shown. This information will vary across different
6347     *         subclasses of View.
6348     */
6349    protected ContextMenuInfo getContextMenuInfo() {
6350        return null;
6351    }
6352
6353    /**
6354     * Views should implement this if the view itself is going to add items to
6355     * the context menu.
6356     *
6357     * @param menu the context menu to populate
6358     */
6359    protected void onCreateContextMenu(ContextMenu menu) {
6360    }
6361
6362    /**
6363     * Implement this method to handle trackball motion events.  The
6364     * <em>relative</em> movement of the trackball since the last event
6365     * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
6366     * {@link MotionEvent#getY MotionEvent.getY()}.  These are normalized so
6367     * that a movement of 1 corresponds to the user pressing one DPAD key (so
6368     * they will often be fractional values, representing the more fine-grained
6369     * movement information available from a trackball).
6370     *
6371     * @param event The motion event.
6372     * @return True if the event was handled, false otherwise.
6373     */
6374    public boolean onTrackballEvent(MotionEvent event) {
6375        return false;
6376    }
6377
6378    /**
6379     * Implement this method to handle generic motion events.
6380     * <p>
6381     * Generic motion events describe joystick movements, mouse hovers, track pad
6382     * touches, scroll wheel movements and other input events.  The
6383     * {@link MotionEvent#getSource() source} of the motion event specifies
6384     * the class of input that was received.  Implementations of this method
6385     * must examine the bits in the source before processing the event.
6386     * The following code example shows how this is done.
6387     * </p><p>
6388     * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER}
6389     * are delivered to the view under the pointer.  All other generic motion events are
6390     * delivered to the focused view.
6391     * </p>
6392     * <pre> public boolean onGenericMotionEvent(MotionEvent event) {
6393     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
6394     *         if (event.getAction() == MotionEvent.ACTION_MOVE) {
6395     *             // process the joystick movement...
6396     *             return true;
6397     *         }
6398     *     }
6399     *     if ((event.getSource() &amp; InputDevice.SOURCE_CLASS_POINTER) != 0) {
6400     *         switch (event.getAction()) {
6401     *             case MotionEvent.ACTION_HOVER_MOVE:
6402     *                 // process the mouse hover movement...
6403     *                 return true;
6404     *             case MotionEvent.ACTION_SCROLL:
6405     *                 // process the scroll wheel movement...
6406     *                 return true;
6407     *         }
6408     *     }
6409     *     return super.onGenericMotionEvent(event);
6410     * }</pre>
6411     *
6412     * @param event The generic motion event being processed.
6413     * @return True if the event was handled, false otherwise.
6414     */
6415    public boolean onGenericMotionEvent(MotionEvent event) {
6416        return false;
6417    }
6418
6419    /**
6420     * Implement this method to handle hover events.
6421     * <p>
6422     * This method is called whenever a pointer is hovering into, over, or out of the
6423     * bounds of a view and the view is not currently being touched.
6424     * Hover events are represented as pointer events with action
6425     * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE},
6426     * or {@link MotionEvent#ACTION_HOVER_EXIT}.
6427     * </p>
6428     * <ul>
6429     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER}
6430     * when the pointer enters the bounds of the view.</li>
6431     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE}
6432     * when the pointer has already entered the bounds of the view and has moved.</li>
6433     * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT}
6434     * when the pointer has exited the bounds of the view or when the pointer is
6435     * about to go down due to a button click, tap, or similar user action that
6436     * causes the view to be touched.</li>
6437     * </ul>
6438     * <p>
6439     * The view should implement this method to return true to indicate that it is
6440     * handling the hover event, such as by changing its drawable state.
6441     * </p><p>
6442     * The default implementation calls {@link #setHovered} to update the hovered state
6443     * of the view when a hover enter or hover exit event is received, if the view
6444     * is enabled and is clickable.  The default implementation also sends hover
6445     * accessibility events.
6446     * </p>
6447     *
6448     * @param event The motion event that describes the hover.
6449     * @return True if the view handled the hover event.
6450     *
6451     * @see #isHovered
6452     * @see #setHovered
6453     * @see #onHoverChanged
6454     */
6455    public boolean onHoverEvent(MotionEvent event) {
6456        // The root view may receive hover (or touch) events that are outside the bounds of
6457        // the window.  This code ensures that we only send accessibility events for
6458        // hovers that are actually within the bounds of the root view.
6459        final int action = event.getAction();
6460        if (!mSendingHoverAccessibilityEvents) {
6461            if ((action == MotionEvent.ACTION_HOVER_ENTER
6462                    || action == MotionEvent.ACTION_HOVER_MOVE)
6463                    && !hasHoveredChild()
6464                    && pointInView(event.getX(), event.getY())) {
6465                mSendingHoverAccessibilityEvents = true;
6466                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
6467            }
6468        } else {
6469            if (action == MotionEvent.ACTION_HOVER_EXIT
6470                    || (action == MotionEvent.ACTION_HOVER_MOVE
6471                            && !pointInView(event.getX(), event.getY()))) {
6472                mSendingHoverAccessibilityEvents = false;
6473                sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
6474            }
6475        }
6476
6477        if (isHoverable()) {
6478            switch (action) {
6479                case MotionEvent.ACTION_HOVER_ENTER:
6480                    setHovered(true);
6481                    break;
6482                case MotionEvent.ACTION_HOVER_EXIT:
6483                    setHovered(false);
6484                    break;
6485            }
6486
6487            // Dispatch the event to onGenericMotionEvent before returning true.
6488            // This is to provide compatibility with existing applications that
6489            // handled HOVER_MOVE events in onGenericMotionEvent and that would
6490            // break because of the new default handling for hoverable views
6491            // in onHoverEvent.
6492            // Note that onGenericMotionEvent will be called by default when
6493            // onHoverEvent returns false (refer to dispatchGenericMotionEvent).
6494            dispatchGenericMotionEventInternal(event);
6495            return true;
6496        }
6497        return false;
6498    }
6499
6500    /**
6501     * Returns true if the view should handle {@link #onHoverEvent}
6502     * by calling {@link #setHovered} to change its hovered state.
6503     *
6504     * @return True if the view is hoverable.
6505     */
6506    private boolean isHoverable() {
6507        final int viewFlags = mViewFlags;
6508        //noinspection SimplifiableIfStatement
6509        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6510            return false;
6511        }
6512
6513        return (viewFlags & CLICKABLE) == CLICKABLE
6514                || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
6515    }
6516
6517    /**
6518     * Returns true if the view is currently hovered.
6519     *
6520     * @return True if the view is currently hovered.
6521     *
6522     * @see #setHovered
6523     * @see #onHoverChanged
6524     */
6525    @ViewDebug.ExportedProperty
6526    public boolean isHovered() {
6527        return (mPrivateFlags & HOVERED) != 0;
6528    }
6529
6530    /**
6531     * Sets whether the view is currently hovered.
6532     * <p>
6533     * Calling this method also changes the drawable state of the view.  This
6534     * enables the view to react to hover by using different drawable resources
6535     * to change its appearance.
6536     * </p><p>
6537     * The {@link #onHoverChanged} method is called when the hovered state changes.
6538     * </p>
6539     *
6540     * @param hovered True if the view is hovered.
6541     *
6542     * @see #isHovered
6543     * @see #onHoverChanged
6544     */
6545    public void setHovered(boolean hovered) {
6546        if (hovered) {
6547            if ((mPrivateFlags & HOVERED) == 0) {
6548                mPrivateFlags |= HOVERED;
6549                refreshDrawableState();
6550                onHoverChanged(true);
6551            }
6552        } else {
6553            if ((mPrivateFlags & HOVERED) != 0) {
6554                mPrivateFlags &= ~HOVERED;
6555                refreshDrawableState();
6556                onHoverChanged(false);
6557            }
6558        }
6559    }
6560
6561    /**
6562     * Implement this method to handle hover state changes.
6563     * <p>
6564     * This method is called whenever the hover state changes as a result of a
6565     * call to {@link #setHovered}.
6566     * </p>
6567     *
6568     * @param hovered The current hover state, as returned by {@link #isHovered}.
6569     *
6570     * @see #isHovered
6571     * @see #setHovered
6572     */
6573    public void onHoverChanged(boolean hovered) {
6574    }
6575
6576    /**
6577     * Implement this method to handle touch screen motion events.
6578     *
6579     * @param event The motion event.
6580     * @return True if the event was handled, false otherwise.
6581     */
6582    public boolean onTouchEvent(MotionEvent event) {
6583        final int viewFlags = mViewFlags;
6584
6585        if ((viewFlags & ENABLED_MASK) == DISABLED) {
6586            if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PRESSED) != 0) {
6587                setPressed(false);
6588            }
6589            // A disabled view that is clickable still consumes the touch
6590            // events, it just doesn't respond to them.
6591            return (((viewFlags & CLICKABLE) == CLICKABLE ||
6592                    (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
6593        }
6594
6595        if (mTouchDelegate != null) {
6596            if (mTouchDelegate.onTouchEvent(event)) {
6597                return true;
6598            }
6599        }
6600
6601        if (((viewFlags & CLICKABLE) == CLICKABLE ||
6602                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
6603            switch (event.getAction()) {
6604                case MotionEvent.ACTION_UP:
6605                    boolean prepressed = (mPrivateFlags & PREPRESSED) != 0;
6606                    if ((mPrivateFlags & PRESSED) != 0 || prepressed) {
6607                        // take focus if we don't have it already and we should in
6608                        // touch mode.
6609                        boolean focusTaken = false;
6610                        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
6611                            focusTaken = requestFocus();
6612                        }
6613
6614                        if (prepressed) {
6615                            // The button is being released before we actually
6616                            // showed it as pressed.  Make it show the pressed
6617                            // state now (before scheduling the click) to ensure
6618                            // the user sees it.
6619                            setPressed(true);
6620                       }
6621
6622                        if (!mHasPerformedLongPress) {
6623                            // This is a tap, so remove the longpress check
6624                            removeLongPressCallback();
6625
6626                            // Only perform take click actions if we were in the pressed state
6627                            if (!focusTaken) {
6628                                // Use a Runnable and post this rather than calling
6629                                // performClick directly. This lets other visual state
6630                                // of the view update before click actions start.
6631                                if (mPerformClick == null) {
6632                                    mPerformClick = new PerformClick();
6633                                }
6634                                if (!post(mPerformClick)) {
6635                                    performClick();
6636                                }
6637                            }
6638                        }
6639
6640                        if (mUnsetPressedState == null) {
6641                            mUnsetPressedState = new UnsetPressedState();
6642                        }
6643
6644                        if (prepressed) {
6645                            postDelayed(mUnsetPressedState,
6646                                    ViewConfiguration.getPressedStateDuration());
6647                        } else if (!post(mUnsetPressedState)) {
6648                            // If the post failed, unpress right now
6649                            mUnsetPressedState.run();
6650                        }
6651                        removeTapCallback();
6652                    }
6653                    break;
6654
6655                case MotionEvent.ACTION_DOWN:
6656                    mHasPerformedLongPress = false;
6657
6658                    if (performButtonActionOnTouchDown(event)) {
6659                        break;
6660                    }
6661
6662                    // Walk up the hierarchy to determine if we're inside a scrolling container.
6663                    boolean isInScrollingContainer = isInScrollingContainer();
6664
6665                    // For views inside a scrolling container, delay the pressed feedback for
6666                    // a short period in case this is a scroll.
6667                    if (isInScrollingContainer) {
6668                        mPrivateFlags |= PREPRESSED;
6669                        if (mPendingCheckForTap == null) {
6670                            mPendingCheckForTap = new CheckForTap();
6671                        }
6672                        postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
6673                    } else {
6674                        // Not inside a scrolling container, so show the feedback right away
6675                        setPressed(true);
6676                        checkForLongClick(0);
6677                    }
6678                    break;
6679
6680                case MotionEvent.ACTION_CANCEL:
6681                    setPressed(false);
6682                    removeTapCallback();
6683                    break;
6684
6685                case MotionEvent.ACTION_MOVE:
6686                    final int x = (int) event.getX();
6687                    final int y = (int) event.getY();
6688
6689                    // Be lenient about moving outside of buttons
6690                    if (!pointInView(x, y, mTouchSlop)) {
6691                        // Outside button
6692                        removeTapCallback();
6693                        if ((mPrivateFlags & PRESSED) != 0) {
6694                            // Remove any future long press/tap checks
6695                            removeLongPressCallback();
6696
6697                            setPressed(false);
6698                        }
6699                    }
6700                    break;
6701            }
6702            return true;
6703        }
6704
6705        return false;
6706    }
6707
6708    /**
6709     * @hide
6710     */
6711    public boolean isInScrollingContainer() {
6712        ViewParent p = getParent();
6713        while (p != null && p instanceof ViewGroup) {
6714            if (((ViewGroup) p).shouldDelayChildPressedState()) {
6715                return true;
6716            }
6717            p = p.getParent();
6718        }
6719        return false;
6720    }
6721
6722    /**
6723     * Remove the longpress detection timer.
6724     */
6725    private void removeLongPressCallback() {
6726        if (mPendingCheckForLongPress != null) {
6727          removeCallbacks(mPendingCheckForLongPress);
6728        }
6729    }
6730
6731    /**
6732     * Remove the pending click action
6733     */
6734    private void removePerformClickCallback() {
6735        if (mPerformClick != null) {
6736            removeCallbacks(mPerformClick);
6737        }
6738    }
6739
6740    /**
6741     * Remove the prepress detection timer.
6742     */
6743    private void removeUnsetPressCallback() {
6744        if ((mPrivateFlags & PRESSED) != 0 && mUnsetPressedState != null) {
6745            setPressed(false);
6746            removeCallbacks(mUnsetPressedState);
6747        }
6748    }
6749
6750    /**
6751     * Remove the tap detection timer.
6752     */
6753    private void removeTapCallback() {
6754        if (mPendingCheckForTap != null) {
6755            mPrivateFlags &= ~PREPRESSED;
6756            removeCallbacks(mPendingCheckForTap);
6757        }
6758    }
6759
6760    /**
6761     * Cancels a pending long press.  Your subclass can use this if you
6762     * want the context menu to come up if the user presses and holds
6763     * at the same place, but you don't want it to come up if they press
6764     * and then move around enough to cause scrolling.
6765     */
6766    public void cancelLongPress() {
6767        removeLongPressCallback();
6768
6769        /*
6770         * The prepressed state handled by the tap callback is a display
6771         * construct, but the tap callback will post a long press callback
6772         * less its own timeout. Remove it here.
6773         */
6774        removeTapCallback();
6775    }
6776
6777    /**
6778     * Remove the pending callback for sending a
6779     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
6780     */
6781    private void removeSendViewScrolledAccessibilityEventCallback() {
6782        if (mSendViewScrolledAccessibilityEvent != null) {
6783            removeCallbacks(mSendViewScrolledAccessibilityEvent);
6784        }
6785    }
6786
6787    /**
6788     * Sets the TouchDelegate for this View.
6789     */
6790    public void setTouchDelegate(TouchDelegate delegate) {
6791        mTouchDelegate = delegate;
6792    }
6793
6794    /**
6795     * Gets the TouchDelegate for this View.
6796     */
6797    public TouchDelegate getTouchDelegate() {
6798        return mTouchDelegate;
6799    }
6800
6801    /**
6802     * Set flags controlling behavior of this view.
6803     *
6804     * @param flags Constant indicating the value which should be set
6805     * @param mask Constant indicating the bit range that should be changed
6806     */
6807    void setFlags(int flags, int mask) {
6808        int old = mViewFlags;
6809        mViewFlags = (mViewFlags & ~mask) | (flags & mask);
6810
6811        int changed = mViewFlags ^ old;
6812        if (changed == 0) {
6813            return;
6814        }
6815        int privateFlags = mPrivateFlags;
6816
6817        /* Check if the FOCUSABLE bit has changed */
6818        if (((changed & FOCUSABLE_MASK) != 0) &&
6819                ((privateFlags & HAS_BOUNDS) !=0)) {
6820            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
6821                    && ((privateFlags & FOCUSED) != 0)) {
6822                /* Give up focus if we are no longer focusable */
6823                clearFocus();
6824            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
6825                    && ((privateFlags & FOCUSED) == 0)) {
6826                /*
6827                 * Tell the view system that we are now available to take focus
6828                 * if no one else already has it.
6829                 */
6830                if (mParent != null) mParent.focusableViewAvailable(this);
6831            }
6832        }
6833
6834        if ((flags & VISIBILITY_MASK) == VISIBLE) {
6835            if ((changed & VISIBILITY_MASK) != 0) {
6836                /*
6837                 * If this view is becoming visible, invalidate it in case it changed while
6838                 * it was not visible. Marking it drawn ensures that the invalidation will
6839                 * go through.
6840                 */
6841                mPrivateFlags |= DRAWN;
6842                invalidate(true);
6843
6844                needGlobalAttributesUpdate(true);
6845
6846                // a view becoming visible is worth notifying the parent
6847                // about in case nothing has focus.  even if this specific view
6848                // isn't focusable, it may contain something that is, so let
6849                // the root view try to give this focus if nothing else does.
6850                if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
6851                    mParent.focusableViewAvailable(this);
6852                }
6853            }
6854        }
6855
6856        /* Check if the GONE bit has changed */
6857        if ((changed & GONE) != 0) {
6858            needGlobalAttributesUpdate(false);
6859            requestLayout();
6860
6861            if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
6862                if (hasFocus()) clearFocus();
6863                destroyDrawingCache();
6864                if (mParent instanceof View) {
6865                    // GONE views noop invalidation, so invalidate the parent
6866                    ((View) mParent).invalidate(true);
6867                }
6868                // Mark the view drawn to ensure that it gets invalidated properly the next
6869                // time it is visible and gets invalidated
6870                mPrivateFlags |= DRAWN;
6871            }
6872            if (mAttachInfo != null) {
6873                mAttachInfo.mViewVisibilityChanged = true;
6874            }
6875        }
6876
6877        /* Check if the VISIBLE bit has changed */
6878        if ((changed & INVISIBLE) != 0) {
6879            needGlobalAttributesUpdate(false);
6880            /*
6881             * If this view is becoming invisible, set the DRAWN flag so that
6882             * the next invalidate() will not be skipped.
6883             */
6884            mPrivateFlags |= DRAWN;
6885
6886            if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
6887                // root view becoming invisible shouldn't clear focus
6888                if (getRootView() != this) {
6889                    clearFocus();
6890                }
6891            }
6892            if (mAttachInfo != null) {
6893                mAttachInfo.mViewVisibilityChanged = true;
6894            }
6895        }
6896
6897        if ((changed & VISIBILITY_MASK) != 0) {
6898            if (mParent instanceof ViewGroup) {
6899                ((ViewGroup) mParent).onChildVisibilityChanged(this,
6900                        (changed & VISIBILITY_MASK), (flags & VISIBILITY_MASK));
6901                ((View) mParent).invalidate(true);
6902            } else if (mParent != null) {
6903                mParent.invalidateChild(this, null);
6904            }
6905            dispatchVisibilityChanged(this, (flags & VISIBILITY_MASK));
6906        }
6907
6908        if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
6909            destroyDrawingCache();
6910        }
6911
6912        if ((changed & DRAWING_CACHE_ENABLED) != 0) {
6913            destroyDrawingCache();
6914            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6915            invalidateParentCaches();
6916        }
6917
6918        if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
6919            destroyDrawingCache();
6920            mPrivateFlags &= ~DRAWING_CACHE_VALID;
6921        }
6922
6923        if ((changed & DRAW_MASK) != 0) {
6924            if ((mViewFlags & WILL_NOT_DRAW) != 0) {
6925                if (mBGDrawable != null) {
6926                    mPrivateFlags &= ~SKIP_DRAW;
6927                    mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
6928                } else {
6929                    mPrivateFlags |= SKIP_DRAW;
6930                }
6931            } else {
6932                mPrivateFlags &= ~SKIP_DRAW;
6933            }
6934            requestLayout();
6935            invalidate(true);
6936        }
6937
6938        if ((changed & KEEP_SCREEN_ON) != 0) {
6939            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
6940                mParent.recomputeViewAttributes(this);
6941            }
6942        }
6943
6944        if ((changed & LAYOUT_DIRECTION_MASK) != 0) {
6945            requestLayout();
6946        }
6947    }
6948
6949    /**
6950     * Change the view's z order in the tree, so it's on top of other sibling
6951     * views
6952     */
6953    public void bringToFront() {
6954        if (mParent != null) {
6955            mParent.bringChildToFront(this);
6956        }
6957    }
6958
6959    /**
6960     * This is called in response to an internal scroll in this view (i.e., the
6961     * view scrolled its own contents). This is typically as a result of
6962     * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
6963     * called.
6964     *
6965     * @param l Current horizontal scroll origin.
6966     * @param t Current vertical scroll origin.
6967     * @param oldl Previous horizontal scroll origin.
6968     * @param oldt Previous vertical scroll origin.
6969     */
6970    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
6971        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
6972            postSendViewScrolledAccessibilityEventCallback();
6973        }
6974
6975        mBackgroundSizeChanged = true;
6976
6977        final AttachInfo ai = mAttachInfo;
6978        if (ai != null) {
6979            ai.mViewScrollChanged = true;
6980        }
6981    }
6982
6983    /**
6984     * Interface definition for a callback to be invoked when the layout bounds of a view
6985     * changes due to layout processing.
6986     */
6987    public interface OnLayoutChangeListener {
6988        /**
6989         * Called when the focus state of a view has changed.
6990         *
6991         * @param v The view whose state has changed.
6992         * @param left The new value of the view's left property.
6993         * @param top The new value of the view's top property.
6994         * @param right The new value of the view's right property.
6995         * @param bottom The new value of the view's bottom property.
6996         * @param oldLeft The previous value of the view's left property.
6997         * @param oldTop The previous value of the view's top property.
6998         * @param oldRight The previous value of the view's right property.
6999         * @param oldBottom The previous value of the view's bottom property.
7000         */
7001        void onLayoutChange(View v, int left, int top, int right, int bottom,
7002            int oldLeft, int oldTop, int oldRight, int oldBottom);
7003    }
7004
7005    /**
7006     * This is called during layout when the size of this view has changed. If
7007     * you were just added to the view hierarchy, you're called with the old
7008     * values of 0.
7009     *
7010     * @param w Current width of this view.
7011     * @param h Current height of this view.
7012     * @param oldw Old width of this view.
7013     * @param oldh Old height of this view.
7014     */
7015    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
7016    }
7017
7018    /**
7019     * Called by draw to draw the child views. This may be overridden
7020     * by derived classes to gain control just before its children are drawn
7021     * (but after its own view has been drawn).
7022     * @param canvas the canvas on which to draw the view
7023     */
7024    protected void dispatchDraw(Canvas canvas) {
7025    }
7026
7027    /**
7028     * Gets the parent of this view. Note that the parent is a
7029     * ViewParent and not necessarily a View.
7030     *
7031     * @return Parent of this view.
7032     */
7033    public final ViewParent getParent() {
7034        return mParent;
7035    }
7036
7037    /**
7038     * Set the horizontal scrolled position of your view. This will cause a call to
7039     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7040     * invalidated.
7041     * @param value the x position to scroll to
7042     */
7043    public void setScrollX(int value) {
7044        scrollTo(value, mScrollY);
7045    }
7046
7047    /**
7048     * Set the vertical scrolled position of your view. This will cause a call to
7049     * {@link #onScrollChanged(int, int, int, int)} and the view will be
7050     * invalidated.
7051     * @param value the y position to scroll to
7052     */
7053    public void setScrollY(int value) {
7054        scrollTo(mScrollX, value);
7055    }
7056
7057    /**
7058     * Return the scrolled left position of this view. This is the left edge of
7059     * the displayed part of your view. You do not need to draw any pixels
7060     * farther left, since those are outside of the frame of your view on
7061     * screen.
7062     *
7063     * @return The left edge of the displayed part of your view, in pixels.
7064     */
7065    public final int getScrollX() {
7066        return mScrollX;
7067    }
7068
7069    /**
7070     * Return the scrolled top position of this view. This is the top edge of
7071     * the displayed part of your view. You do not need to draw any pixels above
7072     * it, since those are outside of the frame of your view on screen.
7073     *
7074     * @return The top edge of the displayed part of your view, in pixels.
7075     */
7076    public final int getScrollY() {
7077        return mScrollY;
7078    }
7079
7080    /**
7081     * Return the width of the your view.
7082     *
7083     * @return The width of your view, in pixels.
7084     */
7085    @ViewDebug.ExportedProperty(category = "layout")
7086    public final int getWidth() {
7087        return mRight - mLeft;
7088    }
7089
7090    /**
7091     * Return the height of your view.
7092     *
7093     * @return The height of your view, in pixels.
7094     */
7095    @ViewDebug.ExportedProperty(category = "layout")
7096    public final int getHeight() {
7097        return mBottom - mTop;
7098    }
7099
7100    /**
7101     * Return the visible drawing bounds of your view. Fills in the output
7102     * rectangle with the values from getScrollX(), getScrollY(),
7103     * getWidth(), and getHeight().
7104     *
7105     * @param outRect The (scrolled) drawing bounds of the view.
7106     */
7107    public void getDrawingRect(Rect outRect) {
7108        outRect.left = mScrollX;
7109        outRect.top = mScrollY;
7110        outRect.right = mScrollX + (mRight - mLeft);
7111        outRect.bottom = mScrollY + (mBottom - mTop);
7112    }
7113
7114    /**
7115     * Like {@link #getMeasuredWidthAndState()}, but only returns the
7116     * raw width component (that is the result is masked by
7117     * {@link #MEASURED_SIZE_MASK}).
7118     *
7119     * @return The raw measured width of this view.
7120     */
7121    public final int getMeasuredWidth() {
7122        return mMeasuredWidth & MEASURED_SIZE_MASK;
7123    }
7124
7125    /**
7126     * Return the full width measurement information for this view as computed
7127     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7128     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7129     * This should be used during measurement and layout calculations only. Use
7130     * {@link #getWidth()} to see how wide a view is after layout.
7131     *
7132     * @return The measured width of this view as a bit mask.
7133     */
7134    public final int getMeasuredWidthAndState() {
7135        return mMeasuredWidth;
7136    }
7137
7138    /**
7139     * Like {@link #getMeasuredHeightAndState()}, but only returns the
7140     * raw width component (that is the result is masked by
7141     * {@link #MEASURED_SIZE_MASK}).
7142     *
7143     * @return The raw measured height of this view.
7144     */
7145    public final int getMeasuredHeight() {
7146        return mMeasuredHeight & MEASURED_SIZE_MASK;
7147    }
7148
7149    /**
7150     * Return the full height measurement information for this view as computed
7151     * by the most recent call to {@link #measure(int, int)}.  This result is a bit mask
7152     * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
7153     * This should be used during measurement and layout calculations only. Use
7154     * {@link #getHeight()} to see how wide a view is after layout.
7155     *
7156     * @return The measured width of this view as a bit mask.
7157     */
7158    public final int getMeasuredHeightAndState() {
7159        return mMeasuredHeight;
7160    }
7161
7162    /**
7163     * Return only the state bits of {@link #getMeasuredWidthAndState()}
7164     * and {@link #getMeasuredHeightAndState()}, combined into one integer.
7165     * The width component is in the regular bits {@link #MEASURED_STATE_MASK}
7166     * and the height component is at the shifted bits
7167     * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}.
7168     */
7169    public final int getMeasuredState() {
7170        return (mMeasuredWidth&MEASURED_STATE_MASK)
7171                | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT)
7172                        & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
7173    }
7174
7175    /**
7176     * The transform matrix of this view, which is calculated based on the current
7177     * roation, scale, and pivot properties.
7178     *
7179     * @see #getRotation()
7180     * @see #getScaleX()
7181     * @see #getScaleY()
7182     * @see #getPivotX()
7183     * @see #getPivotY()
7184     * @return The current transform matrix for the view
7185     */
7186    public Matrix getMatrix() {
7187        if (mTransformationInfo != null) {
7188            updateMatrix();
7189            return mTransformationInfo.mMatrix;
7190        }
7191        return Matrix.IDENTITY_MATRIX;
7192    }
7193
7194    /**
7195     * Utility function to determine if the value is far enough away from zero to be
7196     * considered non-zero.
7197     * @param value A floating point value to check for zero-ness
7198     * @return whether the passed-in value is far enough away from zero to be considered non-zero
7199     */
7200    private static boolean nonzero(float value) {
7201        return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON);
7202    }
7203
7204    /**
7205     * Returns true if the transform matrix is the identity matrix.
7206     * Recomputes the matrix if necessary.
7207     *
7208     * @return True if the transform matrix is the identity matrix, false otherwise.
7209     */
7210    final boolean hasIdentityMatrix() {
7211        if (mTransformationInfo != null) {
7212            updateMatrix();
7213            return mTransformationInfo.mMatrixIsIdentity;
7214        }
7215        return true;
7216    }
7217
7218    void ensureTransformationInfo() {
7219        if (mTransformationInfo == null) {
7220            mTransformationInfo = new TransformationInfo();
7221        }
7222    }
7223
7224    /**
7225     * Recomputes the transform matrix if necessary.
7226     */
7227    private void updateMatrix() {
7228        final TransformationInfo info = mTransformationInfo;
7229        if (info == null) {
7230            return;
7231        }
7232        if (info.mMatrixDirty) {
7233            // transform-related properties have changed since the last time someone
7234            // asked for the matrix; recalculate it with the current values
7235
7236            // Figure out if we need to update the pivot point
7237            if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7238                if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) {
7239                    info.mPrevWidth = mRight - mLeft;
7240                    info.mPrevHeight = mBottom - mTop;
7241                    info.mPivotX = info.mPrevWidth / 2f;
7242                    info.mPivotY = info.mPrevHeight / 2f;
7243                }
7244            }
7245            info.mMatrix.reset();
7246            if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) {
7247                info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY);
7248                info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY);
7249                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7250            } else {
7251                if (info.mCamera == null) {
7252                    info.mCamera = new Camera();
7253                    info.matrix3D = new Matrix();
7254                }
7255                info.mCamera.save();
7256                info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY);
7257                info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation);
7258                info.mCamera.getMatrix(info.matrix3D);
7259                info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY);
7260                info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX,
7261                        info.mPivotY + info.mTranslationY);
7262                info.mMatrix.postConcat(info.matrix3D);
7263                info.mCamera.restore();
7264            }
7265            info.mMatrixDirty = false;
7266            info.mMatrixIsIdentity = info.mMatrix.isIdentity();
7267            info.mInverseMatrixDirty = true;
7268        }
7269    }
7270
7271    /**
7272     * Utility method to retrieve the inverse of the current mMatrix property.
7273     * We cache the matrix to avoid recalculating it when transform properties
7274     * have not changed.
7275     *
7276     * @return The inverse of the current matrix of this view.
7277     */
7278    final Matrix getInverseMatrix() {
7279        final TransformationInfo info = mTransformationInfo;
7280        if (info != null) {
7281            updateMatrix();
7282            if (info.mInverseMatrixDirty) {
7283                if (info.mInverseMatrix == null) {
7284                    info.mInverseMatrix = new Matrix();
7285                }
7286                info.mMatrix.invert(info.mInverseMatrix);
7287                info.mInverseMatrixDirty = false;
7288            }
7289            return info.mInverseMatrix;
7290        }
7291        return Matrix.IDENTITY_MATRIX;
7292    }
7293
7294    /**
7295     * Gets the distance along the Z axis from the camera to this view.
7296     *
7297     * @see #setCameraDistance(float)
7298     *
7299     * @return The distance along the Z axis.
7300     */
7301    public float getCameraDistance() {
7302        ensureTransformationInfo();
7303        final float dpi = mResources.getDisplayMetrics().densityDpi;
7304        final TransformationInfo info = mTransformationInfo;
7305        if (info.mCamera == null) {
7306            info.mCamera = new Camera();
7307            info.matrix3D = new Matrix();
7308        }
7309        return -(info.mCamera.getLocationZ() * dpi);
7310    }
7311
7312    /**
7313     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
7314     * views are drawn) from the camera to this view. The camera's distance
7315     * affects 3D transformations, for instance rotations around the X and Y
7316     * axis. If the rotationX or rotationY properties are changed and this view is
7317     * large (more than half the size of the screen), it is recommended to always
7318     * use a camera distance that's greater than the height (X axis rotation) or
7319     * the width (Y axis rotation) of this view.</p>
7320     *
7321     * <p>The distance of the camera from the view plane can have an affect on the
7322     * perspective distortion of the view when it is rotated around the x or y axis.
7323     * For example, a large distance will result in a large viewing angle, and there
7324     * will not be much perspective distortion of the view as it rotates. A short
7325     * distance may cause much more perspective distortion upon rotation, and can
7326     * also result in some drawing artifacts if the rotated view ends up partially
7327     * behind the camera (which is why the recommendation is to use a distance at
7328     * least as far as the size of the view, if the view is to be rotated.)</p>
7329     *
7330     * <p>The distance is expressed in "depth pixels." The default distance depends
7331     * on the screen density. For instance, on a medium density display, the
7332     * default distance is 1280. On a high density display, the default distance
7333     * is 1920.</p>
7334     *
7335     * <p>If you want to specify a distance that leads to visually consistent
7336     * results across various densities, use the following formula:</p>
7337     * <pre>
7338     * float scale = context.getResources().getDisplayMetrics().density;
7339     * view.setCameraDistance(distance * scale);
7340     * </pre>
7341     *
7342     * <p>The density scale factor of a high density display is 1.5,
7343     * and 1920 = 1280 * 1.5.</p>
7344     *
7345     * @param distance The distance in "depth pixels", if negative the opposite
7346     *        value is used
7347     *
7348     * @see #setRotationX(float)
7349     * @see #setRotationY(float)
7350     */
7351    public void setCameraDistance(float distance) {
7352        invalidateParentCaches();
7353        invalidate(false);
7354
7355        ensureTransformationInfo();
7356        final float dpi = mResources.getDisplayMetrics().densityDpi;
7357        final TransformationInfo info = mTransformationInfo;
7358        if (info.mCamera == null) {
7359            info.mCamera = new Camera();
7360            info.matrix3D = new Matrix();
7361        }
7362
7363        info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi);
7364        info.mMatrixDirty = true;
7365
7366        invalidate(false);
7367        if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7368            mDisplayList.setCameraDistance(distance);
7369        }
7370    }
7371
7372    /**
7373     * The degrees that the view is rotated around the pivot point.
7374     *
7375     * @see #setRotation(float)
7376     * @see #getPivotX()
7377     * @see #getPivotY()
7378     *
7379     * @return The degrees of rotation.
7380     */
7381    @ViewDebug.ExportedProperty(category = "drawing")
7382    public float getRotation() {
7383        return mTransformationInfo != null ? mTransformationInfo.mRotation : 0;
7384    }
7385
7386    /**
7387     * Sets the degrees that the view is rotated around the pivot point. Increasing values
7388     * result in clockwise rotation.
7389     *
7390     * @param rotation The degrees of rotation.
7391     *
7392     * @see #getRotation()
7393     * @see #getPivotX()
7394     * @see #getPivotY()
7395     * @see #setRotationX(float)
7396     * @see #setRotationY(float)
7397     *
7398     * @attr ref android.R.styleable#View_rotation
7399     */
7400    public void setRotation(float rotation) {
7401        ensureTransformationInfo();
7402        final TransformationInfo info = mTransformationInfo;
7403        if (info.mRotation != rotation) {
7404            invalidateParentCaches();
7405            // Double-invalidation is necessary to capture view's old and new areas
7406            invalidate(false);
7407            info.mRotation = rotation;
7408            info.mMatrixDirty = true;
7409            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7410            invalidate(false);
7411            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7412                mDisplayList.setRotation(rotation);
7413            }
7414        }
7415    }
7416
7417    /**
7418     * The degrees that the view is rotated around the vertical axis through the pivot point.
7419     *
7420     * @see #getPivotX()
7421     * @see #getPivotY()
7422     * @see #setRotationY(float)
7423     *
7424     * @return The degrees of Y rotation.
7425     */
7426    @ViewDebug.ExportedProperty(category = "drawing")
7427    public float getRotationY() {
7428        return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0;
7429    }
7430
7431    /**
7432     * Sets the degrees that the view is rotated around the vertical axis through the pivot point.
7433     * Increasing values result in counter-clockwise rotation from the viewpoint of looking
7434     * down the y axis.
7435     *
7436     * When rotating large views, it is recommended to adjust the camera distance
7437     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7438     *
7439     * @param rotationY The degrees of Y rotation.
7440     *
7441     * @see #getRotationY()
7442     * @see #getPivotX()
7443     * @see #getPivotY()
7444     * @see #setRotation(float)
7445     * @see #setRotationX(float)
7446     * @see #setCameraDistance(float)
7447     *
7448     * @attr ref android.R.styleable#View_rotationY
7449     */
7450    public void setRotationY(float rotationY) {
7451        ensureTransformationInfo();
7452        final TransformationInfo info = mTransformationInfo;
7453        if (info.mRotationY != rotationY) {
7454            invalidateParentCaches();
7455            // Double-invalidation is necessary to capture view's old and new areas
7456            invalidate(false);
7457            info.mRotationY = rotationY;
7458            info.mMatrixDirty = true;
7459            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7460            invalidate(false);
7461            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7462                mDisplayList.setRotationY(rotationY);
7463            }
7464        }
7465    }
7466
7467    /**
7468     * The degrees that the view is rotated around the horizontal axis through the pivot point.
7469     *
7470     * @see #getPivotX()
7471     * @see #getPivotY()
7472     * @see #setRotationX(float)
7473     *
7474     * @return The degrees of X rotation.
7475     */
7476    @ViewDebug.ExportedProperty(category = "drawing")
7477    public float getRotationX() {
7478        return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0;
7479    }
7480
7481    /**
7482     * Sets the degrees that the view is rotated around the horizontal axis through the pivot point.
7483     * Increasing values result in clockwise rotation from the viewpoint of looking down the
7484     * x axis.
7485     *
7486     * When rotating large views, it is recommended to adjust the camera distance
7487     * accordingly. Refer to {@link #setCameraDistance(float)} for more information.
7488     *
7489     * @param rotationX The degrees of X rotation.
7490     *
7491     * @see #getRotationX()
7492     * @see #getPivotX()
7493     * @see #getPivotY()
7494     * @see #setRotation(float)
7495     * @see #setRotationY(float)
7496     * @see #setCameraDistance(float)
7497     *
7498     * @attr ref android.R.styleable#View_rotationX
7499     */
7500    public void setRotationX(float rotationX) {
7501        ensureTransformationInfo();
7502        final TransformationInfo info = mTransformationInfo;
7503        if (info.mRotationX != rotationX) {
7504            invalidateParentCaches();
7505            // Double-invalidation is necessary to capture view's old and new areas
7506            invalidate(false);
7507            info.mRotationX = rotationX;
7508            info.mMatrixDirty = true;
7509            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7510            invalidate(false);
7511            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7512                mDisplayList.setRotationX(rotationX);
7513            }
7514        }
7515    }
7516
7517    /**
7518     * The amount that the view is scaled in x around the pivot point, as a proportion of
7519     * the view's unscaled width. A value of 1, the default, means that no scaling is applied.
7520     *
7521     * <p>By default, this is 1.0f.
7522     *
7523     * @see #getPivotX()
7524     * @see #getPivotY()
7525     * @return The scaling factor.
7526     */
7527    @ViewDebug.ExportedProperty(category = "drawing")
7528    public float getScaleX() {
7529        return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1;
7530    }
7531
7532    /**
7533     * Sets the amount that the view is scaled in x around the pivot point, as a proportion of
7534     * the view's unscaled width. A value of 1 means that no scaling is applied.
7535     *
7536     * @param scaleX The scaling factor.
7537     * @see #getPivotX()
7538     * @see #getPivotY()
7539     *
7540     * @attr ref android.R.styleable#View_scaleX
7541     */
7542    public void setScaleX(float scaleX) {
7543        ensureTransformationInfo();
7544        final TransformationInfo info = mTransformationInfo;
7545        if (info.mScaleX != scaleX) {
7546            invalidateParentCaches();
7547            // Double-invalidation is necessary to capture view's old and new areas
7548            invalidate(false);
7549            info.mScaleX = scaleX;
7550            info.mMatrixDirty = true;
7551            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7552            invalidate(false);
7553            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7554                mDisplayList.setScaleX(scaleX);
7555            }
7556        }
7557    }
7558
7559    /**
7560     * The amount that the view is scaled in y around the pivot point, as a proportion of
7561     * the view's unscaled height. A value of 1, the default, means that no scaling is applied.
7562     *
7563     * <p>By default, this is 1.0f.
7564     *
7565     * @see #getPivotX()
7566     * @see #getPivotY()
7567     * @return The scaling factor.
7568     */
7569    @ViewDebug.ExportedProperty(category = "drawing")
7570    public float getScaleY() {
7571        return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1;
7572    }
7573
7574    /**
7575     * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of
7576     * the view's unscaled width. A value of 1 means that no scaling is applied.
7577     *
7578     * @param scaleY The scaling factor.
7579     * @see #getPivotX()
7580     * @see #getPivotY()
7581     *
7582     * @attr ref android.R.styleable#View_scaleY
7583     */
7584    public void setScaleY(float scaleY) {
7585        ensureTransformationInfo();
7586        final TransformationInfo info = mTransformationInfo;
7587        if (info.mScaleY != scaleY) {
7588            invalidateParentCaches();
7589            // Double-invalidation is necessary to capture view's old and new areas
7590            invalidate(false);
7591            info.mScaleY = scaleY;
7592            info.mMatrixDirty = true;
7593            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7594            invalidate(false);
7595            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7596                mDisplayList.setScaleY(scaleY);
7597            }
7598        }
7599    }
7600
7601    /**
7602     * The x location of the point around which the view is {@link #setRotation(float) rotated}
7603     * and {@link #setScaleX(float) scaled}.
7604     *
7605     * @see #getRotation()
7606     * @see #getScaleX()
7607     * @see #getScaleY()
7608     * @see #getPivotY()
7609     * @return The x location of the pivot point.
7610     */
7611    @ViewDebug.ExportedProperty(category = "drawing")
7612    public float getPivotX() {
7613        return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0;
7614    }
7615
7616    /**
7617     * Sets the x location of the point around which the view is
7618     * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}.
7619     * By default, the pivot point is centered on the object.
7620     * Setting this property disables this behavior and causes the view to use only the
7621     * explicitly set pivotX and pivotY values.
7622     *
7623     * @param pivotX The x location of the pivot point.
7624     * @see #getRotation()
7625     * @see #getScaleX()
7626     * @see #getScaleY()
7627     * @see #getPivotY()
7628     *
7629     * @attr ref android.R.styleable#View_transformPivotX
7630     */
7631    public void setPivotX(float pivotX) {
7632        ensureTransformationInfo();
7633        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7634        final TransformationInfo info = mTransformationInfo;
7635        if (info.mPivotX != pivotX) {
7636            invalidateParentCaches();
7637            // Double-invalidation is necessary to capture view's old and new areas
7638            invalidate(false);
7639            info.mPivotX = pivotX;
7640            info.mMatrixDirty = true;
7641            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7642            invalidate(false);
7643            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7644                mDisplayList.setPivotX(pivotX);
7645            }
7646        }
7647    }
7648
7649    /**
7650     * The y location of the point around which the view is {@link #setRotation(float) rotated}
7651     * and {@link #setScaleY(float) scaled}.
7652     *
7653     * @see #getRotation()
7654     * @see #getScaleX()
7655     * @see #getScaleY()
7656     * @see #getPivotY()
7657     * @return The y location of the pivot point.
7658     */
7659    @ViewDebug.ExportedProperty(category = "drawing")
7660    public float getPivotY() {
7661        return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0;
7662    }
7663
7664    /**
7665     * Sets the y location of the point around which the view is {@link #setRotation(float) rotated}
7666     * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object.
7667     * Setting this property disables this behavior and causes the view to use only the
7668     * explicitly set pivotX and pivotY values.
7669     *
7670     * @param pivotY The y location of the pivot point.
7671     * @see #getRotation()
7672     * @see #getScaleX()
7673     * @see #getScaleY()
7674     * @see #getPivotY()
7675     *
7676     * @attr ref android.R.styleable#View_transformPivotY
7677     */
7678    public void setPivotY(float pivotY) {
7679        ensureTransformationInfo();
7680        mPrivateFlags |= PIVOT_EXPLICITLY_SET;
7681        final TransformationInfo info = mTransformationInfo;
7682        if (info.mPivotY != pivotY) {
7683            invalidateParentCaches();
7684            // Double-invalidation is necessary to capture view's old and new areas
7685            invalidate(false);
7686            info.mPivotY = pivotY;
7687            info.mMatrixDirty = true;
7688            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7689            invalidate(false);
7690            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7691                mDisplayList.setPivotY(pivotY);
7692            }
7693        }
7694    }
7695
7696    /**
7697     * The opacity of the view. This is a value from 0 to 1, where 0 means the view is
7698     * completely transparent and 1 means the view is completely opaque.
7699     *
7700     * <p>By default this is 1.0f.
7701     * @return The opacity of the view.
7702     */
7703    @ViewDebug.ExportedProperty(category = "drawing")
7704    public float getAlpha() {
7705        return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1;
7706    }
7707
7708    /**
7709     * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
7710     * completely transparent and 1 means the view is completely opaque.</p>
7711     *
7712     * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
7713     * responsible for applying the opacity itself. Otherwise, calling this method is
7714     * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
7715     * setting a hardware layer.</p>
7716     *
7717     * <p>Note that setting alpha to a translucent value (0 < alpha < 1) may have
7718     * performance implications. It is generally best to use the alpha property sparingly and
7719     * transiently, as in the case of fading animations.</p>
7720     *
7721     * @param alpha The opacity of the view.
7722     *
7723     * @see #setLayerType(int, android.graphics.Paint)
7724     *
7725     * @attr ref android.R.styleable#View_alpha
7726     */
7727    public void setAlpha(float alpha) {
7728        ensureTransformationInfo();
7729        if (mTransformationInfo.mAlpha != alpha) {
7730            mTransformationInfo.mAlpha = alpha;
7731            invalidateParentCaches();
7732            if (onSetAlpha((int) (alpha * 255))) {
7733                mPrivateFlags |= ALPHA_SET;
7734                // subclass is handling alpha - don't optimize rendering cache invalidation
7735                invalidate(true);
7736            } else {
7737                mPrivateFlags &= ~ALPHA_SET;
7738                invalidate(false);
7739                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7740                    mDisplayList.setAlpha(alpha);
7741                }
7742            }
7743        }
7744    }
7745
7746    /**
7747     * Faster version of setAlpha() which performs the same steps except there are
7748     * no calls to invalidate(). The caller of this function should perform proper invalidation
7749     * on the parent and this object. The return value indicates whether the subclass handles
7750     * alpha (the return value for onSetAlpha()).
7751     *
7752     * @param alpha The new value for the alpha property
7753     * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and
7754     *         the new value for the alpha property is different from the old value
7755     */
7756    boolean setAlphaNoInvalidation(float alpha) {
7757        ensureTransformationInfo();
7758        if (mTransformationInfo.mAlpha != alpha) {
7759            mTransformationInfo.mAlpha = alpha;
7760            boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255));
7761            if (subclassHandlesAlpha) {
7762                mPrivateFlags |= ALPHA_SET;
7763                return true;
7764            } else {
7765                mPrivateFlags &= ~ALPHA_SET;
7766                if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7767                    mDisplayList.setAlpha(alpha);
7768                }
7769            }
7770        }
7771        return false;
7772    }
7773
7774    /**
7775     * Top position of this view relative to its parent.
7776     *
7777     * @return The top of this view, in pixels.
7778     */
7779    @ViewDebug.CapturedViewProperty
7780    public final int getTop() {
7781        return mTop;
7782    }
7783
7784    /**
7785     * Sets the top position of this view relative to its parent. This method is meant to be called
7786     * by the layout system and should not generally be called otherwise, because the property
7787     * may be changed at any time by the layout.
7788     *
7789     * @param top The top of this view, in pixels.
7790     */
7791    public final void setTop(int top) {
7792        if (top != mTop) {
7793            updateMatrix();
7794            final boolean matrixIsIdentity = mTransformationInfo == null
7795                    || mTransformationInfo.mMatrixIsIdentity;
7796            if (matrixIsIdentity) {
7797                if (mAttachInfo != null) {
7798                    int minTop;
7799                    int yLoc;
7800                    if (top < mTop) {
7801                        minTop = top;
7802                        yLoc = top - mTop;
7803                    } else {
7804                        minTop = mTop;
7805                        yLoc = 0;
7806                    }
7807                    invalidate(0, yLoc, mRight - mLeft, mBottom - minTop);
7808                }
7809            } else {
7810                // Double-invalidation is necessary to capture view's old and new areas
7811                invalidate(true);
7812            }
7813
7814            int width = mRight - mLeft;
7815            int oldHeight = mBottom - mTop;
7816
7817            mTop = top;
7818            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7819                mDisplayList.setTop(mTop);
7820            }
7821
7822            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7823
7824            if (!matrixIsIdentity) {
7825                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7826                    // A change in dimension means an auto-centered pivot point changes, too
7827                    mTransformationInfo.mMatrixDirty = true;
7828                }
7829                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7830                invalidate(true);
7831            }
7832            mBackgroundSizeChanged = true;
7833            invalidateParentIfNeeded();
7834        }
7835    }
7836
7837    /**
7838     * Bottom position of this view relative to its parent.
7839     *
7840     * @return The bottom of this view, in pixels.
7841     */
7842    @ViewDebug.CapturedViewProperty
7843    public final int getBottom() {
7844        return mBottom;
7845    }
7846
7847    /**
7848     * True if this view has changed since the last time being drawn.
7849     *
7850     * @return The dirty state of this view.
7851     */
7852    public boolean isDirty() {
7853        return (mPrivateFlags & DIRTY_MASK) != 0;
7854    }
7855
7856    /**
7857     * Sets the bottom position of this view relative to its parent. This method is meant to be
7858     * called by the layout system and should not generally be called otherwise, because the
7859     * property may be changed at any time by the layout.
7860     *
7861     * @param bottom The bottom of this view, in pixels.
7862     */
7863    public final void setBottom(int bottom) {
7864        if (bottom != mBottom) {
7865            updateMatrix();
7866            final boolean matrixIsIdentity = mTransformationInfo == null
7867                    || mTransformationInfo.mMatrixIsIdentity;
7868            if (matrixIsIdentity) {
7869                if (mAttachInfo != null) {
7870                    int maxBottom;
7871                    if (bottom < mBottom) {
7872                        maxBottom = mBottom;
7873                    } else {
7874                        maxBottom = bottom;
7875                    }
7876                    invalidate(0, 0, mRight - mLeft, maxBottom - mTop);
7877                }
7878            } else {
7879                // Double-invalidation is necessary to capture view's old and new areas
7880                invalidate(true);
7881            }
7882
7883            int width = mRight - mLeft;
7884            int oldHeight = mBottom - mTop;
7885
7886            mBottom = bottom;
7887            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7888                mDisplayList.setBottom(mBottom);
7889            }
7890
7891            onSizeChanged(width, mBottom - mTop, width, oldHeight);
7892
7893            if (!matrixIsIdentity) {
7894                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7895                    // A change in dimension means an auto-centered pivot point changes, too
7896                    mTransformationInfo.mMatrixDirty = true;
7897                }
7898                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7899                invalidate(true);
7900            }
7901            mBackgroundSizeChanged = true;
7902            invalidateParentIfNeeded();
7903        }
7904    }
7905
7906    /**
7907     * Left position of this view relative to its parent.
7908     *
7909     * @return The left edge of this view, in pixels.
7910     */
7911    @ViewDebug.CapturedViewProperty
7912    public final int getLeft() {
7913        return mLeft;
7914    }
7915
7916    /**
7917     * Sets the left position of this view relative to its parent. This method is meant to be called
7918     * by the layout system and should not generally be called otherwise, because the property
7919     * may be changed at any time by the layout.
7920     *
7921     * @param left The bottom of this view, in pixels.
7922     */
7923    public final void setLeft(int left) {
7924        if (left != mLeft) {
7925            updateMatrix();
7926            final boolean matrixIsIdentity = mTransformationInfo == null
7927                    || mTransformationInfo.mMatrixIsIdentity;
7928            if (matrixIsIdentity) {
7929                if (mAttachInfo != null) {
7930                    int minLeft;
7931                    int xLoc;
7932                    if (left < mLeft) {
7933                        minLeft = left;
7934                        xLoc = left - mLeft;
7935                    } else {
7936                        minLeft = mLeft;
7937                        xLoc = 0;
7938                    }
7939                    invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop);
7940                }
7941            } else {
7942                // Double-invalidation is necessary to capture view's old and new areas
7943                invalidate(true);
7944            }
7945
7946            int oldWidth = mRight - mLeft;
7947            int height = mBottom - mTop;
7948
7949            mLeft = left;
7950            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
7951                mDisplayList.setLeft(left);
7952            }
7953
7954            onSizeChanged(mRight - mLeft, height, oldWidth, height);
7955
7956            if (!matrixIsIdentity) {
7957                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
7958                    // A change in dimension means an auto-centered pivot point changes, too
7959                    mTransformationInfo.mMatrixDirty = true;
7960                }
7961                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
7962                invalidate(true);
7963            }
7964            mBackgroundSizeChanged = true;
7965            invalidateParentIfNeeded();
7966            if (USE_DISPLAY_LIST_PROPERTIES) {
7967
7968            }
7969        }
7970    }
7971
7972    /**
7973     * Right position of this view relative to its parent.
7974     *
7975     * @return The right edge of this view, in pixels.
7976     */
7977    @ViewDebug.CapturedViewProperty
7978    public final int getRight() {
7979        return mRight;
7980    }
7981
7982    /**
7983     * Sets the right position of this view relative to its parent. This method is meant to be called
7984     * by the layout system and should not generally be called otherwise, because the property
7985     * may be changed at any time by the layout.
7986     *
7987     * @param right The bottom of this view, in pixels.
7988     */
7989    public final void setRight(int right) {
7990        if (right != mRight) {
7991            updateMatrix();
7992            final boolean matrixIsIdentity = mTransformationInfo == null
7993                    || mTransformationInfo.mMatrixIsIdentity;
7994            if (matrixIsIdentity) {
7995                if (mAttachInfo != null) {
7996                    int maxRight;
7997                    if (right < mRight) {
7998                        maxRight = mRight;
7999                    } else {
8000                        maxRight = right;
8001                    }
8002                    invalidate(0, 0, maxRight - mLeft, mBottom - mTop);
8003                }
8004            } else {
8005                // Double-invalidation is necessary to capture view's old and new areas
8006                invalidate(true);
8007            }
8008
8009            int oldWidth = mRight - mLeft;
8010            int height = mBottom - mTop;
8011
8012            mRight = right;
8013            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8014                mDisplayList.setRight(mRight);
8015            }
8016
8017            onSizeChanged(mRight - mLeft, height, oldWidth, height);
8018
8019            if (!matrixIsIdentity) {
8020                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
8021                    // A change in dimension means an auto-centered pivot point changes, too
8022                    mTransformationInfo.mMatrixDirty = true;
8023                }
8024                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8025                invalidate(true);
8026            }
8027            mBackgroundSizeChanged = true;
8028            invalidateParentIfNeeded();
8029        }
8030    }
8031
8032    /**
8033     * The visual x position of this view, in pixels. This is equivalent to the
8034     * {@link #setTranslationX(float) translationX} property plus the current
8035     * {@link #getLeft() left} property.
8036     *
8037     * @return The visual x position of this view, in pixels.
8038     */
8039    @ViewDebug.ExportedProperty(category = "drawing")
8040    public float getX() {
8041        return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0);
8042    }
8043
8044    /**
8045     * Sets the visual x position of this view, in pixels. This is equivalent to setting the
8046     * {@link #setTranslationX(float) translationX} property to be the difference between
8047     * the x value passed in and the current {@link #getLeft() left} property.
8048     *
8049     * @param x The visual x position of this view, in pixels.
8050     */
8051    public void setX(float x) {
8052        setTranslationX(x - mLeft);
8053    }
8054
8055    /**
8056     * The visual y position of this view, in pixels. This is equivalent to the
8057     * {@link #setTranslationY(float) translationY} property plus the current
8058     * {@link #getTop() top} property.
8059     *
8060     * @return The visual y position of this view, in pixels.
8061     */
8062    @ViewDebug.ExportedProperty(category = "drawing")
8063    public float getY() {
8064        return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0);
8065    }
8066
8067    /**
8068     * Sets the visual y position of this view, in pixels. This is equivalent to setting the
8069     * {@link #setTranslationY(float) translationY} property to be the difference between
8070     * the y value passed in and the current {@link #getTop() top} property.
8071     *
8072     * @param y The visual y position of this view, in pixels.
8073     */
8074    public void setY(float y) {
8075        setTranslationY(y - mTop);
8076    }
8077
8078
8079    /**
8080     * The horizontal location of this view relative to its {@link #getLeft() left} position.
8081     * This position is post-layout, in addition to wherever the object's
8082     * layout placed it.
8083     *
8084     * @return The horizontal position of this view relative to its left position, in pixels.
8085     */
8086    @ViewDebug.ExportedProperty(category = "drawing")
8087    public float getTranslationX() {
8088        return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0;
8089    }
8090
8091    /**
8092     * Sets the horizontal location of this view relative to its {@link #getLeft() left} position.
8093     * This effectively positions the object post-layout, in addition to wherever the object's
8094     * layout placed it.
8095     *
8096     * @param translationX The horizontal position of this view relative to its left position,
8097     * in pixels.
8098     *
8099     * @attr ref android.R.styleable#View_translationX
8100     */
8101    public void setTranslationX(float translationX) {
8102        ensureTransformationInfo();
8103        final TransformationInfo info = mTransformationInfo;
8104        if (info.mTranslationX != translationX) {
8105            invalidateParentCaches();
8106            // Double-invalidation is necessary to capture view's old and new areas
8107            invalidate(false);
8108            info.mTranslationX = translationX;
8109            info.mMatrixDirty = true;
8110            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8111            invalidate(false);
8112            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8113                mDisplayList.setTranslationX(translationX);
8114            }
8115        }
8116    }
8117
8118    /**
8119     * The horizontal location of this view relative to its {@link #getTop() top} position.
8120     * This position is post-layout, in addition to wherever the object's
8121     * layout placed it.
8122     *
8123     * @return The vertical position of this view relative to its top position,
8124     * in pixels.
8125     */
8126    @ViewDebug.ExportedProperty(category = "drawing")
8127    public float getTranslationY() {
8128        return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0;
8129    }
8130
8131    /**
8132     * Sets the vertical location of this view relative to its {@link #getTop() top} position.
8133     * This effectively positions the object post-layout, in addition to wherever the object's
8134     * layout placed it.
8135     *
8136     * @param translationY The vertical position of this view relative to its top position,
8137     * in pixels.
8138     *
8139     * @attr ref android.R.styleable#View_translationY
8140     */
8141    public void setTranslationY(float translationY) {
8142        ensureTransformationInfo();
8143        final TransformationInfo info = mTransformationInfo;
8144        if (info.mTranslationY != translationY) {
8145            invalidateParentCaches();
8146            // Double-invalidation is necessary to capture view's old and new areas
8147            invalidate(false);
8148            info.mTranslationY = translationY;
8149            info.mMatrixDirty = true;
8150            mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8151            invalidate(false);
8152            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8153                mDisplayList.setTranslationY(translationY);
8154            }
8155        }
8156    }
8157
8158    /**
8159     * Hit rectangle in parent's coordinates
8160     *
8161     * @param outRect The hit rectangle of the view.
8162     */
8163    public void getHitRect(Rect outRect) {
8164        updateMatrix();
8165        final TransformationInfo info = mTransformationInfo;
8166        if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) {
8167            outRect.set(mLeft, mTop, mRight, mBottom);
8168        } else {
8169            final RectF tmpRect = mAttachInfo.mTmpTransformRect;
8170            tmpRect.set(-info.mPivotX, -info.mPivotY,
8171                    getWidth() - info.mPivotX, getHeight() - info.mPivotY);
8172            info.mMatrix.mapRect(tmpRect);
8173            outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop,
8174                    (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop);
8175        }
8176    }
8177
8178    /**
8179     * Determines whether the given point, in local coordinates is inside the view.
8180     */
8181    /*package*/ final boolean pointInView(float localX, float localY) {
8182        return localX >= 0 && localX < (mRight - mLeft)
8183                && localY >= 0 && localY < (mBottom - mTop);
8184    }
8185
8186    /**
8187     * Utility method to determine whether the given point, in local coordinates,
8188     * is inside the view, where the area of the view is expanded by the slop factor.
8189     * This method is called while processing touch-move events to determine if the event
8190     * is still within the view.
8191     */
8192    private boolean pointInView(float localX, float localY, float slop) {
8193        return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) &&
8194                localY < ((mBottom - mTop) + slop);
8195    }
8196
8197    /**
8198     * When a view has focus and the user navigates away from it, the next view is searched for
8199     * starting from the rectangle filled in by this method.
8200     *
8201     * By default, the rectange is the {@link #getDrawingRect(android.graphics.Rect)})
8202     * of the view.  However, if your view maintains some idea of internal selection,
8203     * such as a cursor, or a selected row or column, you should override this method and
8204     * fill in a more specific rectangle.
8205     *
8206     * @param r The rectangle to fill in, in this view's coordinates.
8207     */
8208    public void getFocusedRect(Rect r) {
8209        getDrawingRect(r);
8210    }
8211
8212    /**
8213     * If some part of this view is not clipped by any of its parents, then
8214     * return that area in r in global (root) coordinates. To convert r to local
8215     * coordinates (without taking possible View rotations into account), offset
8216     * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)).
8217     * If the view is completely clipped or translated out, return false.
8218     *
8219     * @param r If true is returned, r holds the global coordinates of the
8220     *        visible portion of this view.
8221     * @param globalOffset If true is returned, globalOffset holds the dx,dy
8222     *        between this view and its root. globalOffet may be null.
8223     * @return true if r is non-empty (i.e. part of the view is visible at the
8224     *         root level.
8225     */
8226    public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
8227        int width = mRight - mLeft;
8228        int height = mBottom - mTop;
8229        if (width > 0 && height > 0) {
8230            r.set(0, 0, width, height);
8231            if (globalOffset != null) {
8232                globalOffset.set(-mScrollX, -mScrollY);
8233            }
8234            return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
8235        }
8236        return false;
8237    }
8238
8239    public final boolean getGlobalVisibleRect(Rect r) {
8240        return getGlobalVisibleRect(r, null);
8241    }
8242
8243    public final boolean getLocalVisibleRect(Rect r) {
8244        Point offset = new Point();
8245        if (getGlobalVisibleRect(r, offset)) {
8246            r.offset(-offset.x, -offset.y); // make r local
8247            return true;
8248        }
8249        return false;
8250    }
8251
8252    /**
8253     * Offset this view's vertical location by the specified number of pixels.
8254     *
8255     * @param offset the number of pixels to offset the view by
8256     */
8257    public void offsetTopAndBottom(int offset) {
8258        if (offset != 0) {
8259            updateMatrix();
8260            final boolean matrixIsIdentity = mTransformationInfo == null
8261                    || mTransformationInfo.mMatrixIsIdentity;
8262            if (matrixIsIdentity) {
8263                final ViewParent p = mParent;
8264                if (p != null && mAttachInfo != null) {
8265                    final Rect r = mAttachInfo.mTmpInvalRect;
8266                    int minTop;
8267                    int maxBottom;
8268                    int yLoc;
8269                    if (offset < 0) {
8270                        minTop = mTop + offset;
8271                        maxBottom = mBottom;
8272                        yLoc = offset;
8273                    } else {
8274                        minTop = mTop;
8275                        maxBottom = mBottom + offset;
8276                        yLoc = 0;
8277                    }
8278                    r.set(0, yLoc, mRight - mLeft, maxBottom - minTop);
8279                    p.invalidateChild(this, r);
8280                }
8281            } else {
8282                invalidate(false);
8283            }
8284
8285            mTop += offset;
8286            mBottom += offset;
8287            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8288                mDisplayList.offsetTopBottom(offset);
8289            }
8290
8291            if (!matrixIsIdentity) {
8292                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8293                invalidate(false);
8294            }
8295            invalidateParentIfNeeded();
8296        }
8297    }
8298
8299    /**
8300     * Offset this view's horizontal location by the specified amount of pixels.
8301     *
8302     * @param offset the numer of pixels to offset the view by
8303     */
8304    public void offsetLeftAndRight(int offset) {
8305        if (offset != 0) {
8306            updateMatrix();
8307            final boolean matrixIsIdentity = mTransformationInfo == null
8308                    || mTransformationInfo.mMatrixIsIdentity;
8309            if (matrixIsIdentity) {
8310                final ViewParent p = mParent;
8311                if (p != null && mAttachInfo != null) {
8312                    final Rect r = mAttachInfo.mTmpInvalRect;
8313                    int minLeft;
8314                    int maxRight;
8315                    if (offset < 0) {
8316                        minLeft = mLeft + offset;
8317                        maxRight = mRight;
8318                    } else {
8319                        minLeft = mLeft;
8320                        maxRight = mRight + offset;
8321                    }
8322                    r.set(0, 0, maxRight - minLeft, mBottom - mTop);
8323                    p.invalidateChild(this, r);
8324                }
8325            } else {
8326                invalidate(false);
8327            }
8328
8329            mLeft += offset;
8330            mRight += offset;
8331            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
8332                mDisplayList.offsetLeftRight(offset);
8333            }
8334
8335            if (!matrixIsIdentity) {
8336                mPrivateFlags |= DRAWN; // force another invalidation with the new orientation
8337                invalidate(false);
8338            }
8339            invalidateParentIfNeeded();
8340        }
8341    }
8342
8343    /**
8344     * Get the LayoutParams associated with this view. All views should have
8345     * layout parameters. These supply parameters to the <i>parent</i> of this
8346     * view specifying how it should be arranged. There are many subclasses of
8347     * ViewGroup.LayoutParams, and these correspond to the different subclasses
8348     * of ViewGroup that are responsible for arranging their children.
8349     *
8350     * This method may return null if this View is not attached to a parent
8351     * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)}
8352     * was not invoked successfully. When a View is attached to a parent
8353     * ViewGroup, this method must not return null.
8354     *
8355     * @return The LayoutParams associated with this view, or null if no
8356     *         parameters have been set yet
8357     */
8358    @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
8359    public ViewGroup.LayoutParams getLayoutParams() {
8360        return mLayoutParams;
8361    }
8362
8363    /**
8364     * Set the layout parameters associated with this view. These supply
8365     * parameters to the <i>parent</i> of this view specifying how it should be
8366     * arranged. There are many subclasses of ViewGroup.LayoutParams, and these
8367     * correspond to the different subclasses of ViewGroup that are responsible
8368     * for arranging their children.
8369     *
8370     * @param params The layout parameters for this view, cannot be null
8371     */
8372    public void setLayoutParams(ViewGroup.LayoutParams params) {
8373        if (params == null) {
8374            throw new NullPointerException("Layout parameters cannot be null");
8375        }
8376        mLayoutParams = params;
8377        if (mParent instanceof ViewGroup) {
8378            ((ViewGroup) mParent).onSetLayoutParams(this, params);
8379        }
8380        requestLayout();
8381    }
8382
8383    /**
8384     * Set the scrolled position of your view. This will cause a call to
8385     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8386     * invalidated.
8387     * @param x the x position to scroll to
8388     * @param y the y position to scroll to
8389     */
8390    public void scrollTo(int x, int y) {
8391        if (mScrollX != x || mScrollY != y) {
8392            int oldX = mScrollX;
8393            int oldY = mScrollY;
8394            mScrollX = x;
8395            mScrollY = y;
8396            invalidateParentCaches();
8397            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
8398            if (!awakenScrollBars()) {
8399                invalidate(true);
8400            }
8401        }
8402    }
8403
8404    /**
8405     * Move the scrolled position of your view. This will cause a call to
8406     * {@link #onScrollChanged(int, int, int, int)} and the view will be
8407     * invalidated.
8408     * @param x the amount of pixels to scroll by horizontally
8409     * @param y the amount of pixels to scroll by vertically
8410     */
8411    public void scrollBy(int x, int y) {
8412        scrollTo(mScrollX + x, mScrollY + y);
8413    }
8414
8415    /**
8416     * <p>Trigger the scrollbars to draw. When invoked this method starts an
8417     * animation to fade the scrollbars out after a default delay. If a subclass
8418     * provides animated scrolling, the start delay should equal the duration
8419     * of the scrolling animation.</p>
8420     *
8421     * <p>The animation starts only if at least one of the scrollbars is
8422     * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and
8423     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8424     * this method returns true, and false otherwise. If the animation is
8425     * started, this method calls {@link #invalidate()}; in that case the
8426     * caller should not call {@link #invalidate()}.</p>
8427     *
8428     * <p>This method should be invoked every time a subclass directly updates
8429     * the scroll parameters.</p>
8430     *
8431     * <p>This method is automatically invoked by {@link #scrollBy(int, int)}
8432     * and {@link #scrollTo(int, int)}.</p>
8433     *
8434     * @return true if the animation is played, false otherwise
8435     *
8436     * @see #awakenScrollBars(int)
8437     * @see #scrollBy(int, int)
8438     * @see #scrollTo(int, int)
8439     * @see #isHorizontalScrollBarEnabled()
8440     * @see #isVerticalScrollBarEnabled()
8441     * @see #setHorizontalScrollBarEnabled(boolean)
8442     * @see #setVerticalScrollBarEnabled(boolean)
8443     */
8444    protected boolean awakenScrollBars() {
8445        return mScrollCache != null &&
8446                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true);
8447    }
8448
8449    /**
8450     * Trigger the scrollbars to draw.
8451     * This method differs from awakenScrollBars() only in its default duration.
8452     * initialAwakenScrollBars() will show the scroll bars for longer than
8453     * usual to give the user more of a chance to notice them.
8454     *
8455     * @return true if the animation is played, false otherwise.
8456     */
8457    private boolean initialAwakenScrollBars() {
8458        return mScrollCache != null &&
8459                awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true);
8460    }
8461
8462    /**
8463     * <p>
8464     * Trigger the scrollbars to draw. When invoked this method starts an
8465     * animation to fade the scrollbars out after a fixed delay. If a subclass
8466     * provides animated scrolling, the start delay should equal the duration of
8467     * the scrolling animation.
8468     * </p>
8469     *
8470     * <p>
8471     * The animation starts only if at least one of the scrollbars is enabled,
8472     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8473     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8474     * this method returns true, and false otherwise. If the animation is
8475     * started, this method calls {@link #invalidate()}; in that case the caller
8476     * should not call {@link #invalidate()}.
8477     * </p>
8478     *
8479     * <p>
8480     * This method should be invoked everytime a subclass directly updates the
8481     * scroll parameters.
8482     * </p>
8483     *
8484     * @param startDelay the delay, in milliseconds, after which the animation
8485     *        should start; when the delay is 0, the animation starts
8486     *        immediately
8487     * @return true if the animation is played, false otherwise
8488     *
8489     * @see #scrollBy(int, int)
8490     * @see #scrollTo(int, int)
8491     * @see #isHorizontalScrollBarEnabled()
8492     * @see #isVerticalScrollBarEnabled()
8493     * @see #setHorizontalScrollBarEnabled(boolean)
8494     * @see #setVerticalScrollBarEnabled(boolean)
8495     */
8496    protected boolean awakenScrollBars(int startDelay) {
8497        return awakenScrollBars(startDelay, true);
8498    }
8499
8500    /**
8501     * <p>
8502     * Trigger the scrollbars to draw. When invoked this method starts an
8503     * animation to fade the scrollbars out after a fixed delay. If a subclass
8504     * provides animated scrolling, the start delay should equal the duration of
8505     * the scrolling animation.
8506     * </p>
8507     *
8508     * <p>
8509     * The animation starts only if at least one of the scrollbars is enabled,
8510     * as specified by {@link #isHorizontalScrollBarEnabled()} and
8511     * {@link #isVerticalScrollBarEnabled()}. When the animation is started,
8512     * this method returns true, and false otherwise. If the animation is
8513     * started, this method calls {@link #invalidate()} if the invalidate parameter
8514     * is set to true; in that case the caller
8515     * should not call {@link #invalidate()}.
8516     * </p>
8517     *
8518     * <p>
8519     * This method should be invoked everytime a subclass directly updates the
8520     * scroll parameters.
8521     * </p>
8522     *
8523     * @param startDelay the delay, in milliseconds, after which the animation
8524     *        should start; when the delay is 0, the animation starts
8525     *        immediately
8526     *
8527     * @param invalidate Wheter this method should call invalidate
8528     *
8529     * @return true if the animation is played, false otherwise
8530     *
8531     * @see #scrollBy(int, int)
8532     * @see #scrollTo(int, int)
8533     * @see #isHorizontalScrollBarEnabled()
8534     * @see #isVerticalScrollBarEnabled()
8535     * @see #setHorizontalScrollBarEnabled(boolean)
8536     * @see #setVerticalScrollBarEnabled(boolean)
8537     */
8538    protected boolean awakenScrollBars(int startDelay, boolean invalidate) {
8539        final ScrollabilityCache scrollCache = mScrollCache;
8540
8541        if (scrollCache == null || !scrollCache.fadeScrollBars) {
8542            return false;
8543        }
8544
8545        if (scrollCache.scrollBar == null) {
8546            scrollCache.scrollBar = new ScrollBarDrawable();
8547        }
8548
8549        if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) {
8550
8551            if (invalidate) {
8552                // Invalidate to show the scrollbars
8553                invalidate(true);
8554            }
8555
8556            if (scrollCache.state == ScrollabilityCache.OFF) {
8557                // FIXME: this is copied from WindowManagerService.
8558                // We should get this value from the system when it
8559                // is possible to do so.
8560                final int KEY_REPEAT_FIRST_DELAY = 750;
8561                startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay);
8562            }
8563
8564            // Tell mScrollCache when we should start fading. This may
8565            // extend the fade start time if one was already scheduled
8566            long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay;
8567            scrollCache.fadeStartTime = fadeStartTime;
8568            scrollCache.state = ScrollabilityCache.ON;
8569
8570            // Schedule our fader to run, unscheduling any old ones first
8571            if (mAttachInfo != null) {
8572                mAttachInfo.mHandler.removeCallbacks(scrollCache);
8573                mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime);
8574            }
8575
8576            return true;
8577        }
8578
8579        return false;
8580    }
8581
8582    /**
8583     * Do not invalidate views which are not visible and which are not running an animation. They
8584     * will not get drawn and they should not set dirty flags as if they will be drawn
8585     */
8586    private boolean skipInvalidate() {
8587        return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
8588                (!(mParent instanceof ViewGroup) ||
8589                        !((ViewGroup) mParent).isViewTransitioning(this));
8590    }
8591    /**
8592     * Mark the area defined by dirty as needing to be drawn. If the view is
8593     * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point
8594     * in the future. This must be called from a UI thread. To call from a non-UI
8595     * thread, call {@link #postInvalidate()}.
8596     *
8597     * WARNING: This method is destructive to dirty.
8598     * @param dirty the rectangle representing the bounds of the dirty region
8599     */
8600    public void invalidate(Rect dirty) {
8601        if (ViewDebug.TRACE_HIERARCHY) {
8602            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8603        }
8604
8605        if (skipInvalidate()) {
8606            return;
8607        }
8608        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8609                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8610                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8611            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8612            mPrivateFlags |= INVALIDATED;
8613            mPrivateFlags |= DIRTY;
8614            final ViewParent p = mParent;
8615            final AttachInfo ai = mAttachInfo;
8616            //noinspection PointlessBooleanExpression,ConstantConditions
8617            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8618                if (p != null && ai != null && ai.mHardwareAccelerated) {
8619                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8620                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8621                    p.invalidateChild(this, null);
8622                    return;
8623                }
8624            }
8625            if (p != null && ai != null) {
8626                final int scrollX = mScrollX;
8627                final int scrollY = mScrollY;
8628                final Rect r = ai.mTmpInvalRect;
8629                r.set(dirty.left - scrollX, dirty.top - scrollY,
8630                        dirty.right - scrollX, dirty.bottom - scrollY);
8631                mParent.invalidateChild(this, r);
8632            }
8633        }
8634    }
8635
8636    /**
8637     * Mark the area defined by the rect (l,t,r,b) as needing to be drawn.
8638     * The coordinates of the dirty rect are relative to the view.
8639     * If the view is visible, {@link #onDraw(android.graphics.Canvas)}
8640     * will be called at some point in the future. This must be called from
8641     * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
8642     * @param l the left position of the dirty region
8643     * @param t the top position of the dirty region
8644     * @param r the right position of the dirty region
8645     * @param b the bottom position of the dirty region
8646     */
8647    public void invalidate(int l, int t, int r, int b) {
8648        if (ViewDebug.TRACE_HIERARCHY) {
8649            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8650        }
8651
8652        if (skipInvalidate()) {
8653            return;
8654        }
8655        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8656                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID ||
8657                (mPrivateFlags & INVALIDATED) != INVALIDATED) {
8658            mPrivateFlags &= ~DRAWING_CACHE_VALID;
8659            mPrivateFlags |= INVALIDATED;
8660            mPrivateFlags |= DIRTY;
8661            final ViewParent p = mParent;
8662            final AttachInfo ai = mAttachInfo;
8663            //noinspection PointlessBooleanExpression,ConstantConditions
8664            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8665                if (p != null && ai != null && ai.mHardwareAccelerated) {
8666                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8667                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8668                    p.invalidateChild(this, null);
8669                    return;
8670                }
8671            }
8672            if (p != null && ai != null && l < r && t < b) {
8673                final int scrollX = mScrollX;
8674                final int scrollY = mScrollY;
8675                final Rect tmpr = ai.mTmpInvalRect;
8676                tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
8677                p.invalidateChild(this, tmpr);
8678            }
8679        }
8680    }
8681
8682    /**
8683     * Invalidate the whole view. If the view is visible,
8684     * {@link #onDraw(android.graphics.Canvas)} will be called at some point in
8685     * the future. This must be called from a UI thread. To call from a non-UI thread,
8686     * call {@link #postInvalidate()}.
8687     */
8688    public void invalidate() {
8689        invalidate(true);
8690    }
8691
8692    /**
8693     * This is where the invalidate() work actually happens. A full invalidate()
8694     * causes the drawing cache to be invalidated, but this function can be called with
8695     * invalidateCache set to false to skip that invalidation step for cases that do not
8696     * need it (for example, a component that remains at the same dimensions with the same
8697     * content).
8698     *
8699     * @param invalidateCache Whether the drawing cache for this view should be invalidated as
8700     * well. This is usually true for a full invalidate, but may be set to false if the
8701     * View's contents or dimensions have not changed.
8702     */
8703    void invalidate(boolean invalidateCache) {
8704        if (ViewDebug.TRACE_HIERARCHY) {
8705            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
8706        }
8707
8708        if (skipInvalidate()) {
8709            return;
8710        }
8711        if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS) ||
8712                (invalidateCache && (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) ||
8713                (mPrivateFlags & INVALIDATED) != INVALIDATED || isOpaque() != mLastIsOpaque) {
8714            mLastIsOpaque = isOpaque();
8715            mPrivateFlags &= ~DRAWN;
8716            mPrivateFlags |= DIRTY;
8717            if (invalidateCache) {
8718                mPrivateFlags |= INVALIDATED;
8719                mPrivateFlags &= ~DRAWING_CACHE_VALID;
8720            }
8721            final AttachInfo ai = mAttachInfo;
8722            final ViewParent p = mParent;
8723            //noinspection PointlessBooleanExpression,ConstantConditions
8724            if (!HardwareRenderer.RENDER_DIRTY_REGIONS) {
8725                if (p != null && ai != null && ai.mHardwareAccelerated) {
8726                    // fast-track for GL-enabled applications; just invalidate the whole hierarchy
8727                    // with a null dirty rect, which tells the ViewAncestor to redraw everything
8728                    p.invalidateChild(this, null);
8729                    return;
8730                }
8731            }
8732
8733            if (p != null && ai != null) {
8734                final Rect r = ai.mTmpInvalRect;
8735                r.set(0, 0, mRight - mLeft, mBottom - mTop);
8736                // Don't call invalidate -- we don't want to internally scroll
8737                // our own bounds
8738                p.invalidateChild(this, r);
8739            }
8740        }
8741    }
8742
8743    /**
8744     * Used to indicate that the parent of this view should clear its caches. This functionality
8745     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8746     * which is necessary when various parent-managed properties of the view change, such as
8747     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only
8748     * clears the parent caches and does not causes an invalidate event.
8749     *
8750     * @hide
8751     */
8752    protected void invalidateParentCaches() {
8753        if (mParent instanceof View) {
8754            ((View) mParent).mPrivateFlags |= INVALIDATED;
8755        }
8756    }
8757
8758    /**
8759     * Used to indicate that the parent of this view should be invalidated. This functionality
8760     * is used to force the parent to rebuild its display list (when hardware-accelerated),
8761     * which is necessary when various parent-managed properties of the view change, such as
8762     * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate
8763     * an invalidation event to the parent.
8764     *
8765     * @hide
8766     */
8767    protected void invalidateParentIfNeeded() {
8768        if (isHardwareAccelerated() && mParent instanceof View) {
8769            ((View) mParent).invalidate(true);
8770        }
8771    }
8772
8773    /**
8774     * Indicates whether this View is opaque. An opaque View guarantees that it will
8775     * draw all the pixels overlapping its bounds using a fully opaque color.
8776     *
8777     * Subclasses of View should override this method whenever possible to indicate
8778     * whether an instance is opaque. Opaque Views are treated in a special way by
8779     * the View hierarchy, possibly allowing it to perform optimizations during
8780     * invalidate/draw passes.
8781     *
8782     * @return True if this View is guaranteed to be fully opaque, false otherwise.
8783     */
8784    @ViewDebug.ExportedProperty(category = "drawing")
8785    public boolean isOpaque() {
8786        return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK &&
8787                ((mTransformationInfo != null ? mTransformationInfo.mAlpha : 1)
8788                        >= 1.0f - ViewConfiguration.ALPHA_THRESHOLD);
8789    }
8790
8791    /**
8792     * @hide
8793     */
8794    protected void computeOpaqueFlags() {
8795        // Opaque if:
8796        //   - Has a background
8797        //   - Background is opaque
8798        //   - Doesn't have scrollbars or scrollbars are inside overlay
8799
8800        if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
8801            mPrivateFlags |= OPAQUE_BACKGROUND;
8802        } else {
8803            mPrivateFlags &= ~OPAQUE_BACKGROUND;
8804        }
8805
8806        final int flags = mViewFlags;
8807        if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
8808                (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
8809            mPrivateFlags |= OPAQUE_SCROLLBARS;
8810        } else {
8811            mPrivateFlags &= ~OPAQUE_SCROLLBARS;
8812        }
8813    }
8814
8815    /**
8816     * @hide
8817     */
8818    protected boolean hasOpaqueScrollbars() {
8819        return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
8820    }
8821
8822    /**
8823     * @return A handler associated with the thread running the View. This
8824     * handler can be used to pump events in the UI events queue.
8825     */
8826    public Handler getHandler() {
8827        if (mAttachInfo != null) {
8828            return mAttachInfo.mHandler;
8829        }
8830        return null;
8831    }
8832
8833    /**
8834     * Gets the view root associated with the View.
8835     * @return The view root, or null if none.
8836     * @hide
8837     */
8838    public ViewRootImpl getViewRootImpl() {
8839        if (mAttachInfo != null) {
8840            return mAttachInfo.mViewRootImpl;
8841        }
8842        return null;
8843    }
8844
8845    /**
8846     * <p>Causes the Runnable to be added to the message queue.
8847     * The runnable will be run on the user interface thread.</p>
8848     *
8849     * <p>This method can be invoked from outside of the UI thread
8850     * only when this View is attached to a window.</p>
8851     *
8852     * @param action The Runnable that will be executed.
8853     *
8854     * @return Returns true if the Runnable was successfully placed in to the
8855     *         message queue.  Returns false on failure, usually because the
8856     *         looper processing the message queue is exiting.
8857     */
8858    public boolean post(Runnable action) {
8859        final AttachInfo attachInfo = mAttachInfo;
8860        if (attachInfo != null) {
8861            return attachInfo.mHandler.post(action);
8862        }
8863        // Assume that post will succeed later
8864        ViewRootImpl.getRunQueue().post(action);
8865        return true;
8866    }
8867
8868    /**
8869     * <p>Causes the Runnable to be added to the message queue, to be run
8870     * after the specified amount of time elapses.
8871     * The runnable will be run on the user interface thread.</p>
8872     *
8873     * <p>This method can be invoked from outside of the UI thread
8874     * only when this View is attached to a window.</p>
8875     *
8876     * @param action The Runnable that will be executed.
8877     * @param delayMillis The delay (in milliseconds) until the Runnable
8878     *        will be executed.
8879     *
8880     * @return true if the Runnable was successfully placed in to the
8881     *         message queue.  Returns false on failure, usually because the
8882     *         looper processing the message queue is exiting.  Note that a
8883     *         result of true does not mean the Runnable will be processed --
8884     *         if the looper is quit before the delivery time of the message
8885     *         occurs then the message will be dropped.
8886     */
8887    public boolean postDelayed(Runnable action, long delayMillis) {
8888        final AttachInfo attachInfo = mAttachInfo;
8889        if (attachInfo != null) {
8890            return attachInfo.mHandler.postDelayed(action, delayMillis);
8891        }
8892        // Assume that post will succeed later
8893        ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8894        return true;
8895    }
8896
8897    /**
8898     * <p>Causes the Runnable to execute on the next animation time step.
8899     * The runnable will be run on the user interface thread.</p>
8900     *
8901     * <p>This method can be invoked from outside of the UI thread
8902     * only when this View is attached to a window.</p>
8903     *
8904     * @param action The Runnable that will be executed.
8905     *
8906     * @hide
8907     */
8908    public void postOnAnimation(Runnable action) {
8909        final AttachInfo attachInfo = mAttachInfo;
8910        if (attachInfo != null) {
8911            attachInfo.mViewRootImpl.mChoreographer.postAnimationCallback(action, null);
8912        } else {
8913            // Assume that post will succeed later
8914            ViewRootImpl.getRunQueue().post(action);
8915        }
8916    }
8917
8918    /**
8919     * <p>Causes the Runnable to execute on the next animation time step,
8920     * after the specified amount of time elapses.
8921     * The runnable will be run on the user interface thread.</p>
8922     *
8923     * <p>This method can be invoked from outside of the UI thread
8924     * only when this View is attached to a window.</p>
8925     *
8926     * @param action The Runnable that will be executed.
8927     * @param delayMillis The delay (in milliseconds) until the Runnable
8928     *        will be executed.
8929     *
8930     * @hide
8931     */
8932    public void postOnAnimationDelayed(Runnable action, long delayMillis) {
8933        final AttachInfo attachInfo = mAttachInfo;
8934        if (attachInfo != null) {
8935            attachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed(
8936                    action, null, delayMillis);
8937        } else {
8938            // Assume that post will succeed later
8939            ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
8940        }
8941    }
8942
8943    /**
8944     * <p>Removes the specified Runnable from the message queue.</p>
8945     *
8946     * <p>This method can be invoked from outside of the UI thread
8947     * only when this View is attached to a window.</p>
8948     *
8949     * @param action The Runnable to remove from the message handling queue
8950     *
8951     * @return true if this view could ask the Handler to remove the Runnable,
8952     *         false otherwise. When the returned value is true, the Runnable
8953     *         may or may not have been actually removed from the message queue
8954     *         (for instance, if the Runnable was not in the queue already.)
8955     */
8956    public boolean removeCallbacks(Runnable action) {
8957        if (action != null) {
8958            final AttachInfo attachInfo = mAttachInfo;
8959            if (attachInfo != null) {
8960                attachInfo.mHandler.removeCallbacks(action);
8961                attachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(action, null);
8962            } else {
8963                // Assume that post will succeed later
8964                ViewRootImpl.getRunQueue().removeCallbacks(action);
8965            }
8966        }
8967        return true;
8968    }
8969
8970    /**
8971     * <p>Cause an invalidate to happen on a subsequent cycle through the event loop.
8972     * Use this to invalidate the View from a non-UI thread.</p>
8973     *
8974     * <p>This method can be invoked from outside of the UI thread
8975     * only when this View is attached to a window.</p>
8976     *
8977     * @see #invalidate()
8978     */
8979    public void postInvalidate() {
8980        postInvalidateDelayed(0);
8981    }
8982
8983    /**
8984     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
8985     * through the event loop. Use this to invalidate the View from a non-UI thread.</p>
8986     *
8987     * <p>This method can be invoked from outside of the UI thread
8988     * only when this View is attached to a window.</p>
8989     *
8990     * @param left The left coordinate of the rectangle to invalidate.
8991     * @param top The top coordinate of the rectangle to invalidate.
8992     * @param right The right coordinate of the rectangle to invalidate.
8993     * @param bottom The bottom coordinate of the rectangle to invalidate.
8994     *
8995     * @see #invalidate(int, int, int, int)
8996     * @see #invalidate(Rect)
8997     */
8998    public void postInvalidate(int left, int top, int right, int bottom) {
8999        postInvalidateDelayed(0, left, top, right, bottom);
9000    }
9001
9002    /**
9003     * <p>Cause an invalidate to happen on a subsequent cycle through the event
9004     * loop. Waits for the specified amount of time.</p>
9005     *
9006     * <p>This method can be invoked from outside of the UI thread
9007     * only when this View is attached to a window.</p>
9008     *
9009     * @param delayMilliseconds the duration in milliseconds to delay the
9010     *         invalidation by
9011     */
9012    public void postInvalidateDelayed(long delayMilliseconds) {
9013        // We try only with the AttachInfo because there's no point in invalidating
9014        // if we are not attached to our window
9015        final AttachInfo attachInfo = mAttachInfo;
9016        if (attachInfo != null) {
9017            attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds);
9018        }
9019    }
9020
9021    /**
9022     * <p>Cause an invalidate of the specified area to happen on a subsequent cycle
9023     * through the event loop. Waits for the specified amount of time.</p>
9024     *
9025     * <p>This method can be invoked from outside of the UI thread
9026     * only when this View is attached to a window.</p>
9027     *
9028     * @param delayMilliseconds the duration in milliseconds to delay the
9029     *         invalidation by
9030     * @param left The left coordinate of the rectangle to invalidate.
9031     * @param top The top coordinate of the rectangle to invalidate.
9032     * @param right The right coordinate of the rectangle to invalidate.
9033     * @param bottom The bottom coordinate of the rectangle to invalidate.
9034     */
9035    public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
9036            int right, int bottom) {
9037
9038        // We try only with the AttachInfo because there's no point in invalidating
9039        // if we are not attached to our window
9040        final AttachInfo attachInfo = mAttachInfo;
9041        if (attachInfo != null) {
9042            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9043            info.target = this;
9044            info.left = left;
9045            info.top = top;
9046            info.right = right;
9047            info.bottom = bottom;
9048
9049            attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds);
9050        }
9051    }
9052
9053    /**
9054     * <p>Cause an invalidate to happen on the next animation time step, typically the
9055     * next display frame.</p>
9056     *
9057     * <p>This method can be invoked from outside of the UI thread
9058     * only when this View is attached to a window.</p>
9059     *
9060     * @hide
9061     */
9062    public void postInvalidateOnAnimation() {
9063        // We try only with the AttachInfo because there's no point in invalidating
9064        // if we are not attached to our window
9065        final AttachInfo attachInfo = mAttachInfo;
9066        if (attachInfo != null) {
9067            attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this);
9068        }
9069    }
9070
9071    /**
9072     * <p>Cause an invalidate of the specified area to happen on the next animation
9073     * time step, typically the next display frame.</p>
9074     *
9075     * <p>This method can be invoked from outside of the UI thread
9076     * only when this View is attached to a window.</p>
9077     *
9078     * @param left The left coordinate of the rectangle to invalidate.
9079     * @param top The top coordinate of the rectangle to invalidate.
9080     * @param right The right coordinate of the rectangle to invalidate.
9081     * @param bottom The bottom coordinate of the rectangle to invalidate.
9082     *
9083     * @hide
9084     */
9085    public void postInvalidateOnAnimation(int left, int top, int right, int bottom) {
9086        // We try only with the AttachInfo because there's no point in invalidating
9087        // if we are not attached to our window
9088        final AttachInfo attachInfo = mAttachInfo;
9089        if (attachInfo != null) {
9090            final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
9091            info.target = this;
9092            info.left = left;
9093            info.top = top;
9094            info.right = right;
9095            info.bottom = bottom;
9096
9097            attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info);
9098        }
9099    }
9100
9101    /**
9102     * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event.
9103     * This event is sent at most once every
9104     * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}.
9105     */
9106    private void postSendViewScrolledAccessibilityEventCallback() {
9107        if (mSendViewScrolledAccessibilityEvent == null) {
9108            mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent();
9109        }
9110        if (!mSendViewScrolledAccessibilityEvent.mIsPending) {
9111            mSendViewScrolledAccessibilityEvent.mIsPending = true;
9112            postDelayed(mSendViewScrolledAccessibilityEvent,
9113                    ViewConfiguration.getSendRecurringAccessibilityEventsInterval());
9114        }
9115    }
9116
9117    /**
9118     * Called by a parent to request that a child update its values for mScrollX
9119     * and mScrollY if necessary. This will typically be done if the child is
9120     * animating a scroll using a {@link android.widget.Scroller Scroller}
9121     * object.
9122     */
9123    public void computeScroll() {
9124    }
9125
9126    /**
9127     * <p>Indicate whether the horizontal edges are faded when the view is
9128     * scrolled horizontally.</p>
9129     *
9130     * @return true if the horizontal edges should are faded on scroll, false
9131     *         otherwise
9132     *
9133     * @see #setHorizontalFadingEdgeEnabled(boolean)
9134     * @attr ref android.R.styleable#View_requiresFadingEdge
9135     */
9136    public boolean isHorizontalFadingEdgeEnabled() {
9137        return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
9138    }
9139
9140    /**
9141     * <p>Define whether the horizontal edges should be faded when this view
9142     * is scrolled horizontally.</p>
9143     *
9144     * @param horizontalFadingEdgeEnabled true if the horizontal edges should
9145     *                                    be faded when the view is scrolled
9146     *                                    horizontally
9147     *
9148     * @see #isHorizontalFadingEdgeEnabled()
9149     * @attr ref android.R.styleable#View_requiresFadingEdge
9150     */
9151    public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
9152        if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
9153            if (horizontalFadingEdgeEnabled) {
9154                initScrollCache();
9155            }
9156
9157            mViewFlags ^= FADING_EDGE_HORIZONTAL;
9158        }
9159    }
9160
9161    /**
9162     * <p>Indicate whether the vertical edges are faded when the view is
9163     * scrolled horizontally.</p>
9164     *
9165     * @return true if the vertical edges should are faded on scroll, false
9166     *         otherwise
9167     *
9168     * @see #setVerticalFadingEdgeEnabled(boolean)
9169     * @attr ref android.R.styleable#View_requiresFadingEdge
9170     */
9171    public boolean isVerticalFadingEdgeEnabled() {
9172        return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
9173    }
9174
9175    /**
9176     * <p>Define whether the vertical edges should be faded when this view
9177     * is scrolled vertically.</p>
9178     *
9179     * @param verticalFadingEdgeEnabled true if the vertical edges should
9180     *                                  be faded when the view is scrolled
9181     *                                  vertically
9182     *
9183     * @see #isVerticalFadingEdgeEnabled()
9184     * @attr ref android.R.styleable#View_requiresFadingEdge
9185     */
9186    public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
9187        if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
9188            if (verticalFadingEdgeEnabled) {
9189                initScrollCache();
9190            }
9191
9192            mViewFlags ^= FADING_EDGE_VERTICAL;
9193        }
9194    }
9195
9196    /**
9197     * Returns the strength, or intensity, of the top faded edge. The strength is
9198     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9199     * returns 0.0 or 1.0 but no value in between.
9200     *
9201     * Subclasses should override this method to provide a smoother fade transition
9202     * when scrolling occurs.
9203     *
9204     * @return the intensity of the top fade as a float between 0.0f and 1.0f
9205     */
9206    protected float getTopFadingEdgeStrength() {
9207        return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
9208    }
9209
9210    /**
9211     * Returns the strength, or intensity, of the bottom faded edge. The strength is
9212     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9213     * returns 0.0 or 1.0 but no value in between.
9214     *
9215     * Subclasses should override this method to provide a smoother fade transition
9216     * when scrolling occurs.
9217     *
9218     * @return the intensity of the bottom fade as a float between 0.0f and 1.0f
9219     */
9220    protected float getBottomFadingEdgeStrength() {
9221        return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
9222                computeVerticalScrollRange() ? 1.0f : 0.0f;
9223    }
9224
9225    /**
9226     * Returns the strength, or intensity, of the left faded edge. The strength is
9227     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9228     * returns 0.0 or 1.0 but no value in between.
9229     *
9230     * Subclasses should override this method to provide a smoother fade transition
9231     * when scrolling occurs.
9232     *
9233     * @return the intensity of the left fade as a float between 0.0f and 1.0f
9234     */
9235    protected float getLeftFadingEdgeStrength() {
9236        return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
9237    }
9238
9239    /**
9240     * Returns the strength, or intensity, of the right faded edge. The strength is
9241     * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
9242     * returns 0.0 or 1.0 but no value in between.
9243     *
9244     * Subclasses should override this method to provide a smoother fade transition
9245     * when scrolling occurs.
9246     *
9247     * @return the intensity of the right fade as a float between 0.0f and 1.0f
9248     */
9249    protected float getRightFadingEdgeStrength() {
9250        return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
9251                computeHorizontalScrollRange() ? 1.0f : 0.0f;
9252    }
9253
9254    /**
9255     * <p>Indicate whether the horizontal scrollbar should be drawn or not. The
9256     * scrollbar is not drawn by default.</p>
9257     *
9258     * @return true if the horizontal scrollbar should be painted, false
9259     *         otherwise
9260     *
9261     * @see #setHorizontalScrollBarEnabled(boolean)
9262     */
9263    public boolean isHorizontalScrollBarEnabled() {
9264        return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9265    }
9266
9267    /**
9268     * <p>Define whether the horizontal scrollbar should be drawn or not. The
9269     * scrollbar is not drawn by default.</p>
9270     *
9271     * @param horizontalScrollBarEnabled true if the horizontal scrollbar should
9272     *                                   be painted
9273     *
9274     * @see #isHorizontalScrollBarEnabled()
9275     */
9276    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
9277        if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
9278            mViewFlags ^= SCROLLBARS_HORIZONTAL;
9279            computeOpaqueFlags();
9280            resolvePadding();
9281        }
9282    }
9283
9284    /**
9285     * <p>Indicate whether the vertical scrollbar should be drawn or not. The
9286     * scrollbar is not drawn by default.</p>
9287     *
9288     * @return true if the vertical scrollbar should be painted, false
9289     *         otherwise
9290     *
9291     * @see #setVerticalScrollBarEnabled(boolean)
9292     */
9293    public boolean isVerticalScrollBarEnabled() {
9294        return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
9295    }
9296
9297    /**
9298     * <p>Define whether the vertical scrollbar should be drawn or not. The
9299     * scrollbar is not drawn by default.</p>
9300     *
9301     * @param verticalScrollBarEnabled true if the vertical scrollbar should
9302     *                                 be painted
9303     *
9304     * @see #isVerticalScrollBarEnabled()
9305     */
9306    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
9307        if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
9308            mViewFlags ^= SCROLLBARS_VERTICAL;
9309            computeOpaqueFlags();
9310            resolvePadding();
9311        }
9312    }
9313
9314    /**
9315     * @hide
9316     */
9317    protected void recomputePadding() {
9318        setPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
9319    }
9320
9321    /**
9322     * Define whether scrollbars will fade when the view is not scrolling.
9323     *
9324     * @param fadeScrollbars wheter to enable fading
9325     *
9326     */
9327    public void setScrollbarFadingEnabled(boolean fadeScrollbars) {
9328        initScrollCache();
9329        final ScrollabilityCache scrollabilityCache = mScrollCache;
9330        scrollabilityCache.fadeScrollBars = fadeScrollbars;
9331        if (fadeScrollbars) {
9332            scrollabilityCache.state = ScrollabilityCache.OFF;
9333        } else {
9334            scrollabilityCache.state = ScrollabilityCache.ON;
9335        }
9336    }
9337
9338    /**
9339     *
9340     * Returns true if scrollbars will fade when this view is not scrolling
9341     *
9342     * @return true if scrollbar fading is enabled
9343     */
9344    public boolean isScrollbarFadingEnabled() {
9345        return mScrollCache != null && mScrollCache.fadeScrollBars;
9346    }
9347
9348    /**
9349     * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
9350     * inset. When inset, they add to the padding of the view. And the scrollbars
9351     * can be drawn inside the padding area or on the edge of the view. For example,
9352     * if a view has a background drawable and you want to draw the scrollbars
9353     * inside the padding specified by the drawable, you can use
9354     * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
9355     * appear at the edge of the view, ignoring the padding, then you can use
9356     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
9357     * @param style the style of the scrollbars. Should be one of
9358     * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
9359     * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
9360     * @see #SCROLLBARS_INSIDE_OVERLAY
9361     * @see #SCROLLBARS_INSIDE_INSET
9362     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9363     * @see #SCROLLBARS_OUTSIDE_INSET
9364     */
9365    public void setScrollBarStyle(int style) {
9366        if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
9367            mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
9368            computeOpaqueFlags();
9369            resolvePadding();
9370        }
9371    }
9372
9373    /**
9374     * <p>Returns the current scrollbar style.</p>
9375     * @return the current scrollbar style
9376     * @see #SCROLLBARS_INSIDE_OVERLAY
9377     * @see #SCROLLBARS_INSIDE_INSET
9378     * @see #SCROLLBARS_OUTSIDE_OVERLAY
9379     * @see #SCROLLBARS_OUTSIDE_INSET
9380     */
9381    @ViewDebug.ExportedProperty(mapping = {
9382            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"),
9383            @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"),
9384            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"),
9385            @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET")
9386    })
9387    public int getScrollBarStyle() {
9388        return mViewFlags & SCROLLBARS_STYLE_MASK;
9389    }
9390
9391    /**
9392     * <p>Compute the horizontal range that the horizontal scrollbar
9393     * represents.</p>
9394     *
9395     * <p>The range is expressed in arbitrary units that must be the same as the
9396     * units used by {@link #computeHorizontalScrollExtent()} and
9397     * {@link #computeHorizontalScrollOffset()}.</p>
9398     *
9399     * <p>The default range is the drawing width of this view.</p>
9400     *
9401     * @return the total horizontal range represented by the horizontal
9402     *         scrollbar
9403     *
9404     * @see #computeHorizontalScrollExtent()
9405     * @see #computeHorizontalScrollOffset()
9406     * @see android.widget.ScrollBarDrawable
9407     */
9408    protected int computeHorizontalScrollRange() {
9409        return getWidth();
9410    }
9411
9412    /**
9413     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb
9414     * within the horizontal range. This value is used to compute the position
9415     * of the thumb within the scrollbar's track.</p>
9416     *
9417     * <p>The range is expressed in arbitrary units that must be the same as the
9418     * units used by {@link #computeHorizontalScrollRange()} and
9419     * {@link #computeHorizontalScrollExtent()}.</p>
9420     *
9421     * <p>The default offset is the scroll offset of this view.</p>
9422     *
9423     * @return the horizontal offset of the scrollbar's thumb
9424     *
9425     * @see #computeHorizontalScrollRange()
9426     * @see #computeHorizontalScrollExtent()
9427     * @see android.widget.ScrollBarDrawable
9428     */
9429    protected int computeHorizontalScrollOffset() {
9430        return mScrollX;
9431    }
9432
9433    /**
9434     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb
9435     * within the horizontal range. This value is used to compute the length
9436     * of the thumb within the scrollbar's track.</p>
9437     *
9438     * <p>The range is expressed in arbitrary units that must be the same as the
9439     * units used by {@link #computeHorizontalScrollRange()} and
9440     * {@link #computeHorizontalScrollOffset()}.</p>
9441     *
9442     * <p>The default extent is the drawing width of this view.</p>
9443     *
9444     * @return the horizontal extent of the scrollbar's thumb
9445     *
9446     * @see #computeHorizontalScrollRange()
9447     * @see #computeHorizontalScrollOffset()
9448     * @see android.widget.ScrollBarDrawable
9449     */
9450    protected int computeHorizontalScrollExtent() {
9451        return getWidth();
9452    }
9453
9454    /**
9455     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
9456     *
9457     * <p>The range is expressed in arbitrary units that must be the same as the
9458     * units used by {@link #computeVerticalScrollExtent()} and
9459     * {@link #computeVerticalScrollOffset()}.</p>
9460     *
9461     * @return the total vertical range represented by the vertical scrollbar
9462     *
9463     * <p>The default range is the drawing height of this view.</p>
9464     *
9465     * @see #computeVerticalScrollExtent()
9466     * @see #computeVerticalScrollOffset()
9467     * @see android.widget.ScrollBarDrawable
9468     */
9469    protected int computeVerticalScrollRange() {
9470        return getHeight();
9471    }
9472
9473    /**
9474     * <p>Compute the vertical offset of the vertical scrollbar's thumb
9475     * within the horizontal range. This value is used to compute the position
9476     * of the thumb within the scrollbar's track.</p>
9477     *
9478     * <p>The range is expressed in arbitrary units that must be the same as the
9479     * units used by {@link #computeVerticalScrollRange()} and
9480     * {@link #computeVerticalScrollExtent()}.</p>
9481     *
9482     * <p>The default offset is the scroll offset of this view.</p>
9483     *
9484     * @return the vertical offset of the scrollbar's thumb
9485     *
9486     * @see #computeVerticalScrollRange()
9487     * @see #computeVerticalScrollExtent()
9488     * @see android.widget.ScrollBarDrawable
9489     */
9490    protected int computeVerticalScrollOffset() {
9491        return mScrollY;
9492    }
9493
9494    /**
9495     * <p>Compute the vertical extent of the horizontal scrollbar's thumb
9496     * within the vertical range. This value is used to compute the length
9497     * of the thumb within the scrollbar's track.</p>
9498     *
9499     * <p>The range is expressed in arbitrary units that must be the same as the
9500     * units used by {@link #computeVerticalScrollRange()} and
9501     * {@link #computeVerticalScrollOffset()}.</p>
9502     *
9503     * <p>The default extent is the drawing height of this view.</p>
9504     *
9505     * @return the vertical extent of the scrollbar's thumb
9506     *
9507     * @see #computeVerticalScrollRange()
9508     * @see #computeVerticalScrollOffset()
9509     * @see android.widget.ScrollBarDrawable
9510     */
9511    protected int computeVerticalScrollExtent() {
9512        return getHeight();
9513    }
9514
9515    /**
9516     * Check if this view can be scrolled horizontally in a certain direction.
9517     *
9518     * @param direction Negative to check scrolling left, positive to check scrolling right.
9519     * @return true if this view can be scrolled in the specified direction, false otherwise.
9520     */
9521    public boolean canScrollHorizontally(int direction) {
9522        final int offset = computeHorizontalScrollOffset();
9523        final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent();
9524        if (range == 0) return false;
9525        if (direction < 0) {
9526            return offset > 0;
9527        } else {
9528            return offset < range - 1;
9529        }
9530    }
9531
9532    /**
9533     * Check if this view can be scrolled vertically in a certain direction.
9534     *
9535     * @param direction Negative to check scrolling up, positive to check scrolling down.
9536     * @return true if this view can be scrolled in the specified direction, false otherwise.
9537     */
9538    public boolean canScrollVertically(int direction) {
9539        final int offset = computeVerticalScrollOffset();
9540        final int range = computeVerticalScrollRange() - computeVerticalScrollExtent();
9541        if (range == 0) return false;
9542        if (direction < 0) {
9543            return offset > 0;
9544        } else {
9545            return offset < range - 1;
9546        }
9547    }
9548
9549    /**
9550     * <p>Request the drawing of the horizontal and the vertical scrollbar. The
9551     * scrollbars are painted only if they have been awakened first.</p>
9552     *
9553     * @param canvas the canvas on which to draw the scrollbars
9554     *
9555     * @see #awakenScrollBars(int)
9556     */
9557    protected final void onDrawScrollBars(Canvas canvas) {
9558        // scrollbars are drawn only when the animation is running
9559        final ScrollabilityCache cache = mScrollCache;
9560        if (cache != null) {
9561
9562            int state = cache.state;
9563
9564            if (state == ScrollabilityCache.OFF) {
9565                return;
9566            }
9567
9568            boolean invalidate = false;
9569
9570            if (state == ScrollabilityCache.FADING) {
9571                // We're fading -- get our fade interpolation
9572                if (cache.interpolatorValues == null) {
9573                    cache.interpolatorValues = new float[1];
9574                }
9575
9576                float[] values = cache.interpolatorValues;
9577
9578                // Stops the animation if we're done
9579                if (cache.scrollBarInterpolator.timeToValues(values) ==
9580                        Interpolator.Result.FREEZE_END) {
9581                    cache.state = ScrollabilityCache.OFF;
9582                } else {
9583                    cache.scrollBar.setAlpha(Math.round(values[0]));
9584                }
9585
9586                // This will make the scroll bars inval themselves after
9587                // drawing. We only want this when we're fading so that
9588                // we prevent excessive redraws
9589                invalidate = true;
9590            } else {
9591                // We're just on -- but we may have been fading before so
9592                // reset alpha
9593                cache.scrollBar.setAlpha(255);
9594            }
9595
9596
9597            final int viewFlags = mViewFlags;
9598
9599            final boolean drawHorizontalScrollBar =
9600                (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
9601            final boolean drawVerticalScrollBar =
9602                (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
9603                && !isVerticalScrollBarHidden();
9604
9605            if (drawVerticalScrollBar || drawHorizontalScrollBar) {
9606                final int width = mRight - mLeft;
9607                final int height = mBottom - mTop;
9608
9609                final ScrollBarDrawable scrollBar = cache.scrollBar;
9610
9611                final int scrollX = mScrollX;
9612                final int scrollY = mScrollY;
9613                final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
9614
9615                int left, top, right, bottom;
9616
9617                if (drawHorizontalScrollBar) {
9618                    int size = scrollBar.getSize(false);
9619                    if (size <= 0) {
9620                        size = cache.scrollBarSize;
9621                    }
9622
9623                    scrollBar.setParameters(computeHorizontalScrollRange(),
9624                                            computeHorizontalScrollOffset(),
9625                                            computeHorizontalScrollExtent(), false);
9626                    final int verticalScrollBarGap = drawVerticalScrollBar ?
9627                            getVerticalScrollbarWidth() : 0;
9628                    top = scrollY + height - size - (mUserPaddingBottom & inside);
9629                    left = scrollX + (mPaddingLeft & inside);
9630                    right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap;
9631                    bottom = top + size;
9632                    onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom);
9633                    if (invalidate) {
9634                        invalidate(left, top, right, bottom);
9635                    }
9636                }
9637
9638                if (drawVerticalScrollBar) {
9639                    int size = scrollBar.getSize(true);
9640                    if (size <= 0) {
9641                        size = cache.scrollBarSize;
9642                    }
9643
9644                    scrollBar.setParameters(computeVerticalScrollRange(),
9645                                            computeVerticalScrollOffset(),
9646                                            computeVerticalScrollExtent(), true);
9647                    switch (mVerticalScrollbarPosition) {
9648                        default:
9649                        case SCROLLBAR_POSITION_DEFAULT:
9650                        case SCROLLBAR_POSITION_RIGHT:
9651                            left = scrollX + width - size - (mUserPaddingRight & inside);
9652                            break;
9653                        case SCROLLBAR_POSITION_LEFT:
9654                            left = scrollX + (mUserPaddingLeft & inside);
9655                            break;
9656                    }
9657                    top = scrollY + (mPaddingTop & inside);
9658                    right = left + size;
9659                    bottom = scrollY + height - (mUserPaddingBottom & inside);
9660                    onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom);
9661                    if (invalidate) {
9662                        invalidate(left, top, right, bottom);
9663                    }
9664                }
9665            }
9666        }
9667    }
9668
9669    /**
9670     * Override this if the vertical scrollbar needs to be hidden in a subclass, like when
9671     * FastScroller is visible.
9672     * @return whether to temporarily hide the vertical scrollbar
9673     * @hide
9674     */
9675    protected boolean isVerticalScrollBarHidden() {
9676        return false;
9677    }
9678
9679    /**
9680     * <p>Draw the horizontal scrollbar if
9681     * {@link #isHorizontalScrollBarEnabled()} returns true.</p>
9682     *
9683     * @param canvas the canvas on which to draw the scrollbar
9684     * @param scrollBar the scrollbar's drawable
9685     *
9686     * @see #isHorizontalScrollBarEnabled()
9687     * @see #computeHorizontalScrollRange()
9688     * @see #computeHorizontalScrollExtent()
9689     * @see #computeHorizontalScrollOffset()
9690     * @see android.widget.ScrollBarDrawable
9691     * @hide
9692     */
9693    protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar,
9694            int l, int t, int r, int b) {
9695        scrollBar.setBounds(l, t, r, b);
9696        scrollBar.draw(canvas);
9697    }
9698
9699    /**
9700     * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
9701     * returns true.</p>
9702     *
9703     * @param canvas the canvas on which to draw the scrollbar
9704     * @param scrollBar the scrollbar's drawable
9705     *
9706     * @see #isVerticalScrollBarEnabled()
9707     * @see #computeVerticalScrollRange()
9708     * @see #computeVerticalScrollExtent()
9709     * @see #computeVerticalScrollOffset()
9710     * @see android.widget.ScrollBarDrawable
9711     * @hide
9712     */
9713    protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar,
9714            int l, int t, int r, int b) {
9715        scrollBar.setBounds(l, t, r, b);
9716        scrollBar.draw(canvas);
9717    }
9718
9719    /**
9720     * Implement this to do your drawing.
9721     *
9722     * @param canvas the canvas on which the background will be drawn
9723     */
9724    protected void onDraw(Canvas canvas) {
9725    }
9726
9727    /*
9728     * Caller is responsible for calling requestLayout if necessary.
9729     * (This allows addViewInLayout to not request a new layout.)
9730     */
9731    void assignParent(ViewParent parent) {
9732        if (mParent == null) {
9733            mParent = parent;
9734        } else if (parent == null) {
9735            mParent = null;
9736        } else {
9737            throw new RuntimeException("view " + this + " being added, but"
9738                    + " it already has a parent");
9739        }
9740    }
9741
9742    /**
9743     * This is called when the view is attached to a window.  At this point it
9744     * has a Surface and will start drawing.  Note that this function is
9745     * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)},
9746     * however it may be called any time before the first onDraw -- including
9747     * before or after {@link #onMeasure(int, int)}.
9748     *
9749     * @see #onDetachedFromWindow()
9750     */
9751    protected void onAttachedToWindow() {
9752        if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
9753            mParent.requestTransparentRegion(this);
9754        }
9755        if ((mPrivateFlags & AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) {
9756            initialAwakenScrollBars();
9757            mPrivateFlags &= ~AWAKEN_SCROLL_BARS_ON_ATTACH;
9758        }
9759        jumpDrawablesToCurrentState();
9760        // Order is important here: LayoutDirection MUST be resolved before Padding
9761        // and TextDirection
9762        resolveLayoutDirectionIfNeeded();
9763        resolvePadding();
9764        resolveTextDirection();
9765        if (isFocused()) {
9766            InputMethodManager imm = InputMethodManager.peekInstance();
9767            imm.focusIn(this);
9768        }
9769    }
9770
9771    /**
9772     * @see #onScreenStateChanged(int)
9773     */
9774    void dispatchScreenStateChanged(int screenState) {
9775        onScreenStateChanged(screenState);
9776    }
9777
9778    /**
9779     * This method is called whenever the state of the screen this view is
9780     * attached to changes. A state change will usually occurs when the screen
9781     * turns on or off (whether it happens automatically or the user does it
9782     * manually.)
9783     *
9784     * @param screenState The new state of the screen. Can be either
9785     *                    {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF}
9786     */
9787    public void onScreenStateChanged(int screenState) {
9788    }
9789
9790    /**
9791     * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing
9792     * that the parent directionality can and will be resolved before its children.
9793     */
9794    private void resolveLayoutDirectionIfNeeded() {
9795        // Do not resolve if it is not needed
9796        if ((mPrivateFlags2 & LAYOUT_DIRECTION_RESOLVED) == LAYOUT_DIRECTION_RESOLVED) return;
9797
9798        // Clear any previous layout direction resolution
9799        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED_RTL;
9800
9801        // Set resolved depending on layout direction
9802        switch (getLayoutDirection()) {
9803            case LAYOUT_DIRECTION_INHERIT:
9804                // We cannot do the resolution if there is no parent
9805                if (mParent == null) return;
9806
9807                // If this is root view, no need to look at parent's layout dir.
9808                if (mParent instanceof ViewGroup) {
9809                    ViewGroup viewGroup = ((ViewGroup) mParent);
9810
9811                    // Check if the parent view group can resolve
9812                    if (! viewGroup.canResolveLayoutDirection()) {
9813                        return;
9814                    }
9815                    if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
9816                        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9817                    }
9818                }
9819                break;
9820            case LAYOUT_DIRECTION_RTL:
9821                mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9822                break;
9823            case LAYOUT_DIRECTION_LOCALE:
9824                if(isLayoutDirectionRtl(Locale.getDefault())) {
9825                    mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
9826                }
9827                break;
9828            default:
9829                // Nothing to do, LTR by default
9830        }
9831
9832        // Set to resolved
9833        mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED;
9834        onResolvedLayoutDirectionChanged();
9835        // Resolve padding
9836        resolvePadding();
9837    }
9838
9839    /**
9840     * Called when layout direction has been resolved.
9841     *
9842     * The default implementation does nothing.
9843     */
9844    public void onResolvedLayoutDirectionChanged() {
9845    }
9846
9847    /**
9848     * Resolve padding depending on layout direction.
9849     */
9850    public void resolvePadding() {
9851        // If the user specified the absolute padding (either with android:padding or
9852        // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
9853        // use the default padding or the padding from the background drawable
9854        // (stored at this point in mPadding*)
9855        int resolvedLayoutDirection = getResolvedLayoutDirection();
9856        switch (resolvedLayoutDirection) {
9857            case LAYOUT_DIRECTION_RTL:
9858                // Start user padding override Right user padding. Otherwise, if Right user
9859                // padding is not defined, use the default Right padding. If Right user padding
9860                // is defined, just use it.
9861                if (mUserPaddingStart >= 0) {
9862                    mUserPaddingRight = mUserPaddingStart;
9863                } else if (mUserPaddingRight < 0) {
9864                    mUserPaddingRight = mPaddingRight;
9865                }
9866                if (mUserPaddingEnd >= 0) {
9867                    mUserPaddingLeft = mUserPaddingEnd;
9868                } else if (mUserPaddingLeft < 0) {
9869                    mUserPaddingLeft = mPaddingLeft;
9870                }
9871                break;
9872            case LAYOUT_DIRECTION_LTR:
9873            default:
9874                // Start user padding override Left user padding. Otherwise, if Left user
9875                // padding is not defined, use the default left padding. If Left user padding
9876                // is defined, just use it.
9877                if (mUserPaddingStart >= 0) {
9878                    mUserPaddingLeft = mUserPaddingStart;
9879                } else if (mUserPaddingLeft < 0) {
9880                    mUserPaddingLeft = mPaddingLeft;
9881                }
9882                if (mUserPaddingEnd >= 0) {
9883                    mUserPaddingRight = mUserPaddingEnd;
9884                } else if (mUserPaddingRight < 0) {
9885                    mUserPaddingRight = mPaddingRight;
9886                }
9887        }
9888
9889        mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom;
9890
9891        if(isPaddingRelative()) {
9892            setPaddingRelative(mUserPaddingStart, mPaddingTop, mUserPaddingEnd, mUserPaddingBottom);
9893        } else {
9894            recomputePadding();
9895        }
9896        onPaddingChanged(resolvedLayoutDirection);
9897    }
9898
9899    /**
9900     * Resolve padding depending on the layout direction. Subclasses that care about
9901     * padding resolution should override this method. The default implementation does
9902     * nothing.
9903     *
9904     * @param layoutDirection the direction of the layout
9905     *
9906     * @see {@link #LAYOUT_DIRECTION_LTR}
9907     * @see {@link #LAYOUT_DIRECTION_RTL}
9908     */
9909    public void onPaddingChanged(int layoutDirection) {
9910    }
9911
9912    /**
9913     * Check if layout direction resolution can be done.
9914     *
9915     * @return true if layout direction resolution can be done otherwise return false.
9916     */
9917    public boolean canResolveLayoutDirection() {
9918        switch (getLayoutDirection()) {
9919            case LAYOUT_DIRECTION_INHERIT:
9920                return (mParent != null);
9921            default:
9922                return true;
9923        }
9924    }
9925
9926    /**
9927     * Reset the resolved layout direction. Will call {@link View#onResolvedLayoutDirectionReset}
9928     * when reset is done.
9929     */
9930    public void resetResolvedLayoutDirection() {
9931        // Reset the current View resolution
9932        mPrivateFlags2 &= ~LAYOUT_DIRECTION_RESOLVED;
9933        onResolvedLayoutDirectionReset();
9934        // Reset also the text direction
9935        resetResolvedTextDirection();
9936    }
9937
9938    /**
9939     * Called during reset of resolved layout direction.
9940     *
9941     * Subclasses need to override this method to clear cached information that depends on the
9942     * resolved layout direction, or to inform child views that inherit their layout direction.
9943     *
9944     * The default implementation does nothing.
9945     */
9946    public void onResolvedLayoutDirectionReset() {
9947    }
9948
9949    /**
9950     * Check if a Locale uses an RTL script.
9951     *
9952     * @param locale Locale to check
9953     * @return true if the Locale uses an RTL script.
9954     */
9955    protected static boolean isLayoutDirectionRtl(Locale locale) {
9956        return (LAYOUT_DIRECTION_RTL == LocaleUtil.getLayoutDirectionFromLocale(locale));
9957    }
9958
9959    /**
9960     * This is called when the view is detached from a window.  At this point it
9961     * no longer has a surface for drawing.
9962     *
9963     * @see #onAttachedToWindow()
9964     */
9965    protected void onDetachedFromWindow() {
9966        mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
9967
9968        removeUnsetPressCallback();
9969        removeLongPressCallback();
9970        removePerformClickCallback();
9971        removeSendViewScrolledAccessibilityEventCallback();
9972
9973        destroyDrawingCache();
9974
9975        destroyLayer();
9976
9977        if (mDisplayList != null) {
9978            mDisplayList.postInvalidate(mAttachInfo.mHandler);
9979        }
9980
9981        if (mAttachInfo != null) {
9982            mAttachInfo.mViewRootImpl.cancelInvalidate(this);
9983        }
9984
9985        mCurrentAnimation = null;
9986
9987        resetResolvedLayoutDirection();
9988    }
9989
9990    /**
9991     * @return The number of times this view has been attached to a window
9992     */
9993    protected int getWindowAttachCount() {
9994        return mWindowAttachCount;
9995    }
9996
9997    /**
9998     * Retrieve a unique token identifying the window this view is attached to.
9999     * @return Return the window's token for use in
10000     * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
10001     */
10002    public IBinder getWindowToken() {
10003        return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
10004    }
10005
10006    /**
10007     * Retrieve a unique token identifying the top-level "real" window of
10008     * the window that this view is attached to.  That is, this is like
10009     * {@link #getWindowToken}, except if the window this view in is a panel
10010     * window (attached to another containing window), then the token of
10011     * the containing window is returned instead.
10012     *
10013     * @return Returns the associated window token, either
10014     * {@link #getWindowToken()} or the containing window's token.
10015     */
10016    public IBinder getApplicationWindowToken() {
10017        AttachInfo ai = mAttachInfo;
10018        if (ai != null) {
10019            IBinder appWindowToken = ai.mPanelParentWindowToken;
10020            if (appWindowToken == null) {
10021                appWindowToken = ai.mWindowToken;
10022            }
10023            return appWindowToken;
10024        }
10025        return null;
10026    }
10027
10028    /**
10029     * Retrieve private session object this view hierarchy is using to
10030     * communicate with the window manager.
10031     * @return the session object to communicate with the window manager
10032     */
10033    /*package*/ IWindowSession getWindowSession() {
10034        return mAttachInfo != null ? mAttachInfo.mSession : null;
10035    }
10036
10037    /**
10038     * @param info the {@link android.view.View.AttachInfo} to associated with
10039     *        this view
10040     */
10041    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
10042        //System.out.println("Attached! " + this);
10043        mAttachInfo = info;
10044        mWindowAttachCount++;
10045        // We will need to evaluate the drawable state at least once.
10046        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
10047        if (mFloatingTreeObserver != null) {
10048            info.mTreeObserver.merge(mFloatingTreeObserver);
10049            mFloatingTreeObserver = null;
10050        }
10051        if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
10052            mAttachInfo.mScrollContainers.add(this);
10053            mPrivateFlags |= SCROLL_CONTAINER_ADDED;
10054        }
10055        performCollectViewAttributes(visibility);
10056        onAttachedToWindow();
10057
10058        ListenerInfo li = mListenerInfo;
10059        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10060                li != null ? li.mOnAttachStateChangeListeners : null;
10061        if (listeners != null && listeners.size() > 0) {
10062            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10063            // perform the dispatching. The iterator is a safe guard against listeners that
10064            // could mutate the list by calling the various add/remove methods. This prevents
10065            // the array from being modified while we iterate it.
10066            for (OnAttachStateChangeListener listener : listeners) {
10067                listener.onViewAttachedToWindow(this);
10068            }
10069        }
10070
10071        int vis = info.mWindowVisibility;
10072        if (vis != GONE) {
10073            onWindowVisibilityChanged(vis);
10074        }
10075        if ((mPrivateFlags&DRAWABLE_STATE_DIRTY) != 0) {
10076            // If nobody has evaluated the drawable state yet, then do it now.
10077            refreshDrawableState();
10078        }
10079    }
10080
10081    void dispatchDetachedFromWindow() {
10082        AttachInfo info = mAttachInfo;
10083        if (info != null) {
10084            int vis = info.mWindowVisibility;
10085            if (vis != GONE) {
10086                onWindowVisibilityChanged(GONE);
10087            }
10088        }
10089
10090        onDetachedFromWindow();
10091
10092        ListenerInfo li = mListenerInfo;
10093        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
10094                li != null ? li.mOnAttachStateChangeListeners : null;
10095        if (listeners != null && listeners.size() > 0) {
10096            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
10097            // perform the dispatching. The iterator is a safe guard against listeners that
10098            // could mutate the list by calling the various add/remove methods. This prevents
10099            // the array from being modified while we iterate it.
10100            for (OnAttachStateChangeListener listener : listeners) {
10101                listener.onViewDetachedFromWindow(this);
10102            }
10103        }
10104
10105        if ((mPrivateFlags & SCROLL_CONTAINER_ADDED) != 0) {
10106            mAttachInfo.mScrollContainers.remove(this);
10107            mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
10108        }
10109
10110        mAttachInfo = null;
10111    }
10112
10113    /**
10114     * Store this view hierarchy's frozen state into the given container.
10115     *
10116     * @param container The SparseArray in which to save the view's state.
10117     *
10118     * @see #restoreHierarchyState(android.util.SparseArray)
10119     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10120     * @see #onSaveInstanceState()
10121     */
10122    public void saveHierarchyState(SparseArray<Parcelable> container) {
10123        dispatchSaveInstanceState(container);
10124    }
10125
10126    /**
10127     * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for
10128     * this view and its children. May be overridden to modify how freezing happens to a
10129     * view's children; for example, some views may want to not store state for their children.
10130     *
10131     * @param container The SparseArray in which to save the view's state.
10132     *
10133     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10134     * @see #saveHierarchyState(android.util.SparseArray)
10135     * @see #onSaveInstanceState()
10136     */
10137    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
10138        if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
10139            mPrivateFlags &= ~SAVE_STATE_CALLED;
10140            Parcelable state = onSaveInstanceState();
10141            if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10142                throw new IllegalStateException(
10143                        "Derived class did not call super.onSaveInstanceState()");
10144            }
10145            if (state != null) {
10146                // Log.i("View", "Freezing #" + Integer.toHexString(mID)
10147                // + ": " + state);
10148                container.put(mID, state);
10149            }
10150        }
10151    }
10152
10153    /**
10154     * Hook allowing a view to generate a representation of its internal state
10155     * that can later be used to create a new instance with that same state.
10156     * This state should only contain information that is not persistent or can
10157     * not be reconstructed later. For example, you will never store your
10158     * current position on screen because that will be computed again when a
10159     * new instance of the view is placed in its view hierarchy.
10160     * <p>
10161     * Some examples of things you may store here: the current cursor position
10162     * in a text view (but usually not the text itself since that is stored in a
10163     * content provider or other persistent storage), the currently selected
10164     * item in a list view.
10165     *
10166     * @return Returns a Parcelable object containing the view's current dynamic
10167     *         state, or null if there is nothing interesting to save. The
10168     *         default implementation returns null.
10169     * @see #onRestoreInstanceState(android.os.Parcelable)
10170     * @see #saveHierarchyState(android.util.SparseArray)
10171     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10172     * @see #setSaveEnabled(boolean)
10173     */
10174    protected Parcelable onSaveInstanceState() {
10175        mPrivateFlags |= SAVE_STATE_CALLED;
10176        return BaseSavedState.EMPTY_STATE;
10177    }
10178
10179    /**
10180     * Restore this view hierarchy's frozen state from the given container.
10181     *
10182     * @param container The SparseArray which holds previously frozen states.
10183     *
10184     * @see #saveHierarchyState(android.util.SparseArray)
10185     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10186     * @see #onRestoreInstanceState(android.os.Parcelable)
10187     */
10188    public void restoreHierarchyState(SparseArray<Parcelable> container) {
10189        dispatchRestoreInstanceState(container);
10190    }
10191
10192    /**
10193     * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the
10194     * state for this view and its children. May be overridden to modify how restoring
10195     * happens to a view's children; for example, some views may want to not store state
10196     * for their children.
10197     *
10198     * @param container The SparseArray which holds previously saved state.
10199     *
10200     * @see #dispatchSaveInstanceState(android.util.SparseArray)
10201     * @see #restoreHierarchyState(android.util.SparseArray)
10202     * @see #onRestoreInstanceState(android.os.Parcelable)
10203     */
10204    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
10205        if (mID != NO_ID) {
10206            Parcelable state = container.get(mID);
10207            if (state != null) {
10208                // Log.i("View", "Restoreing #" + Integer.toHexString(mID)
10209                // + ": " + state);
10210                mPrivateFlags &= ~SAVE_STATE_CALLED;
10211                onRestoreInstanceState(state);
10212                if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
10213                    throw new IllegalStateException(
10214                            "Derived class did not call super.onRestoreInstanceState()");
10215                }
10216            }
10217        }
10218    }
10219
10220    /**
10221     * Hook allowing a view to re-apply a representation of its internal state that had previously
10222     * been generated by {@link #onSaveInstanceState}. This function will never be called with a
10223     * null state.
10224     *
10225     * @param state The frozen state that had previously been returned by
10226     *        {@link #onSaveInstanceState}.
10227     *
10228     * @see #onSaveInstanceState()
10229     * @see #restoreHierarchyState(android.util.SparseArray)
10230     * @see #dispatchRestoreInstanceState(android.util.SparseArray)
10231     */
10232    protected void onRestoreInstanceState(Parcelable state) {
10233        mPrivateFlags |= SAVE_STATE_CALLED;
10234        if (state != BaseSavedState.EMPTY_STATE && state != null) {
10235            throw new IllegalArgumentException("Wrong state class, expecting View State but "
10236                    + "received " + state.getClass().toString() + " instead. This usually happens "
10237                    + "when two views of different type have the same id in the same hierarchy. "
10238                    + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure "
10239                    + "other views do not use the same id.");
10240        }
10241    }
10242
10243    /**
10244     * <p>Return the time at which the drawing of the view hierarchy started.</p>
10245     *
10246     * @return the drawing start time in milliseconds
10247     */
10248    public long getDrawingTime() {
10249        return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
10250    }
10251
10252    /**
10253     * <p>Enables or disables the duplication of the parent's state into this view. When
10254     * duplication is enabled, this view gets its drawable state from its parent rather
10255     * than from its own internal properties.</p>
10256     *
10257     * <p>Note: in the current implementation, setting this property to true after the
10258     * view was added to a ViewGroup might have no effect at all. This property should
10259     * always be used from XML or set to true before adding this view to a ViewGroup.</p>
10260     *
10261     * <p>Note: if this view's parent addStateFromChildren property is enabled and this
10262     * property is enabled, an exception will be thrown.</p>
10263     *
10264     * <p>Note: if the child view uses and updates additionnal states which are unknown to the
10265     * parent, these states should not be affected by this method.</p>
10266     *
10267     * @param enabled True to enable duplication of the parent's drawable state, false
10268     *                to disable it.
10269     *
10270     * @see #getDrawableState()
10271     * @see #isDuplicateParentStateEnabled()
10272     */
10273    public void setDuplicateParentStateEnabled(boolean enabled) {
10274        setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
10275    }
10276
10277    /**
10278     * <p>Indicates whether this duplicates its drawable state from its parent.</p>
10279     *
10280     * @return True if this view's drawable state is duplicated from the parent,
10281     *         false otherwise
10282     *
10283     * @see #getDrawableState()
10284     * @see #setDuplicateParentStateEnabled(boolean)
10285     */
10286    public boolean isDuplicateParentStateEnabled() {
10287        return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
10288    }
10289
10290    /**
10291     * <p>Specifies the type of layer backing this view. The layer can be
10292     * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
10293     * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
10294     *
10295     * <p>A layer is associated with an optional {@link android.graphics.Paint}
10296     * instance that controls how the layer is composed on screen. The following
10297     * properties of the paint are taken into account when composing the layer:</p>
10298     * <ul>
10299     * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
10300     * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
10301     * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
10302     * </ul>
10303     *
10304     * <p>If this view has an alpha value set to < 1.0 by calling
10305     * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
10306     * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
10307     * equivalent to setting a hardware layer on this view and providing a paint with
10308     * the desired alpha value.<p>
10309     *
10310     * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
10311     * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
10312     * for more information on when and how to use layers.</p>
10313     *
10314     * @param layerType The ype of layer to use with this view, must be one of
10315     *        {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10316     *        {@link #LAYER_TYPE_HARDWARE}
10317     * @param paint The paint used to compose the layer. This argument is optional
10318     *        and can be null. It is ignored when the layer type is
10319     *        {@link #LAYER_TYPE_NONE}
10320     *
10321     * @see #getLayerType()
10322     * @see #LAYER_TYPE_NONE
10323     * @see #LAYER_TYPE_SOFTWARE
10324     * @see #LAYER_TYPE_HARDWARE
10325     * @see #setAlpha(float)
10326     *
10327     * @attr ref android.R.styleable#View_layerType
10328     */
10329    public void setLayerType(int layerType, Paint paint) {
10330        if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
10331            throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
10332                    + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
10333        }
10334
10335        if (layerType == mLayerType) {
10336            if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) {
10337                mLayerPaint = paint == null ? new Paint() : paint;
10338                invalidateParentCaches();
10339                invalidate(true);
10340            }
10341            return;
10342        }
10343
10344        // Destroy any previous software drawing cache if needed
10345        switch (mLayerType) {
10346            case LAYER_TYPE_HARDWARE:
10347                destroyLayer();
10348                // fall through - non-accelerated views may use software layer mechanism instead
10349            case LAYER_TYPE_SOFTWARE:
10350                destroyDrawingCache();
10351                break;
10352            default:
10353                break;
10354        }
10355
10356        mLayerType = layerType;
10357        final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE;
10358        mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint);
10359        mLocalDirtyRect = layerDisabled ? null : new Rect();
10360
10361        invalidateParentCaches();
10362        invalidate(true);
10363    }
10364
10365    /**
10366     * Indicates whether this view has a static layer. A view with layer type
10367     * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
10368     * dynamic.
10369     */
10370    boolean hasStaticLayer() {
10371        return true;
10372    }
10373
10374    /**
10375     * Indicates what type of layer is currently associated with this view. By default
10376     * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
10377     * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
10378     * for more information on the different types of layers.
10379     *
10380     * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
10381     *         {@link #LAYER_TYPE_HARDWARE}
10382     *
10383     * @see #setLayerType(int, android.graphics.Paint)
10384     * @see #buildLayer()
10385     * @see #LAYER_TYPE_NONE
10386     * @see #LAYER_TYPE_SOFTWARE
10387     * @see #LAYER_TYPE_HARDWARE
10388     */
10389    public int getLayerType() {
10390        return mLayerType;
10391    }
10392
10393    /**
10394     * Forces this view's layer to be created and this view to be rendered
10395     * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE},
10396     * invoking this method will have no effect.
10397     *
10398     * This method can for instance be used to render a view into its layer before
10399     * starting an animation. If this view is complex, rendering into the layer
10400     * before starting the animation will avoid skipping frames.
10401     *
10402     * @throws IllegalStateException If this view is not attached to a window
10403     *
10404     * @see #setLayerType(int, android.graphics.Paint)
10405     */
10406    public void buildLayer() {
10407        if (mLayerType == LAYER_TYPE_NONE) return;
10408
10409        if (mAttachInfo == null) {
10410            throw new IllegalStateException("This view must be attached to a window first");
10411        }
10412
10413        switch (mLayerType) {
10414            case LAYER_TYPE_HARDWARE:
10415                if (mAttachInfo.mHardwareRenderer != null &&
10416                        mAttachInfo.mHardwareRenderer.isEnabled() &&
10417                        mAttachInfo.mHardwareRenderer.validate()) {
10418                    getHardwareLayer();
10419                }
10420                break;
10421            case LAYER_TYPE_SOFTWARE:
10422                buildDrawingCache(true);
10423                break;
10424        }
10425    }
10426
10427    // Make sure the HardwareRenderer.validate() was invoked before calling this method
10428    void flushLayer() {
10429        if (mLayerType == LAYER_TYPE_HARDWARE && mHardwareLayer != null) {
10430            mHardwareLayer.flush();
10431        }
10432    }
10433
10434    /**
10435     * <p>Returns a hardware layer that can be used to draw this view again
10436     * without executing its draw method.</p>
10437     *
10438     * @return A HardwareLayer ready to render, or null if an error occurred.
10439     */
10440    HardwareLayer getHardwareLayer() {
10441        if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null ||
10442                !mAttachInfo.mHardwareRenderer.isEnabled()) {
10443            return null;
10444        }
10445
10446        if (!mAttachInfo.mHardwareRenderer.validate()) return null;
10447
10448        final int width = mRight - mLeft;
10449        final int height = mBottom - mTop;
10450
10451        if (width == 0 || height == 0) {
10452            return null;
10453        }
10454
10455        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) {
10456            if (mHardwareLayer == null) {
10457                mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer(
10458                        width, height, isOpaque());
10459                mLocalDirtyRect.set(0, 0, width, height);
10460            } else if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) {
10461                mHardwareLayer.resize(width, height);
10462                mLocalDirtyRect.set(0, 0, width, height);
10463            }
10464
10465            // The layer is not valid if the underlying GPU resources cannot be allocated
10466            if (!mHardwareLayer.isValid()) {
10467                return null;
10468            }
10469
10470            mHardwareLayer.redraw(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect);
10471            mLocalDirtyRect.setEmpty();
10472        }
10473
10474        return mHardwareLayer;
10475    }
10476
10477    /**
10478     * Destroys this View's hardware layer if possible.
10479     *
10480     * @return True if the layer was destroyed, false otherwise.
10481     *
10482     * @see #setLayerType(int, android.graphics.Paint)
10483     * @see #LAYER_TYPE_HARDWARE
10484     */
10485    boolean destroyLayer() {
10486        if (mHardwareLayer != null) {
10487            AttachInfo info = mAttachInfo;
10488            if (info != null && info.mHardwareRenderer != null &&
10489                    info.mHardwareRenderer.isEnabled() && info.mHardwareRenderer.validate()) {
10490                mHardwareLayer.destroy();
10491                mHardwareLayer = null;
10492
10493                invalidate(true);
10494                invalidateParentCaches();
10495            }
10496            return true;
10497        }
10498        return false;
10499    }
10500
10501    /**
10502     * Destroys all hardware rendering resources. This method is invoked
10503     * when the system needs to reclaim resources. Upon execution of this
10504     * method, you should free any OpenGL resources created by the view.
10505     *
10506     * Note: you <strong>must</strong> call
10507     * <code>super.destroyHardwareResources()</code> when overriding
10508     * this method.
10509     *
10510     * @hide
10511     */
10512    protected void destroyHardwareResources() {
10513        destroyLayer();
10514    }
10515
10516    /**
10517     * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
10518     * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
10519     * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
10520     * the cache is enabled. To benefit from the cache, you must request the drawing cache by
10521     * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
10522     * null.</p>
10523     *
10524     * <p>Enabling the drawing cache is similar to
10525     * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
10526     * acceleration is turned off. When hardware acceleration is turned on, enabling the
10527     * drawing cache has no effect on rendering because the system uses a different mechanism
10528     * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even
10529     * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)}
10530     * for information on how to enable software and hardware layers.</p>
10531     *
10532     * <p>This API can be used to manually generate
10533     * a bitmap copy of this view, by setting the flag to <code>true</code> and calling
10534     * {@link #getDrawingCache()}.</p>
10535     *
10536     * @param enabled true to enable the drawing cache, false otherwise
10537     *
10538     * @see #isDrawingCacheEnabled()
10539     * @see #getDrawingCache()
10540     * @see #buildDrawingCache()
10541     * @see #setLayerType(int, android.graphics.Paint)
10542     */
10543    public void setDrawingCacheEnabled(boolean enabled) {
10544        mCachingFailed = false;
10545        setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
10546    }
10547
10548    /**
10549     * <p>Indicates whether the drawing cache is enabled for this view.</p>
10550     *
10551     * @return true if the drawing cache is enabled
10552     *
10553     * @see #setDrawingCacheEnabled(boolean)
10554     * @see #getDrawingCache()
10555     */
10556    @ViewDebug.ExportedProperty(category = "drawing")
10557    public boolean isDrawingCacheEnabled() {
10558        return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
10559    }
10560
10561    /**
10562     * Debugging utility which recursively outputs the dirty state of a view and its
10563     * descendants.
10564     *
10565     * @hide
10566     */
10567    @SuppressWarnings({"UnusedDeclaration"})
10568    public void outputDirtyFlags(String indent, boolean clear, int clearMask) {
10569        Log.d("View", indent + this + "             DIRTY(" + (mPrivateFlags & View.DIRTY_MASK) +
10570                ") DRAWN(" + (mPrivateFlags & DRAWN) + ")" + " CACHE_VALID(" +
10571                (mPrivateFlags & View.DRAWING_CACHE_VALID) +
10572                ") INVALIDATED(" + (mPrivateFlags & INVALIDATED) + ")");
10573        if (clear) {
10574            mPrivateFlags &= clearMask;
10575        }
10576        if (this instanceof ViewGroup) {
10577            ViewGroup parent = (ViewGroup) this;
10578            final int count = parent.getChildCount();
10579            for (int i = 0; i < count; i++) {
10580                final View child = parent.getChildAt(i);
10581                child.outputDirtyFlags(indent + "  ", clear, clearMask);
10582            }
10583        }
10584    }
10585
10586    /**
10587     * This method is used by ViewGroup to cause its children to restore or recreate their
10588     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
10589     * to recreate its own display list, which would happen if it went through the normal
10590     * draw/dispatchDraw mechanisms.
10591     *
10592     * @hide
10593     */
10594    protected void dispatchGetDisplayList() {}
10595
10596    /**
10597     * A view that is not attached or hardware accelerated cannot create a display list.
10598     * This method checks these conditions and returns the appropriate result.
10599     *
10600     * @return true if view has the ability to create a display list, false otherwise.
10601     *
10602     * @hide
10603     */
10604    public boolean canHaveDisplayList() {
10605        return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null);
10606    }
10607
10608    /**
10609     * @return The HardwareRenderer associated with that view or null if hardware rendering
10610     * is not supported or this this has not been attached to a window.
10611     *
10612     * @hide
10613     */
10614    public HardwareRenderer getHardwareRenderer() {
10615        if (mAttachInfo != null) {
10616            return mAttachInfo.mHardwareRenderer;
10617        }
10618        return null;
10619    }
10620
10621    /**
10622     * Returns a DisplayList. If the incoming displayList is null, one will be created.
10623     * Otherwise, the same display list will be returned (after having been rendered into
10624     * along the way, depending on the invalidation state of the view).
10625     *
10626     * @param displayList The previous version of this displayList, could be null.
10627     * @param isLayer Whether the requester of the display list is a layer. If so,
10628     * the view will avoid creating a layer inside the resulting display list.
10629     * @return A new or reused DisplayList object.
10630     */
10631    private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) {
10632        if (!canHaveDisplayList()) {
10633            return null;
10634        }
10635
10636        if (((mPrivateFlags & DRAWING_CACHE_VALID) == 0 ||
10637                displayList == null || !displayList.isValid() ||
10638                (!isLayer && mRecreateDisplayList))) {
10639            // Don't need to recreate the display list, just need to tell our
10640            // children to restore/recreate theirs
10641            if (displayList != null && displayList.isValid() &&
10642                    !isLayer && !mRecreateDisplayList) {
10643                mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10644                mPrivateFlags &= ~DIRTY_MASK;
10645                dispatchGetDisplayList();
10646
10647                return displayList;
10648            }
10649
10650            if (!isLayer) {
10651                // If we got here, we're recreating it. Mark it as such to ensure that
10652                // we copy in child display lists into ours in drawChild()
10653                mRecreateDisplayList = true;
10654            }
10655            if (displayList == null) {
10656                final String name = getClass().getSimpleName();
10657                displayList = mAttachInfo.mHardwareRenderer.createDisplayList(name);
10658                // If we're creating a new display list, make sure our parent gets invalidated
10659                // since they will need to recreate their display list to account for this
10660                // new child display list.
10661                invalidateParentCaches();
10662            }
10663
10664            boolean caching = false;
10665            final HardwareCanvas canvas = displayList.start();
10666            int restoreCount = 0;
10667            int width = mRight - mLeft;
10668            int height = mBottom - mTop;
10669
10670            try {
10671                canvas.setViewport(width, height);
10672                // The dirty rect should always be null for a display list
10673                canvas.onPreDraw(null);
10674                int layerType = (
10675                        !(mParent instanceof ViewGroup) || ((ViewGroup)mParent).mDrawLayers) ?
10676                        getLayerType() : LAYER_TYPE_NONE;
10677                if (!isLayer && layerType == LAYER_TYPE_HARDWARE && USE_DISPLAY_LIST_PROPERTIES) {
10678                    final HardwareLayer layer = getHardwareLayer();
10679                    if (layer != null && layer.isValid()) {
10680                        canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint);
10681                    } else {
10682                        canvas.saveLayer(0, 0,
10683                                mRight - mLeft, mBottom - mTop, mLayerPaint,
10684                                Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
10685                    }
10686                    caching = true;
10687                } else {
10688
10689                    computeScroll();
10690
10691                    if (!USE_DISPLAY_LIST_PROPERTIES) {
10692                        restoreCount = canvas.save();
10693                    }
10694                    canvas.translate(-mScrollX, -mScrollY);
10695                    if (!isLayer) {
10696                        mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10697                        mPrivateFlags &= ~DIRTY_MASK;
10698                    }
10699
10700                    // Fast path for layouts with no backgrounds
10701                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
10702                        dispatchDraw(canvas);
10703                    } else {
10704                        draw(canvas);
10705                    }
10706                }
10707            } finally {
10708                if (USE_DISPLAY_LIST_PROPERTIES) {
10709                    canvas.restoreToCount(restoreCount);
10710                }
10711                canvas.onPostDraw();
10712
10713                displayList.end();
10714                if (USE_DISPLAY_LIST_PROPERTIES) {
10715                    displayList.setCaching(caching);
10716                }
10717                if (isLayer && USE_DISPLAY_LIST_PROPERTIES) {
10718                    displayList.setLeftTopRightBottom(0, 0, width, height);
10719                } else {
10720                    setDisplayListProperties(displayList);
10721                }
10722            }
10723        } else if (!isLayer) {
10724            mPrivateFlags |= DRAWN | DRAWING_CACHE_VALID;
10725            mPrivateFlags &= ~DIRTY_MASK;
10726        }
10727
10728        return displayList;
10729    }
10730
10731    /**
10732     * Get the DisplayList for the HardwareLayer
10733     *
10734     * @param layer The HardwareLayer whose DisplayList we want
10735     * @return A DisplayList fopr the specified HardwareLayer
10736     */
10737    private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) {
10738        DisplayList displayList = getDisplayList(layer.getDisplayList(), true);
10739        layer.setDisplayList(displayList);
10740        return displayList;
10741    }
10742
10743
10744    /**
10745     * <p>Returns a display list that can be used to draw this view again
10746     * without executing its draw method.</p>
10747     *
10748     * @return A DisplayList ready to replay, or null if caching is not enabled.
10749     *
10750     * @hide
10751     */
10752    public DisplayList getDisplayList() {
10753        mDisplayList = getDisplayList(mDisplayList, false);
10754        return mDisplayList;
10755    }
10756
10757    /**
10758     * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p>
10759     *
10760     * @return A non-scaled bitmap representing this view or null if cache is disabled.
10761     *
10762     * @see #getDrawingCache(boolean)
10763     */
10764    public Bitmap getDrawingCache() {
10765        return getDrawingCache(false);
10766    }
10767
10768    /**
10769     * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
10770     * is null when caching is disabled. If caching is enabled and the cache is not ready,
10771     * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
10772     * draw from the cache when the cache is enabled. To benefit from the cache, you must
10773     * request the drawing cache by calling this method and draw it on screen if the
10774     * returned bitmap is not null.</p>
10775     *
10776     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10777     * this method will create a bitmap of the same size as this view. Because this bitmap
10778     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10779     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10780     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10781     * size than the view. This implies that your application must be able to handle this
10782     * size.</p>
10783     *
10784     * @param autoScale Indicates whether the generated bitmap should be scaled based on
10785     *        the current density of the screen when the application is in compatibility
10786     *        mode.
10787     *
10788     * @return A bitmap representing this view or null if cache is disabled.
10789     *
10790     * @see #setDrawingCacheEnabled(boolean)
10791     * @see #isDrawingCacheEnabled()
10792     * @see #buildDrawingCache(boolean)
10793     * @see #destroyDrawingCache()
10794     */
10795    public Bitmap getDrawingCache(boolean autoScale) {
10796        if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
10797            return null;
10798        }
10799        if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
10800            buildDrawingCache(autoScale);
10801        }
10802        return autoScale ? mDrawingCache : mUnscaledDrawingCache;
10803    }
10804
10805    /**
10806     * <p>Frees the resources used by the drawing cache. If you call
10807     * {@link #buildDrawingCache()} manually without calling
10808     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10809     * should cleanup the cache with this method afterwards.</p>
10810     *
10811     * @see #setDrawingCacheEnabled(boolean)
10812     * @see #buildDrawingCache()
10813     * @see #getDrawingCache()
10814     */
10815    public void destroyDrawingCache() {
10816        if (mDrawingCache != null) {
10817            mDrawingCache.recycle();
10818            mDrawingCache = null;
10819        }
10820        if (mUnscaledDrawingCache != null) {
10821            mUnscaledDrawingCache.recycle();
10822            mUnscaledDrawingCache = null;
10823        }
10824    }
10825
10826    /**
10827     * Setting a solid background color for the drawing cache's bitmaps will improve
10828     * performance and memory usage. Note, though that this should only be used if this
10829     * view will always be drawn on top of a solid color.
10830     *
10831     * @param color The background color to use for the drawing cache's bitmap
10832     *
10833     * @see #setDrawingCacheEnabled(boolean)
10834     * @see #buildDrawingCache()
10835     * @see #getDrawingCache()
10836     */
10837    public void setDrawingCacheBackgroundColor(int color) {
10838        if (color != mDrawingCacheBackgroundColor) {
10839            mDrawingCacheBackgroundColor = color;
10840            mPrivateFlags &= ~DRAWING_CACHE_VALID;
10841        }
10842    }
10843
10844    /**
10845     * @see #setDrawingCacheBackgroundColor(int)
10846     *
10847     * @return The background color to used for the drawing cache's bitmap
10848     */
10849    public int getDrawingCacheBackgroundColor() {
10850        return mDrawingCacheBackgroundColor;
10851    }
10852
10853    /**
10854     * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p>
10855     *
10856     * @see #buildDrawingCache(boolean)
10857     */
10858    public void buildDrawingCache() {
10859        buildDrawingCache(false);
10860    }
10861
10862    /**
10863     * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
10864     *
10865     * <p>If you call {@link #buildDrawingCache()} manually without calling
10866     * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
10867     * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
10868     *
10869     * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled,
10870     * this method will create a bitmap of the same size as this view. Because this bitmap
10871     * will be drawn scaled by the parent ViewGroup, the result on screen might show
10872     * scaling artifacts. To avoid such artifacts, you should call this method by setting
10873     * the auto scaling to true. Doing so, however, will generate a bitmap of a different
10874     * size than the view. This implies that your application must be able to handle this
10875     * size.</p>
10876     *
10877     * <p>You should avoid calling this method when hardware acceleration is enabled. If
10878     * you do not need the drawing cache bitmap, calling this method will increase memory
10879     * usage and cause the view to be rendered in software once, thus negatively impacting
10880     * performance.</p>
10881     *
10882     * @see #getDrawingCache()
10883     * @see #destroyDrawingCache()
10884     */
10885    public void buildDrawingCache(boolean autoScale) {
10886        if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || (autoScale ?
10887                mDrawingCache == null : mUnscaledDrawingCache == null)) {
10888            mCachingFailed = false;
10889
10890            if (ViewDebug.TRACE_HIERARCHY) {
10891                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
10892            }
10893
10894            int width = mRight - mLeft;
10895            int height = mBottom - mTop;
10896
10897            final AttachInfo attachInfo = mAttachInfo;
10898            final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired;
10899
10900            if (autoScale && scalingRequired) {
10901                width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
10902                height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
10903            }
10904
10905            final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
10906            final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque();
10907            final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache;
10908
10909            if (width <= 0 || height <= 0 ||
10910                     // Projected bitmap size in bytes
10911                    (width * height * (opaque && !use32BitCache ? 2 : 4) >
10912                            ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
10913                destroyDrawingCache();
10914                mCachingFailed = true;
10915                return;
10916            }
10917
10918            boolean clear = true;
10919            Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache;
10920
10921            if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
10922                Bitmap.Config quality;
10923                if (!opaque) {
10924                    // Never pick ARGB_4444 because it looks awful
10925                    // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case
10926                    switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
10927                        case DRAWING_CACHE_QUALITY_AUTO:
10928                            quality = Bitmap.Config.ARGB_8888;
10929                            break;
10930                        case DRAWING_CACHE_QUALITY_LOW:
10931                            quality = Bitmap.Config.ARGB_8888;
10932                            break;
10933                        case DRAWING_CACHE_QUALITY_HIGH:
10934                            quality = Bitmap.Config.ARGB_8888;
10935                            break;
10936                        default:
10937                            quality = Bitmap.Config.ARGB_8888;
10938                            break;
10939                    }
10940                } else {
10941                    // Optimization for translucent windows
10942                    // If the window is translucent, use a 32 bits bitmap to benefit from memcpy()
10943                    quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
10944                }
10945
10946                // Try to cleanup memory
10947                if (bitmap != null) bitmap.recycle();
10948
10949                try {
10950                    bitmap = Bitmap.createBitmap(width, height, quality);
10951                    bitmap.setDensity(getResources().getDisplayMetrics().densityDpi);
10952                    if (autoScale) {
10953                        mDrawingCache = bitmap;
10954                    } else {
10955                        mUnscaledDrawingCache = bitmap;
10956                    }
10957                    if (opaque && use32BitCache) bitmap.setHasAlpha(false);
10958                } catch (OutOfMemoryError e) {
10959                    // If there is not enough memory to create the bitmap cache, just
10960                    // ignore the issue as bitmap caches are not required to draw the
10961                    // view hierarchy
10962                    if (autoScale) {
10963                        mDrawingCache = null;
10964                    } else {
10965                        mUnscaledDrawingCache = null;
10966                    }
10967                    mCachingFailed = true;
10968                    return;
10969                }
10970
10971                clear = drawingCacheBackgroundColor != 0;
10972            }
10973
10974            Canvas canvas;
10975            if (attachInfo != null) {
10976                canvas = attachInfo.mCanvas;
10977                if (canvas == null) {
10978                    canvas = new Canvas();
10979                }
10980                canvas.setBitmap(bitmap);
10981                // Temporarily clobber the cached Canvas in case one of our children
10982                // is also using a drawing cache. Without this, the children would
10983                // steal the canvas by attaching their own bitmap to it and bad, bad
10984                // thing would happen (invisible views, corrupted drawings, etc.)
10985                attachInfo.mCanvas = null;
10986            } else {
10987                // This case should hopefully never or seldom happen
10988                canvas = new Canvas(bitmap);
10989            }
10990
10991            if (clear) {
10992                bitmap.eraseColor(drawingCacheBackgroundColor);
10993            }
10994
10995            computeScroll();
10996            final int restoreCount = canvas.save();
10997
10998            if (autoScale && scalingRequired) {
10999                final float scale = attachInfo.mApplicationScale;
11000                canvas.scale(scale, scale);
11001            }
11002
11003            canvas.translate(-mScrollX, -mScrollY);
11004
11005            mPrivateFlags |= DRAWN;
11006            if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
11007                    mLayerType != LAYER_TYPE_NONE) {
11008                mPrivateFlags |= DRAWING_CACHE_VALID;
11009            }
11010
11011            // Fast path for layouts with no backgrounds
11012            if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11013                if (ViewDebug.TRACE_HIERARCHY) {
11014                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11015                }
11016                mPrivateFlags &= ~DIRTY_MASK;
11017                dispatchDraw(canvas);
11018            } else {
11019                draw(canvas);
11020            }
11021
11022            canvas.restoreToCount(restoreCount);
11023            canvas.setBitmap(null);
11024
11025            if (attachInfo != null) {
11026                // Restore the cached Canvas for our siblings
11027                attachInfo.mCanvas = canvas;
11028            }
11029        }
11030    }
11031
11032    /**
11033     * Create a snapshot of the view into a bitmap.  We should probably make
11034     * some form of this public, but should think about the API.
11035     */
11036    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
11037        int width = mRight - mLeft;
11038        int height = mBottom - mTop;
11039
11040        final AttachInfo attachInfo = mAttachInfo;
11041        final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f;
11042        width = (int) ((width * scale) + 0.5f);
11043        height = (int) ((height * scale) + 0.5f);
11044
11045        Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, height > 0 ? height : 1, quality);
11046        if (bitmap == null) {
11047            throw new OutOfMemoryError();
11048        }
11049
11050        Resources resources = getResources();
11051        if (resources != null) {
11052            bitmap.setDensity(resources.getDisplayMetrics().densityDpi);
11053        }
11054
11055        Canvas canvas;
11056        if (attachInfo != null) {
11057            canvas = attachInfo.mCanvas;
11058            if (canvas == null) {
11059                canvas = new Canvas();
11060            }
11061            canvas.setBitmap(bitmap);
11062            // Temporarily clobber the cached Canvas in case one of our children
11063            // is also using a drawing cache. Without this, the children would
11064            // steal the canvas by attaching their own bitmap to it and bad, bad
11065            // things would happen (invisible views, corrupted drawings, etc.)
11066            attachInfo.mCanvas = null;
11067        } else {
11068            // This case should hopefully never or seldom happen
11069            canvas = new Canvas(bitmap);
11070        }
11071
11072        if ((backgroundColor & 0xff000000) != 0) {
11073            bitmap.eraseColor(backgroundColor);
11074        }
11075
11076        computeScroll();
11077        final int restoreCount = canvas.save();
11078        canvas.scale(scale, scale);
11079        canvas.translate(-mScrollX, -mScrollY);
11080
11081        // Temporarily remove the dirty mask
11082        int flags = mPrivateFlags;
11083        mPrivateFlags &= ~DIRTY_MASK;
11084
11085        // Fast path for layouts with no backgrounds
11086        if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11087            dispatchDraw(canvas);
11088        } else {
11089            draw(canvas);
11090        }
11091
11092        mPrivateFlags = flags;
11093
11094        canvas.restoreToCount(restoreCount);
11095        canvas.setBitmap(null);
11096
11097        if (attachInfo != null) {
11098            // Restore the cached Canvas for our siblings
11099            attachInfo.mCanvas = canvas;
11100        }
11101
11102        return bitmap;
11103    }
11104
11105    /**
11106     * Indicates whether this View is currently in edit mode. A View is usually
11107     * in edit mode when displayed within a developer tool. For instance, if
11108     * this View is being drawn by a visual user interface builder, this method
11109     * should return true.
11110     *
11111     * Subclasses should check the return value of this method to provide
11112     * different behaviors if their normal behavior might interfere with the
11113     * host environment. For instance: the class spawns a thread in its
11114     * constructor, the drawing code relies on device-specific features, etc.
11115     *
11116     * This method is usually checked in the drawing code of custom widgets.
11117     *
11118     * @return True if this View is in edit mode, false otherwise.
11119     */
11120    public boolean isInEditMode() {
11121        return false;
11122    }
11123
11124    /**
11125     * If the View draws content inside its padding and enables fading edges,
11126     * it needs to support padding offsets. Padding offsets are added to the
11127     * fading edges to extend the length of the fade so that it covers pixels
11128     * drawn inside the padding.
11129     *
11130     * Subclasses of this class should override this method if they need
11131     * to draw content inside the padding.
11132     *
11133     * @return True if padding offset must be applied, false otherwise.
11134     *
11135     * @see #getLeftPaddingOffset()
11136     * @see #getRightPaddingOffset()
11137     * @see #getTopPaddingOffset()
11138     * @see #getBottomPaddingOffset()
11139     *
11140     * @since CURRENT
11141     */
11142    protected boolean isPaddingOffsetRequired() {
11143        return false;
11144    }
11145
11146    /**
11147     * Amount by which to extend the left fading region. Called only when
11148     * {@link #isPaddingOffsetRequired()} returns true.
11149     *
11150     * @return The left padding offset in pixels.
11151     *
11152     * @see #isPaddingOffsetRequired()
11153     *
11154     * @since CURRENT
11155     */
11156    protected int getLeftPaddingOffset() {
11157        return 0;
11158    }
11159
11160    /**
11161     * Amount by which to extend the right fading region. Called only when
11162     * {@link #isPaddingOffsetRequired()} returns true.
11163     *
11164     * @return The right padding offset in pixels.
11165     *
11166     * @see #isPaddingOffsetRequired()
11167     *
11168     * @since CURRENT
11169     */
11170    protected int getRightPaddingOffset() {
11171        return 0;
11172    }
11173
11174    /**
11175     * Amount by which to extend the top fading region. Called only when
11176     * {@link #isPaddingOffsetRequired()} returns true.
11177     *
11178     * @return The top padding offset in pixels.
11179     *
11180     * @see #isPaddingOffsetRequired()
11181     *
11182     * @since CURRENT
11183     */
11184    protected int getTopPaddingOffset() {
11185        return 0;
11186    }
11187
11188    /**
11189     * Amount by which to extend the bottom fading region. Called only when
11190     * {@link #isPaddingOffsetRequired()} returns true.
11191     *
11192     * @return The bottom padding offset in pixels.
11193     *
11194     * @see #isPaddingOffsetRequired()
11195     *
11196     * @since CURRENT
11197     */
11198    protected int getBottomPaddingOffset() {
11199        return 0;
11200    }
11201
11202    /**
11203     * @hide
11204     * @param offsetRequired
11205     */
11206    protected int getFadeTop(boolean offsetRequired) {
11207        int top = mPaddingTop;
11208        if (offsetRequired) top += getTopPaddingOffset();
11209        return top;
11210    }
11211
11212    /**
11213     * @hide
11214     * @param offsetRequired
11215     */
11216    protected int getFadeHeight(boolean offsetRequired) {
11217        int padding = mPaddingTop;
11218        if (offsetRequired) padding += getTopPaddingOffset();
11219        return mBottom - mTop - mPaddingBottom - padding;
11220    }
11221
11222    /**
11223     * <p>Indicates whether this view is attached to a hardware accelerated
11224     * window or not.</p>
11225     *
11226     * <p>Even if this method returns true, it does not mean that every call
11227     * to {@link #draw(android.graphics.Canvas)} will be made with an hardware
11228     * accelerated {@link android.graphics.Canvas}. For instance, if this view
11229     * is drawn onto an offscreen {@link android.graphics.Bitmap} and its
11230     * window is hardware accelerated,
11231     * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely
11232     * return false, and this method will return true.</p>
11233     *
11234     * @return True if the view is attached to a window and the window is
11235     *         hardware accelerated; false in any other case.
11236     */
11237    public boolean isHardwareAccelerated() {
11238        return mAttachInfo != null && mAttachInfo.mHardwareAccelerated;
11239    }
11240
11241    /**
11242     * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common
11243     * case of an active Animation being run on the view.
11244     */
11245    private boolean drawAnimation(ViewGroup parent, long drawingTime,
11246            Animation a, boolean scalingRequired) {
11247        Transformation invalidationTransform;
11248        final int flags = parent.mGroupFlags;
11249        final boolean initialized = a.isInitialized();
11250        if (!initialized) {
11251            a.initialize(mRight - mLeft, mBottom - mTop, getWidth(), getHeight());
11252            a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop);
11253            onAnimationStart();
11254        }
11255
11256        boolean more = a.getTransformation(drawingTime, parent.mChildTransformation, 1f);
11257        if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
11258            if (parent.mInvalidationTransformation == null) {
11259                parent.mInvalidationTransformation = new Transformation();
11260            }
11261            invalidationTransform = parent.mInvalidationTransformation;
11262            a.getTransformation(drawingTime, invalidationTransform, 1f);
11263        } else {
11264            invalidationTransform = parent.mChildTransformation;
11265        }
11266        if (more) {
11267            if (!a.willChangeBounds()) {
11268                if ((flags & (parent.FLAG_OPTIMIZE_INVALIDATE | parent.FLAG_ANIMATION_DONE)) ==
11269                        parent.FLAG_OPTIMIZE_INVALIDATE) {
11270                    parent.mGroupFlags |= parent.FLAG_INVALIDATE_REQUIRED;
11271                } else if ((flags & parent.FLAG_INVALIDATE_REQUIRED) == 0) {
11272                    // The child need to draw an animation, potentially offscreen, so
11273                    // make sure we do not cancel invalidate requests
11274                    parent.mPrivateFlags |= DRAW_ANIMATION;
11275                    parent.invalidate(mLeft, mTop, mRight, mBottom);
11276                }
11277            } else {
11278                if (parent.mInvalidateRegion == null) {
11279                    parent.mInvalidateRegion = new RectF();
11280                }
11281                final RectF region = parent.mInvalidateRegion;
11282                a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region,
11283                        invalidationTransform);
11284
11285                // The child need to draw an animation, potentially offscreen, so
11286                // make sure we do not cancel invalidate requests
11287                parent.mPrivateFlags |= DRAW_ANIMATION;
11288
11289                final int left = mLeft + (int) region.left;
11290                final int top = mTop + (int) region.top;
11291                parent.invalidate(left, top, left + (int) (region.width() + .5f),
11292                        top + (int) (region.height() + .5f));
11293            }
11294        }
11295        return more;
11296    }
11297
11298    void setDisplayListProperties() {
11299        setDisplayListProperties(mDisplayList);
11300    }
11301
11302    /**
11303     * This method is called by getDisplayList() when a display list is created or re-rendered.
11304     * It sets or resets the current value of all properties on that display list (resetting is
11305     * necessary when a display list is being re-created, because we need to make sure that
11306     * previously-set transform values
11307     */
11308    void setDisplayListProperties(DisplayList displayList) {
11309        if (USE_DISPLAY_LIST_PROPERTIES && displayList != null) {
11310            displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
11311            if (mParent instanceof ViewGroup) {
11312                displayList.setClipChildren(
11313                        (((ViewGroup)mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0);
11314            }
11315            if (mAttachInfo != null && mAttachInfo.mScalingRequired &&
11316                    mAttachInfo.mApplicationScale != 1.0f) {
11317                displayList.setApplicationScale(1f / mAttachInfo.mApplicationScale);
11318            }
11319            if (mTransformationInfo != null) {
11320                displayList.setTransformationInfo(mTransformationInfo.mAlpha,
11321                        mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY,
11322                        mTransformationInfo.mRotation, mTransformationInfo.mRotationX,
11323                        mTransformationInfo.mRotationY, mTransformationInfo.mScaleX,
11324                        mTransformationInfo.mScaleY);
11325                displayList.setCameraDistance(getCameraDistance());
11326                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == PIVOT_EXPLICITLY_SET) {
11327                    displayList.setPivotX(getPivotX());
11328                    displayList.setPivotY(getPivotY());
11329                }
11330            }
11331        }
11332    }
11333
11334    /**
11335     * This method is called by ViewGroup.drawChild() to have each child view draw itself.
11336     * This draw() method is an implementation detail and is not intended to be overridden or
11337     * to be called from anywhere else other than ViewGroup.drawChild().
11338     */
11339    boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
11340        boolean useDisplayListProperties = USE_DISPLAY_LIST_PROPERTIES && mAttachInfo != null &&
11341                mAttachInfo.mHardwareAccelerated;
11342        boolean more = false;
11343        final boolean childHasIdentityMatrix = hasIdentityMatrix();
11344        final int flags = parent.mGroupFlags;
11345
11346        if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) {
11347            parent.mChildTransformation.clear();
11348            parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11349        }
11350
11351        Transformation transformToApply = null;
11352        boolean concatMatrix = false;
11353
11354        boolean scalingRequired = false;
11355        boolean caching;
11356        int layerType = parent.mDrawLayers ? getLayerType() : LAYER_TYPE_NONE;
11357
11358        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
11359        if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 ||
11360                (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) {
11361            caching = true;
11362            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
11363        } else {
11364            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
11365        }
11366
11367        final Animation a = getAnimation();
11368        if (a != null) {
11369            more = drawAnimation(parent, drawingTime, a, scalingRequired);
11370            concatMatrix = a.willChangeTransformationMatrix();
11371            transformToApply = parent.mChildTransformation;
11372        } else if ((flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
11373            final boolean hasTransform =
11374                    parent.getChildStaticTransformation(this, parent.mChildTransformation);
11375            if (hasTransform) {
11376                final int transformType = parent.mChildTransformation.getTransformationType();
11377                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
11378                        parent.mChildTransformation : null;
11379                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
11380            }
11381        }
11382
11383        concatMatrix |= !childHasIdentityMatrix;
11384
11385        // Sets the flag as early as possible to allow draw() implementations
11386        // to call invalidate() successfully when doing animations
11387        mPrivateFlags |= DRAWN;
11388
11389        if (!concatMatrix && canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) &&
11390                (mPrivateFlags & DRAW_ANIMATION) == 0) {
11391            return more;
11392        }
11393
11394        if (hardwareAccelerated) {
11395            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
11396            // retain the flag's value temporarily in the mRecreateDisplayList flag
11397            mRecreateDisplayList = (mPrivateFlags & INVALIDATED) == INVALIDATED;
11398            mPrivateFlags &= ~INVALIDATED;
11399        }
11400
11401        computeScroll();
11402
11403        final int sx = mScrollX;
11404        final int sy = mScrollY;
11405
11406        DisplayList displayList = null;
11407        Bitmap cache = null;
11408        boolean hasDisplayList = false;
11409        if (caching) {
11410            if (!hardwareAccelerated) {
11411                if (layerType != LAYER_TYPE_NONE) {
11412                    layerType = LAYER_TYPE_SOFTWARE;
11413                    buildDrawingCache(true);
11414                }
11415                cache = getDrawingCache(true);
11416            } else {
11417                switch (layerType) {
11418                    case LAYER_TYPE_SOFTWARE:
11419                        buildDrawingCache(true);
11420                        cache = getDrawingCache(true);
11421                        break;
11422                    case LAYER_TYPE_HARDWARE:
11423                        if (useDisplayListProperties) {
11424                            hasDisplayList = canHaveDisplayList();
11425                        }
11426                        break;
11427                    case LAYER_TYPE_NONE:
11428                        // Delay getting the display list until animation-driven alpha values are
11429                        // set up and possibly passed on to the view
11430                        hasDisplayList = canHaveDisplayList();
11431                        break;
11432                }
11433            }
11434        }
11435        useDisplayListProperties &= hasDisplayList;
11436
11437        final boolean hasNoCache = cache == null || hasDisplayList;
11438        final boolean offsetForScroll = cache == null && !hasDisplayList &&
11439                layerType != LAYER_TYPE_HARDWARE;
11440
11441        int restoreTo = -1;
11442        if (!useDisplayListProperties) {
11443            restoreTo = canvas.save();
11444        }
11445        if (offsetForScroll) {
11446            canvas.translate(mLeft - sx, mTop - sy);
11447        } else {
11448            if (!useDisplayListProperties) {
11449                canvas.translate(mLeft, mTop);
11450            }
11451            if (scalingRequired) {
11452                if (useDisplayListProperties) {
11453                    restoreTo = canvas.save();
11454                }
11455                // mAttachInfo cannot be null, otherwise scalingRequired == false
11456                final float scale = 1.0f / mAttachInfo.mApplicationScale;
11457                canvas.scale(scale, scale);
11458            }
11459        }
11460
11461        float alpha = useDisplayListProperties ? 1 : getAlpha();
11462        if (transformToApply != null || alpha < 1.0f || !hasIdentityMatrix()) {
11463            if (transformToApply != null || !childHasIdentityMatrix) {
11464                int transX = 0;
11465                int transY = 0;
11466
11467                if (offsetForScroll) {
11468                    transX = -sx;
11469                    transY = -sy;
11470                }
11471
11472                if (transformToApply != null) {
11473                    if (concatMatrix) {
11474                        // Undo the scroll translation, apply the transformation matrix,
11475                        // then redo the scroll translate to get the correct result.
11476                        if (!useDisplayListProperties) {
11477                            canvas.translate(-transX, -transY);
11478                            canvas.concat(transformToApply.getMatrix());
11479                            canvas.translate(transX, transY);
11480                        }
11481                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11482                    }
11483
11484                    float transformAlpha = transformToApply.getAlpha();
11485                    if (transformAlpha < 1.0f) {
11486                        alpha *= transformToApply.getAlpha();
11487                        parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11488                    }
11489                }
11490
11491                if (!childHasIdentityMatrix && !useDisplayListProperties) {
11492                    canvas.translate(-transX, -transY);
11493                    canvas.concat(getMatrix());
11494                    canvas.translate(transX, transY);
11495                }
11496            }
11497
11498            if (alpha < 1.0f) {
11499                parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION;
11500                if (hasNoCache) {
11501                    final int multipliedAlpha = (int) (255 * alpha);
11502                    if (!onSetAlpha(multipliedAlpha)) {
11503                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11504                        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 ||
11505                                layerType != LAYER_TYPE_NONE) {
11506                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
11507                        }
11508                        if (layerType == LAYER_TYPE_NONE) {
11509                            if (!useDisplayListProperties) {
11510                                final int scrollX = hasDisplayList ? 0 : sx;
11511                                final int scrollY = hasDisplayList ? 0 : sy;
11512                                canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft,
11513                                        scrollY + mBottom - mTop, multipliedAlpha, layerFlags);
11514                            }
11515                        }
11516                    } else {
11517                        // Alpha is handled by the child directly, clobber the layer's alpha
11518                        mPrivateFlags |= ALPHA_SET;
11519                    }
11520                }
11521            }
11522        } else if ((mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11523            onSetAlpha(255);
11524            mPrivateFlags &= ~ALPHA_SET;
11525        }
11526
11527        if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN &&
11528                !useDisplayListProperties) {
11529            if (offsetForScroll) {
11530                canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop));
11531            } else {
11532                if (!scalingRequired || cache == null) {
11533                    canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop);
11534                } else {
11535                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
11536                }
11537            }
11538        }
11539
11540        if (hasDisplayList) {
11541            displayList = getDisplayList();
11542            if (!displayList.isValid()) {
11543                // Uncommon, but possible. If a view is removed from the hierarchy during the call
11544                // to getDisplayList(), the display list will be marked invalid and we should not
11545                // try to use it again.
11546                displayList = null;
11547                hasDisplayList = false;
11548            }
11549        }
11550
11551        if (hasNoCache) {
11552            boolean layerRendered = false;
11553            if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) {
11554                final HardwareLayer layer = getHardwareLayer();
11555                if (layer != null && layer.isValid()) {
11556                    mLayerPaint.setAlpha((int) (alpha * 255));
11557                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint);
11558                    layerRendered = true;
11559                } else {
11560                    final int scrollX = hasDisplayList ? 0 : sx;
11561                    final int scrollY = hasDisplayList ? 0 : sy;
11562                    canvas.saveLayer(scrollX, scrollY,
11563                            scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint,
11564                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
11565                }
11566            }
11567
11568            if (!layerRendered) {
11569                if (!hasDisplayList) {
11570                    // Fast path for layouts with no backgrounds
11571                    if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
11572                        if (ViewDebug.TRACE_HIERARCHY) {
11573                            ViewDebug.trace(parent, ViewDebug.HierarchyTraceType.DRAW);
11574                        }
11575                        mPrivateFlags &= ~DIRTY_MASK;
11576                        dispatchDraw(canvas);
11577                    } else {
11578                        draw(canvas);
11579                    }
11580                } else {
11581                    mPrivateFlags &= ~DIRTY_MASK;
11582                    ((HardwareCanvas) canvas).drawDisplayList(displayList,
11583                            mRight - mLeft, mBottom - mTop, null, flags);
11584                }
11585            }
11586        } else if (cache != null) {
11587            mPrivateFlags &= ~DIRTY_MASK;
11588            Paint cachePaint;
11589
11590            if (layerType == LAYER_TYPE_NONE) {
11591                cachePaint = parent.mCachePaint;
11592                if (cachePaint == null) {
11593                    cachePaint = new Paint();
11594                    cachePaint.setDither(false);
11595                    parent.mCachePaint = cachePaint;
11596                }
11597                if (alpha < 1.0f) {
11598                    cachePaint.setAlpha((int) (alpha * 255));
11599                    parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
11600                } else if  ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) {
11601                    cachePaint.setAlpha(255);
11602                    parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE;
11603                }
11604            } else {
11605                cachePaint = mLayerPaint;
11606                cachePaint.setAlpha((int) (alpha * 255));
11607            }
11608            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
11609        }
11610
11611        if (restoreTo >= 0) {
11612            canvas.restoreToCount(restoreTo);
11613        }
11614
11615        if (a != null && !more) {
11616            if (!hardwareAccelerated && !a.getFillAfter()) {
11617                onSetAlpha(255);
11618            }
11619            parent.finishAnimatingView(this, a);
11620        }
11621
11622        if (more && hardwareAccelerated) {
11623            // invalidation is the trigger to recreate display lists, so if we're using
11624            // display lists to render, force an invalidate to allow the animation to
11625            // continue drawing another frame
11626            parent.invalidate(true);
11627            if (a.hasAlpha() && (mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
11628                // alpha animations should cause the child to recreate its display list
11629                invalidate(true);
11630            }
11631        }
11632
11633        mRecreateDisplayList = false;
11634
11635        return more;
11636    }
11637
11638    /**
11639     * Manually render this view (and all of its children) to the given Canvas.
11640     * The view must have already done a full layout before this function is
11641     * called.  When implementing a view, implement
11642     * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
11643     * If you do need to override this method, call the superclass version.
11644     *
11645     * @param canvas The Canvas to which the View is rendered.
11646     */
11647    public void draw(Canvas canvas) {
11648        if (ViewDebug.TRACE_HIERARCHY) {
11649            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
11650        }
11651
11652        final int privateFlags = mPrivateFlags;
11653        final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
11654                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
11655        mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
11656
11657        /*
11658         * Draw traversal performs several drawing steps which must be executed
11659         * in the appropriate order:
11660         *
11661         *      1. Draw the background
11662         *      2. If necessary, save the canvas' layers to prepare for fading
11663         *      3. Draw view's content
11664         *      4. Draw children
11665         *      5. If necessary, draw the fading edges and restore layers
11666         *      6. Draw decorations (scrollbars for instance)
11667         */
11668
11669        // Step 1, draw the background, if needed
11670        int saveCount;
11671
11672        if (!dirtyOpaque) {
11673            final Drawable background = mBGDrawable;
11674            if (background != null) {
11675                final int scrollX = mScrollX;
11676                final int scrollY = mScrollY;
11677
11678                if (mBackgroundSizeChanged) {
11679                    background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
11680                    mBackgroundSizeChanged = false;
11681                }
11682
11683                if ((scrollX | scrollY) == 0) {
11684                    background.draw(canvas);
11685                } else {
11686                    canvas.translate(scrollX, scrollY);
11687                    background.draw(canvas);
11688                    canvas.translate(-scrollX, -scrollY);
11689                }
11690            }
11691        }
11692
11693        // skip step 2 & 5 if possible (common case)
11694        final int viewFlags = mViewFlags;
11695        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
11696        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
11697        if (!verticalEdges && !horizontalEdges) {
11698            // Step 3, draw the content
11699            if (!dirtyOpaque) onDraw(canvas);
11700
11701            // Step 4, draw the children
11702            dispatchDraw(canvas);
11703
11704            // Step 6, draw decorations (scrollbars)
11705            onDrawScrollBars(canvas);
11706
11707            // we're done...
11708            return;
11709        }
11710
11711        /*
11712         * Here we do the full fledged routine...
11713         * (this is an uncommon case where speed matters less,
11714         * this is why we repeat some of the tests that have been
11715         * done above)
11716         */
11717
11718        boolean drawTop = false;
11719        boolean drawBottom = false;
11720        boolean drawLeft = false;
11721        boolean drawRight = false;
11722
11723        float topFadeStrength = 0.0f;
11724        float bottomFadeStrength = 0.0f;
11725        float leftFadeStrength = 0.0f;
11726        float rightFadeStrength = 0.0f;
11727
11728        // Step 2, save the canvas' layers
11729        int paddingLeft = mPaddingLeft;
11730
11731        final boolean offsetRequired = isPaddingOffsetRequired();
11732        if (offsetRequired) {
11733            paddingLeft += getLeftPaddingOffset();
11734        }
11735
11736        int left = mScrollX + paddingLeft;
11737        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
11738        int top = mScrollY + getFadeTop(offsetRequired);
11739        int bottom = top + getFadeHeight(offsetRequired);
11740
11741        if (offsetRequired) {
11742            right += getRightPaddingOffset();
11743            bottom += getBottomPaddingOffset();
11744        }
11745
11746        final ScrollabilityCache scrollabilityCache = mScrollCache;
11747        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
11748        int length = (int) fadeHeight;
11749
11750        // clip the fade length if top and bottom fades overlap
11751        // overlapping fades produce odd-looking artifacts
11752        if (verticalEdges && (top + length > bottom - length)) {
11753            length = (bottom - top) / 2;
11754        }
11755
11756        // also clip horizontal fades if necessary
11757        if (horizontalEdges && (left + length > right - length)) {
11758            length = (right - left) / 2;
11759        }
11760
11761        if (verticalEdges) {
11762            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
11763            drawTop = topFadeStrength * fadeHeight > 1.0f;
11764            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
11765            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
11766        }
11767
11768        if (horizontalEdges) {
11769            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
11770            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
11771            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
11772            drawRight = rightFadeStrength * fadeHeight > 1.0f;
11773        }
11774
11775        saveCount = canvas.getSaveCount();
11776
11777        int solidColor = getSolidColor();
11778        if (solidColor == 0) {
11779            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
11780
11781            if (drawTop) {
11782                canvas.saveLayer(left, top, right, top + length, null, flags);
11783            }
11784
11785            if (drawBottom) {
11786                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
11787            }
11788
11789            if (drawLeft) {
11790                canvas.saveLayer(left, top, left + length, bottom, null, flags);
11791            }
11792
11793            if (drawRight) {
11794                canvas.saveLayer(right - length, top, right, bottom, null, flags);
11795            }
11796        } else {
11797            scrollabilityCache.setFadeColor(solidColor);
11798        }
11799
11800        // Step 3, draw the content
11801        if (!dirtyOpaque) onDraw(canvas);
11802
11803        // Step 4, draw the children
11804        dispatchDraw(canvas);
11805
11806        // Step 5, draw the fade effect and restore layers
11807        final Paint p = scrollabilityCache.paint;
11808        final Matrix matrix = scrollabilityCache.matrix;
11809        final Shader fade = scrollabilityCache.shader;
11810
11811        if (drawTop) {
11812            matrix.setScale(1, fadeHeight * topFadeStrength);
11813            matrix.postTranslate(left, top);
11814            fade.setLocalMatrix(matrix);
11815            canvas.drawRect(left, top, right, top + length, p);
11816        }
11817
11818        if (drawBottom) {
11819            matrix.setScale(1, fadeHeight * bottomFadeStrength);
11820            matrix.postRotate(180);
11821            matrix.postTranslate(left, bottom);
11822            fade.setLocalMatrix(matrix);
11823            canvas.drawRect(left, bottom - length, right, bottom, p);
11824        }
11825
11826        if (drawLeft) {
11827            matrix.setScale(1, fadeHeight * leftFadeStrength);
11828            matrix.postRotate(-90);
11829            matrix.postTranslate(left, top);
11830            fade.setLocalMatrix(matrix);
11831            canvas.drawRect(left, top, left + length, bottom, p);
11832        }
11833
11834        if (drawRight) {
11835            matrix.setScale(1, fadeHeight * rightFadeStrength);
11836            matrix.postRotate(90);
11837            matrix.postTranslate(right, top);
11838            fade.setLocalMatrix(matrix);
11839            canvas.drawRect(right - length, top, right, bottom, p);
11840        }
11841
11842        canvas.restoreToCount(saveCount);
11843
11844        // Step 6, draw decorations (scrollbars)
11845        onDrawScrollBars(canvas);
11846    }
11847
11848    /**
11849     * Override this if your view is known to always be drawn on top of a solid color background,
11850     * and needs to draw fading edges. Returning a non-zero color enables the view system to
11851     * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
11852     * should be set to 0xFF.
11853     *
11854     * @see #setVerticalFadingEdgeEnabled(boolean)
11855     * @see #setHorizontalFadingEdgeEnabled(boolean)
11856     *
11857     * @return The known solid color background for this view, or 0 if the color may vary
11858     */
11859    @ViewDebug.ExportedProperty(category = "drawing")
11860    public int getSolidColor() {
11861        return 0;
11862    }
11863
11864    /**
11865     * Build a human readable string representation of the specified view flags.
11866     *
11867     * @param flags the view flags to convert to a string
11868     * @return a String representing the supplied flags
11869     */
11870    private static String printFlags(int flags) {
11871        String output = "";
11872        int numFlags = 0;
11873        if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
11874            output += "TAKES_FOCUS";
11875            numFlags++;
11876        }
11877
11878        switch (flags & VISIBILITY_MASK) {
11879        case INVISIBLE:
11880            if (numFlags > 0) {
11881                output += " ";
11882            }
11883            output += "INVISIBLE";
11884            // USELESS HERE numFlags++;
11885            break;
11886        case GONE:
11887            if (numFlags > 0) {
11888                output += " ";
11889            }
11890            output += "GONE";
11891            // USELESS HERE numFlags++;
11892            break;
11893        default:
11894            break;
11895        }
11896        return output;
11897    }
11898
11899    /**
11900     * Build a human readable string representation of the specified private
11901     * view flags.
11902     *
11903     * @param privateFlags the private view flags to convert to a string
11904     * @return a String representing the supplied flags
11905     */
11906    private static String printPrivateFlags(int privateFlags) {
11907        String output = "";
11908        int numFlags = 0;
11909
11910        if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
11911            output += "WANTS_FOCUS";
11912            numFlags++;
11913        }
11914
11915        if ((privateFlags & FOCUSED) == FOCUSED) {
11916            if (numFlags > 0) {
11917                output += " ";
11918            }
11919            output += "FOCUSED";
11920            numFlags++;
11921        }
11922
11923        if ((privateFlags & SELECTED) == SELECTED) {
11924            if (numFlags > 0) {
11925                output += " ";
11926            }
11927            output += "SELECTED";
11928            numFlags++;
11929        }
11930
11931        if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
11932            if (numFlags > 0) {
11933                output += " ";
11934            }
11935            output += "IS_ROOT_NAMESPACE";
11936            numFlags++;
11937        }
11938
11939        if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
11940            if (numFlags > 0) {
11941                output += " ";
11942            }
11943            output += "HAS_BOUNDS";
11944            numFlags++;
11945        }
11946
11947        if ((privateFlags & DRAWN) == DRAWN) {
11948            if (numFlags > 0) {
11949                output += " ";
11950            }
11951            output += "DRAWN";
11952            // USELESS HERE numFlags++;
11953        }
11954        return output;
11955    }
11956
11957    /**
11958     * <p>Indicates whether or not this view's layout will be requested during
11959     * the next hierarchy layout pass.</p>
11960     *
11961     * @return true if the layout will be forced during next layout pass
11962     */
11963    public boolean isLayoutRequested() {
11964        return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
11965    }
11966
11967    /**
11968     * Assign a size and position to a view and all of its
11969     * descendants
11970     *
11971     * <p>This is the second phase of the layout mechanism.
11972     * (The first is measuring). In this phase, each parent calls
11973     * layout on all of its children to position them.
11974     * This is typically done using the child measurements
11975     * that were stored in the measure pass().</p>
11976     *
11977     * <p>Derived classes should not override this method.
11978     * Derived classes with children should override
11979     * onLayout. In that method, they should
11980     * call layout on each of their children.</p>
11981     *
11982     * @param l Left position, relative to parent
11983     * @param t Top position, relative to parent
11984     * @param r Right position, relative to parent
11985     * @param b Bottom position, relative to parent
11986     */
11987    @SuppressWarnings({"unchecked"})
11988    public void layout(int l, int t, int r, int b) {
11989        int oldL = mLeft;
11990        int oldT = mTop;
11991        int oldB = mBottom;
11992        int oldR = mRight;
11993        boolean changed = setFrame(l, t, r, b);
11994        if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
11995            if (ViewDebug.TRACE_HIERARCHY) {
11996                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
11997            }
11998
11999            onLayout(changed, l, t, r, b);
12000            mPrivateFlags &= ~LAYOUT_REQUIRED;
12001
12002            ListenerInfo li = mListenerInfo;
12003            if (li != null && li.mOnLayoutChangeListeners != null) {
12004                ArrayList<OnLayoutChangeListener> listenersCopy =
12005                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
12006                int numListeners = listenersCopy.size();
12007                for (int i = 0; i < numListeners; ++i) {
12008                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
12009                }
12010            }
12011        }
12012        mPrivateFlags &= ~FORCE_LAYOUT;
12013    }
12014
12015    /**
12016     * Called from layout when this view should
12017     * assign a size and position to each of its children.
12018     *
12019     * Derived classes with children should override
12020     * this method and call layout on each of
12021     * their children.
12022     * @param changed This is a new size or position for this view
12023     * @param left Left position, relative to parent
12024     * @param top Top position, relative to parent
12025     * @param right Right position, relative to parent
12026     * @param bottom Bottom position, relative to parent
12027     */
12028    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
12029    }
12030
12031    /**
12032     * Assign a size and position to this view.
12033     *
12034     * This is called from layout.
12035     *
12036     * @param left Left position, relative to parent
12037     * @param top Top position, relative to parent
12038     * @param right Right position, relative to parent
12039     * @param bottom Bottom position, relative to parent
12040     * @return true if the new size and position are different than the
12041     *         previous ones
12042     * {@hide}
12043     */
12044    protected boolean setFrame(int left, int top, int right, int bottom) {
12045        boolean changed = false;
12046
12047        if (DBG) {
12048            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
12049                    + right + "," + bottom + ")");
12050        }
12051
12052        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
12053            changed = true;
12054
12055            // Remember our drawn bit
12056            int drawn = mPrivateFlags & DRAWN;
12057
12058            int oldWidth = mRight - mLeft;
12059            int oldHeight = mBottom - mTop;
12060            int newWidth = right - left;
12061            int newHeight = bottom - top;
12062            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
12063
12064            // Invalidate our old position
12065            invalidate(sizeChanged);
12066
12067            mLeft = left;
12068            mTop = top;
12069            mRight = right;
12070            mBottom = bottom;
12071            if (USE_DISPLAY_LIST_PROPERTIES && mDisplayList != null) {
12072                mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
12073            }
12074
12075            mPrivateFlags |= HAS_BOUNDS;
12076
12077
12078            if (sizeChanged) {
12079                if ((mPrivateFlags & PIVOT_EXPLICITLY_SET) == 0) {
12080                    // A change in dimension means an auto-centered pivot point changes, too
12081                    if (mTransformationInfo != null) {
12082                        mTransformationInfo.mMatrixDirty = true;
12083                    }
12084                }
12085                onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
12086            }
12087
12088            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
12089                // If we are visible, force the DRAWN bit to on so that
12090                // this invalidate will go through (at least to our parent).
12091                // This is because someone may have invalidated this view
12092                // before this call to setFrame came in, thereby clearing
12093                // the DRAWN bit.
12094                mPrivateFlags |= DRAWN;
12095                invalidate(sizeChanged);
12096                // parent display list may need to be recreated based on a change in the bounds
12097                // of any child
12098                invalidateParentCaches();
12099            }
12100
12101            // Reset drawn bit to original value (invalidate turns it off)
12102            mPrivateFlags |= drawn;
12103
12104            mBackgroundSizeChanged = true;
12105        }
12106        return changed;
12107    }
12108
12109    /**
12110     * Finalize inflating a view from XML.  This is called as the last phase
12111     * of inflation, after all child views have been added.
12112     *
12113     * <p>Even if the subclass overrides onFinishInflate, they should always be
12114     * sure to call the super method, so that we get called.
12115     */
12116    protected void onFinishInflate() {
12117    }
12118
12119    /**
12120     * Returns the resources associated with this view.
12121     *
12122     * @return Resources object.
12123     */
12124    public Resources getResources() {
12125        return mResources;
12126    }
12127
12128    /**
12129     * Invalidates the specified Drawable.
12130     *
12131     * @param drawable the drawable to invalidate
12132     */
12133    public void invalidateDrawable(Drawable drawable) {
12134        if (verifyDrawable(drawable)) {
12135            final Rect dirty = drawable.getBounds();
12136            final int scrollX = mScrollX;
12137            final int scrollY = mScrollY;
12138
12139            invalidate(dirty.left + scrollX, dirty.top + scrollY,
12140                    dirty.right + scrollX, dirty.bottom + scrollY);
12141        }
12142    }
12143
12144    /**
12145     * Schedules an action on a drawable to occur at a specified time.
12146     *
12147     * @param who the recipient of the action
12148     * @param what the action to run on the drawable
12149     * @param when the time at which the action must occur. Uses the
12150     *        {@link SystemClock#uptimeMillis} timebase.
12151     */
12152    public void scheduleDrawable(Drawable who, Runnable what, long when) {
12153        if (verifyDrawable(who) && what != null) {
12154            final long delay = when - SystemClock.uptimeMillis();
12155            if (mAttachInfo != null) {
12156                mAttachInfo.mViewRootImpl.mChoreographer.postAnimationCallbackDelayed(
12157                        what, who, Choreographer.subtractFrameDelay(delay));
12158            } else {
12159                ViewRootImpl.getRunQueue().postDelayed(what, delay);
12160            }
12161        }
12162    }
12163
12164    /**
12165     * Cancels a scheduled action on a drawable.
12166     *
12167     * @param who the recipient of the action
12168     * @param what the action to cancel
12169     */
12170    public void unscheduleDrawable(Drawable who, Runnable what) {
12171        if (verifyDrawable(who) && what != null) {
12172            if (mAttachInfo != null) {
12173                mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(what, who);
12174            } else {
12175                ViewRootImpl.getRunQueue().removeCallbacks(what);
12176            }
12177        }
12178    }
12179
12180    /**
12181     * Unschedule any events associated with the given Drawable.  This can be
12182     * used when selecting a new Drawable into a view, so that the previous
12183     * one is completely unscheduled.
12184     *
12185     * @param who The Drawable to unschedule.
12186     *
12187     * @see #drawableStateChanged
12188     */
12189    public void unscheduleDrawable(Drawable who) {
12190        if (mAttachInfo != null && who != null) {
12191            mAttachInfo.mViewRootImpl.mChoreographer.removeAnimationCallbacks(null, who);
12192        }
12193    }
12194
12195    /**
12196    * Return the layout direction of a given Drawable.
12197    *
12198    * @param who the Drawable to query
12199    */
12200    public int getResolvedLayoutDirection(Drawable who) {
12201        return (who == mBGDrawable) ? getResolvedLayoutDirection() : LAYOUT_DIRECTION_DEFAULT;
12202    }
12203
12204    /**
12205     * If your view subclass is displaying its own Drawable objects, it should
12206     * override this function and return true for any Drawable it is
12207     * displaying.  This allows animations for those drawables to be
12208     * scheduled.
12209     *
12210     * <p>Be sure to call through to the super class when overriding this
12211     * function.
12212     *
12213     * @param who The Drawable to verify.  Return true if it is one you are
12214     *            displaying, else return the result of calling through to the
12215     *            super class.
12216     *
12217     * @return boolean If true than the Drawable is being displayed in the
12218     *         view; else false and it is not allowed to animate.
12219     *
12220     * @see #unscheduleDrawable(android.graphics.drawable.Drawable)
12221     * @see #drawableStateChanged()
12222     */
12223    protected boolean verifyDrawable(Drawable who) {
12224        return who == mBGDrawable;
12225    }
12226
12227    /**
12228     * This function is called whenever the state of the view changes in such
12229     * a way that it impacts the state of drawables being shown.
12230     *
12231     * <p>Be sure to call through to the superclass when overriding this
12232     * function.
12233     *
12234     * @see Drawable#setState(int[])
12235     */
12236    protected void drawableStateChanged() {
12237        Drawable d = mBGDrawable;
12238        if (d != null && d.isStateful()) {
12239            d.setState(getDrawableState());
12240        }
12241    }
12242
12243    /**
12244     * Call this to force a view to update its drawable state. This will cause
12245     * drawableStateChanged to be called on this view. Views that are interested
12246     * in the new state should call getDrawableState.
12247     *
12248     * @see #drawableStateChanged
12249     * @see #getDrawableState
12250     */
12251    public void refreshDrawableState() {
12252        mPrivateFlags |= DRAWABLE_STATE_DIRTY;
12253        drawableStateChanged();
12254
12255        ViewParent parent = mParent;
12256        if (parent != null) {
12257            parent.childDrawableStateChanged(this);
12258        }
12259    }
12260
12261    /**
12262     * Return an array of resource IDs of the drawable states representing the
12263     * current state of the view.
12264     *
12265     * @return The current drawable state
12266     *
12267     * @see Drawable#setState(int[])
12268     * @see #drawableStateChanged()
12269     * @see #onCreateDrawableState(int)
12270     */
12271    public final int[] getDrawableState() {
12272        if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
12273            return mDrawableState;
12274        } else {
12275            mDrawableState = onCreateDrawableState(0);
12276            mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
12277            return mDrawableState;
12278        }
12279    }
12280
12281    /**
12282     * Generate the new {@link android.graphics.drawable.Drawable} state for
12283     * this view. This is called by the view
12284     * system when the cached Drawable state is determined to be invalid.  To
12285     * retrieve the current state, you should use {@link #getDrawableState}.
12286     *
12287     * @param extraSpace if non-zero, this is the number of extra entries you
12288     * would like in the returned array in which you can place your own
12289     * states.
12290     *
12291     * @return Returns an array holding the current {@link Drawable} state of
12292     * the view.
12293     *
12294     * @see #mergeDrawableStates(int[], int[])
12295     */
12296    protected int[] onCreateDrawableState(int extraSpace) {
12297        if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
12298                mParent instanceof View) {
12299            return ((View) mParent).onCreateDrawableState(extraSpace);
12300        }
12301
12302        int[] drawableState;
12303
12304        int privateFlags = mPrivateFlags;
12305
12306        int viewStateIndex = 0;
12307        if ((privateFlags & PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED;
12308        if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED;
12309        if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED;
12310        if ((privateFlags & SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED;
12311        if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED;
12312        if ((privateFlags & ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED;
12313        if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested &&
12314                HardwareRenderer.isAvailable()) {
12315            // This is set if HW acceleration is requested, even if the current
12316            // process doesn't allow it.  This is just to allow app preview
12317            // windows to better match their app.
12318            viewStateIndex |= VIEW_STATE_ACCELERATED;
12319        }
12320        if ((privateFlags & HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED;
12321
12322        final int privateFlags2 = mPrivateFlags2;
12323        if ((privateFlags2 & DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT;
12324        if ((privateFlags2 & DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED;
12325
12326        drawableState = VIEW_STATE_SETS[viewStateIndex];
12327
12328        //noinspection ConstantIfStatement
12329        if (false) {
12330            Log.i("View", "drawableStateIndex=" + viewStateIndex);
12331            Log.i("View", toString()
12332                    + " pressed=" + ((privateFlags & PRESSED) != 0)
12333                    + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
12334                    + " fo=" + hasFocus()
12335                    + " sl=" + ((privateFlags & SELECTED) != 0)
12336                    + " wf=" + hasWindowFocus()
12337                    + ": " + Arrays.toString(drawableState));
12338        }
12339
12340        if (extraSpace == 0) {
12341            return drawableState;
12342        }
12343
12344        final int[] fullState;
12345        if (drawableState != null) {
12346            fullState = new int[drawableState.length + extraSpace];
12347            System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
12348        } else {
12349            fullState = new int[extraSpace];
12350        }
12351
12352        return fullState;
12353    }
12354
12355    /**
12356     * Merge your own state values in <var>additionalState</var> into the base
12357     * state values <var>baseState</var> that were returned by
12358     * {@link #onCreateDrawableState(int)}.
12359     *
12360     * @param baseState The base state values returned by
12361     * {@link #onCreateDrawableState(int)}, which will be modified to also hold your
12362     * own additional state values.
12363     *
12364     * @param additionalState The additional state values you would like
12365     * added to <var>baseState</var>; this array is not modified.
12366     *
12367     * @return As a convenience, the <var>baseState</var> array you originally
12368     * passed into the function is returned.
12369     *
12370     * @see #onCreateDrawableState(int)
12371     */
12372    protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
12373        final int N = baseState.length;
12374        int i = N - 1;
12375        while (i >= 0 && baseState[i] == 0) {
12376            i--;
12377        }
12378        System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
12379        return baseState;
12380    }
12381
12382    /**
12383     * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()}
12384     * on all Drawable objects associated with this view.
12385     */
12386    public void jumpDrawablesToCurrentState() {
12387        if (mBGDrawable != null) {
12388            mBGDrawable.jumpToCurrentState();
12389        }
12390    }
12391
12392    /**
12393     * Sets the background color for this view.
12394     * @param color the color of the background
12395     */
12396    @RemotableViewMethod
12397    public void setBackgroundColor(int color) {
12398        if (mBGDrawable instanceof ColorDrawable) {
12399            ((ColorDrawable) mBGDrawable).setColor(color);
12400        } else {
12401            setBackgroundDrawable(new ColorDrawable(color));
12402        }
12403    }
12404
12405    /**
12406     * Set the background to a given resource. The resource should refer to
12407     * a Drawable object or 0 to remove the background.
12408     * @param resid The identifier of the resource.
12409     * @attr ref android.R.styleable#View_background
12410     */
12411    @RemotableViewMethod
12412    public void setBackgroundResource(int resid) {
12413        if (resid != 0 && resid == mBackgroundResource) {
12414            return;
12415        }
12416
12417        Drawable d= null;
12418        if (resid != 0) {
12419            d = mResources.getDrawable(resid);
12420        }
12421        setBackgroundDrawable(d);
12422
12423        mBackgroundResource = resid;
12424    }
12425
12426    /**
12427     * Set the background to a given Drawable, or remove the background. If the
12428     * background has padding, this View's padding is set to the background's
12429     * padding. However, when a background is removed, this View's padding isn't
12430     * touched. If setting the padding is desired, please use
12431     * {@link #setPadding(int, int, int, int)}.
12432     *
12433     * @param d The Drawable to use as the background, or null to remove the
12434     *        background
12435     */
12436    public void setBackgroundDrawable(Drawable d) {
12437        if (d == mBGDrawable) {
12438            return;
12439        }
12440
12441        boolean requestLayout = false;
12442
12443        mBackgroundResource = 0;
12444
12445        /*
12446         * Regardless of whether we're setting a new background or not, we want
12447         * to clear the previous drawable.
12448         */
12449        if (mBGDrawable != null) {
12450            mBGDrawable.setCallback(null);
12451            unscheduleDrawable(mBGDrawable);
12452        }
12453
12454        if (d != null) {
12455            Rect padding = sThreadLocal.get();
12456            if (padding == null) {
12457                padding = new Rect();
12458                sThreadLocal.set(padding);
12459            }
12460            if (d.getPadding(padding)) {
12461                switch (d.getResolvedLayoutDirectionSelf()) {
12462                    case LAYOUT_DIRECTION_RTL:
12463                        setPadding(padding.right, padding.top, padding.left, padding.bottom);
12464                        break;
12465                    case LAYOUT_DIRECTION_LTR:
12466                    default:
12467                        setPadding(padding.left, padding.top, padding.right, padding.bottom);
12468                }
12469            }
12470
12471            // Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or
12472            // if it has a different minimum size, we should layout again
12473            if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
12474                    mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
12475                requestLayout = true;
12476            }
12477
12478            d.setCallback(this);
12479            if (d.isStateful()) {
12480                d.setState(getDrawableState());
12481            }
12482            d.setVisible(getVisibility() == VISIBLE, false);
12483            mBGDrawable = d;
12484
12485            if ((mPrivateFlags & SKIP_DRAW) != 0) {
12486                mPrivateFlags &= ~SKIP_DRAW;
12487                mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
12488                requestLayout = true;
12489            }
12490        } else {
12491            /* Remove the background */
12492            mBGDrawable = null;
12493
12494            if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
12495                /*
12496                 * This view ONLY drew the background before and we're removing
12497                 * the background, so now it won't draw anything
12498                 * (hence we SKIP_DRAW)
12499                 */
12500                mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
12501                mPrivateFlags |= SKIP_DRAW;
12502            }
12503
12504            /*
12505             * When the background is set, we try to apply its padding to this
12506             * View. When the background is removed, we don't touch this View's
12507             * padding. This is noted in the Javadocs. Hence, we don't need to
12508             * requestLayout(), the invalidate() below is sufficient.
12509             */
12510
12511            // The old background's minimum size could have affected this
12512            // View's layout, so let's requestLayout
12513            requestLayout = true;
12514        }
12515
12516        computeOpaqueFlags();
12517
12518        if (requestLayout) {
12519            requestLayout();
12520        }
12521
12522        mBackgroundSizeChanged = true;
12523        invalidate(true);
12524    }
12525
12526    /**
12527     * Gets the background drawable
12528     * @return The drawable used as the background for this view, if any.
12529     */
12530    public Drawable getBackground() {
12531        return mBGDrawable;
12532    }
12533
12534    /**
12535     * Sets the padding. The view may add on the space required to display
12536     * the scrollbars, depending on the style and visibility of the scrollbars.
12537     * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
12538     * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
12539     * from the values set in this call.
12540     *
12541     * @attr ref android.R.styleable#View_padding
12542     * @attr ref android.R.styleable#View_paddingBottom
12543     * @attr ref android.R.styleable#View_paddingLeft
12544     * @attr ref android.R.styleable#View_paddingRight
12545     * @attr ref android.R.styleable#View_paddingTop
12546     * @param left the left padding in pixels
12547     * @param top the top padding in pixels
12548     * @param right the right padding in pixels
12549     * @param bottom the bottom padding in pixels
12550     */
12551    public void setPadding(int left, int top, int right, int bottom) {
12552        mUserPaddingStart = -1;
12553        mUserPaddingEnd = -1;
12554        mUserPaddingRelative = false;
12555
12556        internalSetPadding(left, top, right, bottom);
12557    }
12558
12559    private void internalSetPadding(int left, int top, int right, int bottom) {
12560        mUserPaddingLeft = left;
12561        mUserPaddingRight = right;
12562        mUserPaddingBottom = bottom;
12563
12564        final int viewFlags = mViewFlags;
12565        boolean changed = false;
12566
12567        // Common case is there are no scroll bars.
12568        if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
12569            if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
12570                final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0
12571                        ? 0 : getVerticalScrollbarWidth();
12572                switch (mVerticalScrollbarPosition) {
12573                    case SCROLLBAR_POSITION_DEFAULT:
12574                        if (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
12575                            left += offset;
12576                        } else {
12577                            right += offset;
12578                        }
12579                        break;
12580                    case SCROLLBAR_POSITION_RIGHT:
12581                        right += offset;
12582                        break;
12583                    case SCROLLBAR_POSITION_LEFT:
12584                        left += offset;
12585                        break;
12586                }
12587            }
12588            if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) {
12589                bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
12590                        ? 0 : getHorizontalScrollbarHeight();
12591            }
12592        }
12593
12594        if (mPaddingLeft != left) {
12595            changed = true;
12596            mPaddingLeft = left;
12597        }
12598        if (mPaddingTop != top) {
12599            changed = true;
12600            mPaddingTop = top;
12601        }
12602        if (mPaddingRight != right) {
12603            changed = true;
12604            mPaddingRight = right;
12605        }
12606        if (mPaddingBottom != bottom) {
12607            changed = true;
12608            mPaddingBottom = bottom;
12609        }
12610
12611        if (changed) {
12612            requestLayout();
12613        }
12614    }
12615
12616    /**
12617     * Sets the relative padding. The view may add on the space required to display
12618     * the scrollbars, depending on the style and visibility of the scrollbars.
12619     * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop},
12620     * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different
12621     * from the values set in this call.
12622     *
12623     * @attr ref android.R.styleable#View_padding
12624     * @attr ref android.R.styleable#View_paddingBottom
12625     * @attr ref android.R.styleable#View_paddingStart
12626     * @attr ref android.R.styleable#View_paddingEnd
12627     * @attr ref android.R.styleable#View_paddingTop
12628     * @param start the start padding in pixels
12629     * @param top the top padding in pixels
12630     * @param end the end padding in pixels
12631     * @param bottom the bottom padding in pixels
12632     */
12633    public void setPaddingRelative(int start, int top, int end, int bottom) {
12634        mUserPaddingStart = start;
12635        mUserPaddingEnd = end;
12636        mUserPaddingRelative = true;
12637
12638        switch(getResolvedLayoutDirection()) {
12639            case LAYOUT_DIRECTION_RTL:
12640                internalSetPadding(end, top, start, bottom);
12641                break;
12642            case LAYOUT_DIRECTION_LTR:
12643            default:
12644                internalSetPadding(start, top, end, bottom);
12645        }
12646    }
12647
12648    /**
12649     * Returns the top padding of this view.
12650     *
12651     * @return the top padding in pixels
12652     */
12653    public int getPaddingTop() {
12654        return mPaddingTop;
12655    }
12656
12657    /**
12658     * Returns the bottom padding of this view. If there are inset and enabled
12659     * scrollbars, this value may include the space required to display the
12660     * scrollbars as well.
12661     *
12662     * @return the bottom padding in pixels
12663     */
12664    public int getPaddingBottom() {
12665        return mPaddingBottom;
12666    }
12667
12668    /**
12669     * Returns the left padding of this view. If there are inset and enabled
12670     * scrollbars, this value may include the space required to display the
12671     * scrollbars as well.
12672     *
12673     * @return the left padding in pixels
12674     */
12675    public int getPaddingLeft() {
12676        return mPaddingLeft;
12677    }
12678
12679    /**
12680     * Returns the start padding of this view depending on its resolved layout direction.
12681     * If there are inset and enabled scrollbars, this value may include the space
12682     * required to display the scrollbars as well.
12683     *
12684     * @return the start padding in pixels
12685     */
12686    public int getPaddingStart() {
12687        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12688                mPaddingRight : mPaddingLeft;
12689    }
12690
12691    /**
12692     * Returns the right padding of this view. If there are inset and enabled
12693     * scrollbars, this value may include the space required to display the
12694     * scrollbars as well.
12695     *
12696     * @return the right padding in pixels
12697     */
12698    public int getPaddingRight() {
12699        return mPaddingRight;
12700    }
12701
12702    /**
12703     * Returns the end padding of this view depending on its resolved layout direction.
12704     * If there are inset and enabled scrollbars, this value may include the space
12705     * required to display the scrollbars as well.
12706     *
12707     * @return the end padding in pixels
12708     */
12709    public int getPaddingEnd() {
12710        return (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ?
12711                mPaddingLeft : mPaddingRight;
12712    }
12713
12714    /**
12715     * Return if the padding as been set thru relative values
12716     * {@link #setPaddingRelative(int, int, int, int)} or thru
12717     * @attr ref android.R.styleable#View_paddingStart or
12718     * @attr ref android.R.styleable#View_paddingEnd
12719     *
12720     * @return true if the padding is relative or false if it is not.
12721     */
12722    public boolean isPaddingRelative() {
12723        return mUserPaddingRelative;
12724    }
12725
12726    /**
12727     * Changes the selection state of this view. A view can be selected or not.
12728     * Note that selection is not the same as focus. Views are typically
12729     * selected in the context of an AdapterView like ListView or GridView;
12730     * the selected view is the view that is highlighted.
12731     *
12732     * @param selected true if the view must be selected, false otherwise
12733     */
12734    public void setSelected(boolean selected) {
12735        if (((mPrivateFlags & SELECTED) != 0) != selected) {
12736            mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
12737            if (!selected) resetPressedState();
12738            invalidate(true);
12739            refreshDrawableState();
12740            dispatchSetSelected(selected);
12741        }
12742    }
12743
12744    /**
12745     * Dispatch setSelected to all of this View's children.
12746     *
12747     * @see #setSelected(boolean)
12748     *
12749     * @param selected The new selected state
12750     */
12751    protected void dispatchSetSelected(boolean selected) {
12752    }
12753
12754    /**
12755     * Indicates the selection state of this view.
12756     *
12757     * @return true if the view is selected, false otherwise
12758     */
12759    @ViewDebug.ExportedProperty
12760    public boolean isSelected() {
12761        return (mPrivateFlags & SELECTED) != 0;
12762    }
12763
12764    /**
12765     * Changes the activated state of this view. A view can be activated or not.
12766     * Note that activation is not the same as selection.  Selection is
12767     * a transient property, representing the view (hierarchy) the user is
12768     * currently interacting with.  Activation is a longer-term state that the
12769     * user can move views in and out of.  For example, in a list view with
12770     * single or multiple selection enabled, the views in the current selection
12771     * set are activated.  (Um, yeah, we are deeply sorry about the terminology
12772     * here.)  The activated state is propagated down to children of the view it
12773     * is set on.
12774     *
12775     * @param activated true if the view must be activated, false otherwise
12776     */
12777    public void setActivated(boolean activated) {
12778        if (((mPrivateFlags & ACTIVATED) != 0) != activated) {
12779            mPrivateFlags = (mPrivateFlags & ~ACTIVATED) | (activated ? ACTIVATED : 0);
12780            invalidate(true);
12781            refreshDrawableState();
12782            dispatchSetActivated(activated);
12783        }
12784    }
12785
12786    /**
12787     * Dispatch setActivated to all of this View's children.
12788     *
12789     * @see #setActivated(boolean)
12790     *
12791     * @param activated The new activated state
12792     */
12793    protected void dispatchSetActivated(boolean activated) {
12794    }
12795
12796    /**
12797     * Indicates the activation state of this view.
12798     *
12799     * @return true if the view is activated, false otherwise
12800     */
12801    @ViewDebug.ExportedProperty
12802    public boolean isActivated() {
12803        return (mPrivateFlags & ACTIVATED) != 0;
12804    }
12805
12806    /**
12807     * Returns the ViewTreeObserver for this view's hierarchy. The view tree
12808     * observer can be used to get notifications when global events, like
12809     * layout, happen.
12810     *
12811     * The returned ViewTreeObserver observer is not guaranteed to remain
12812     * valid for the lifetime of this View. If the caller of this method keeps
12813     * a long-lived reference to ViewTreeObserver, it should always check for
12814     * the return value of {@link ViewTreeObserver#isAlive()}.
12815     *
12816     * @return The ViewTreeObserver for this view's hierarchy.
12817     */
12818    public ViewTreeObserver getViewTreeObserver() {
12819        if (mAttachInfo != null) {
12820            return mAttachInfo.mTreeObserver;
12821        }
12822        if (mFloatingTreeObserver == null) {
12823            mFloatingTreeObserver = new ViewTreeObserver();
12824        }
12825        return mFloatingTreeObserver;
12826    }
12827
12828    /**
12829     * <p>Finds the topmost view in the current view hierarchy.</p>
12830     *
12831     * @return the topmost view containing this view
12832     */
12833    public View getRootView() {
12834        if (mAttachInfo != null) {
12835            final View v = mAttachInfo.mRootView;
12836            if (v != null) {
12837                return v;
12838            }
12839        }
12840
12841        View parent = this;
12842
12843        while (parent.mParent != null && parent.mParent instanceof View) {
12844            parent = (View) parent.mParent;
12845        }
12846
12847        return parent;
12848    }
12849
12850    /**
12851     * <p>Computes the coordinates of this view on the screen. The argument
12852     * must be an array of two integers. After the method returns, the array
12853     * contains the x and y location in that order.</p>
12854     *
12855     * @param location an array of two integers in which to hold the coordinates
12856     */
12857    public void getLocationOnScreen(int[] location) {
12858        getLocationInWindow(location);
12859
12860        final AttachInfo info = mAttachInfo;
12861        if (info != null) {
12862            location[0] += info.mWindowLeft;
12863            location[1] += info.mWindowTop;
12864        }
12865    }
12866
12867    /**
12868     * <p>Computes the coordinates of this view in its window. The argument
12869     * must be an array of two integers. After the method returns, the array
12870     * contains the x and y location in that order.</p>
12871     *
12872     * @param location an array of two integers in which to hold the coordinates
12873     */
12874    public void getLocationInWindow(int[] location) {
12875        if (location == null || location.length < 2) {
12876            throw new IllegalArgumentException("location must be an array of two integers");
12877        }
12878
12879        if (mAttachInfo == null) {
12880            // When the view is not attached to a window, this method does not make sense
12881            location[0] = location[1] = 0;
12882            return;
12883        }
12884
12885        float[] position = mAttachInfo.mTmpTransformLocation;
12886        position[0] = position[1] = 0.0f;
12887
12888        if (!hasIdentityMatrix()) {
12889            getMatrix().mapPoints(position);
12890        }
12891
12892        position[0] += mLeft;
12893        position[1] += mTop;
12894
12895        ViewParent viewParent = mParent;
12896        while (viewParent instanceof View) {
12897            final View view = (View) viewParent;
12898
12899            position[0] -= view.mScrollX;
12900            position[1] -= view.mScrollY;
12901
12902            if (!view.hasIdentityMatrix()) {
12903                view.getMatrix().mapPoints(position);
12904            }
12905
12906            position[0] += view.mLeft;
12907            position[1] += view.mTop;
12908
12909            viewParent = view.mParent;
12910        }
12911
12912        if (viewParent instanceof ViewRootImpl) {
12913            // *cough*
12914            final ViewRootImpl vr = (ViewRootImpl) viewParent;
12915            position[1] -= vr.mCurScrollY;
12916        }
12917
12918        location[0] = (int) (position[0] + 0.5f);
12919        location[1] = (int) (position[1] + 0.5f);
12920    }
12921
12922    /**
12923     * {@hide}
12924     * @param id the id of the view to be found
12925     * @return the view of the specified id, null if cannot be found
12926     */
12927    protected View findViewTraversal(int id) {
12928        if (id == mID) {
12929            return this;
12930        }
12931        return null;
12932    }
12933
12934    /**
12935     * {@hide}
12936     * @param tag the tag of the view to be found
12937     * @return the view of specified tag, null if cannot be found
12938     */
12939    protected View findViewWithTagTraversal(Object tag) {
12940        if (tag != null && tag.equals(mTag)) {
12941            return this;
12942        }
12943        return null;
12944    }
12945
12946    /**
12947     * {@hide}
12948     * @param predicate The predicate to evaluate.
12949     * @param childToSkip If not null, ignores this child during the recursive traversal.
12950     * @return The first view that matches the predicate or null.
12951     */
12952    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
12953        if (predicate.apply(this)) {
12954            return this;
12955        }
12956        return null;
12957    }
12958
12959    /**
12960     * Look for a child view with the given id.  If this view has the given
12961     * id, return this view.
12962     *
12963     * @param id The id to search for.
12964     * @return The view that has the given id in the hierarchy or null
12965     */
12966    public final View findViewById(int id) {
12967        if (id < 0) {
12968            return null;
12969        }
12970        return findViewTraversal(id);
12971    }
12972
12973    /**
12974     * Finds a view by its unuque and stable accessibility id.
12975     *
12976     * @param accessibilityId The searched accessibility id.
12977     * @return The found view.
12978     */
12979    final View findViewByAccessibilityId(int accessibilityId) {
12980        if (accessibilityId < 0) {
12981            return null;
12982        }
12983        return findViewByAccessibilityIdTraversal(accessibilityId);
12984    }
12985
12986    /**
12987     * Performs the traversal to find a view by its unuque and stable accessibility id.
12988     *
12989     * <strong>Note:</strong>This method does not stop at the root namespace
12990     * boundary since the user can touch the screen at an arbitrary location
12991     * potentially crossing the root namespace bounday which will send an
12992     * accessibility event to accessibility services and they should be able
12993     * to obtain the event source. Also accessibility ids are guaranteed to be
12994     * unique in the window.
12995     *
12996     * @param accessibilityId The accessibility id.
12997     * @return The found view.
12998     */
12999    View findViewByAccessibilityIdTraversal(int accessibilityId) {
13000        if (getAccessibilityViewId() == accessibilityId) {
13001            return this;
13002        }
13003        return null;
13004    }
13005
13006    /**
13007     * Look for a child view with the given tag.  If this view has the given
13008     * tag, return this view.
13009     *
13010     * @param tag The tag to search for, using "tag.equals(getTag())".
13011     * @return The View that has the given tag in the hierarchy or null
13012     */
13013    public final View findViewWithTag(Object tag) {
13014        if (tag == null) {
13015            return null;
13016        }
13017        return findViewWithTagTraversal(tag);
13018    }
13019
13020    /**
13021     * {@hide}
13022     * Look for a child view that matches the specified predicate.
13023     * If this view matches the predicate, return this view.
13024     *
13025     * @param predicate The predicate to evaluate.
13026     * @return The first view that matches the predicate or null.
13027     */
13028    public final View findViewByPredicate(Predicate<View> predicate) {
13029        return findViewByPredicateTraversal(predicate, null);
13030    }
13031
13032    /**
13033     * {@hide}
13034     * Look for a child view that matches the specified predicate,
13035     * starting with the specified view and its descendents and then
13036     * recusively searching the ancestors and siblings of that view
13037     * until this view is reached.
13038     *
13039     * This method is useful in cases where the predicate does not match
13040     * a single unique view (perhaps multiple views use the same id)
13041     * and we are trying to find the view that is "closest" in scope to the
13042     * starting view.
13043     *
13044     * @param start The view to start from.
13045     * @param predicate The predicate to evaluate.
13046     * @return The first view that matches the predicate or null.
13047     */
13048    public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) {
13049        View childToSkip = null;
13050        for (;;) {
13051            View view = start.findViewByPredicateTraversal(predicate, childToSkip);
13052            if (view != null || start == this) {
13053                return view;
13054            }
13055
13056            ViewParent parent = start.getParent();
13057            if (parent == null || !(parent instanceof View)) {
13058                return null;
13059            }
13060
13061            childToSkip = start;
13062            start = (View) parent;
13063        }
13064    }
13065
13066    /**
13067     * Sets the identifier for this view. The identifier does not have to be
13068     * unique in this view's hierarchy. The identifier should be a positive
13069     * number.
13070     *
13071     * @see #NO_ID
13072     * @see #getId()
13073     * @see #findViewById(int)
13074     *
13075     * @param id a number used to identify the view
13076     *
13077     * @attr ref android.R.styleable#View_id
13078     */
13079    public void setId(int id) {
13080        mID = id;
13081    }
13082
13083    /**
13084     * {@hide}
13085     *
13086     * @param isRoot true if the view belongs to the root namespace, false
13087     *        otherwise
13088     */
13089    public void setIsRootNamespace(boolean isRoot) {
13090        if (isRoot) {
13091            mPrivateFlags |= IS_ROOT_NAMESPACE;
13092        } else {
13093            mPrivateFlags &= ~IS_ROOT_NAMESPACE;
13094        }
13095    }
13096
13097    /**
13098     * {@hide}
13099     *
13100     * @return true if the view belongs to the root namespace, false otherwise
13101     */
13102    public boolean isRootNamespace() {
13103        return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
13104    }
13105
13106    /**
13107     * Returns this view's identifier.
13108     *
13109     * @return a positive integer used to identify the view or {@link #NO_ID}
13110     *         if the view has no ID
13111     *
13112     * @see #setId(int)
13113     * @see #findViewById(int)
13114     * @attr ref android.R.styleable#View_id
13115     */
13116    @ViewDebug.CapturedViewProperty
13117    public int getId() {
13118        return mID;
13119    }
13120
13121    /**
13122     * Returns this view's tag.
13123     *
13124     * @return the Object stored in this view as a tag
13125     *
13126     * @see #setTag(Object)
13127     * @see #getTag(int)
13128     */
13129    @ViewDebug.ExportedProperty
13130    public Object getTag() {
13131        return mTag;
13132    }
13133
13134    /**
13135     * Sets the tag associated with this view. A tag can be used to mark
13136     * a view in its hierarchy and does not have to be unique within the
13137     * hierarchy. Tags can also be used to store data within a view without
13138     * resorting to another data structure.
13139     *
13140     * @param tag an Object to tag the view with
13141     *
13142     * @see #getTag()
13143     * @see #setTag(int, Object)
13144     */
13145    public void setTag(final Object tag) {
13146        mTag = tag;
13147    }
13148
13149    /**
13150     * Returns the tag associated with this view and the specified key.
13151     *
13152     * @param key The key identifying the tag
13153     *
13154     * @return the Object stored in this view as a tag
13155     *
13156     * @see #setTag(int, Object)
13157     * @see #getTag()
13158     */
13159    public Object getTag(int key) {
13160        if (mKeyedTags != null) return mKeyedTags.get(key);
13161        return null;
13162    }
13163
13164    /**
13165     * Sets a tag associated with this view and a key. A tag can be used
13166     * to mark a view in its hierarchy and does not have to be unique within
13167     * the hierarchy. Tags can also be used to store data within a view
13168     * without resorting to another data structure.
13169     *
13170     * The specified key should be an id declared in the resources of the
13171     * application to ensure it is unique (see the <a
13172     * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>).
13173     * Keys identified as belonging to
13174     * the Android framework or not associated with any package will cause
13175     * an {@link IllegalArgumentException} to be thrown.
13176     *
13177     * @param key The key identifying the tag
13178     * @param tag An Object to tag the view with
13179     *
13180     * @throws IllegalArgumentException If they specified key is not valid
13181     *
13182     * @see #setTag(Object)
13183     * @see #getTag(int)
13184     */
13185    public void setTag(int key, final Object tag) {
13186        // If the package id is 0x00 or 0x01, it's either an undefined package
13187        // or a framework id
13188        if ((key >>> 24) < 2) {
13189            throw new IllegalArgumentException("The key must be an application-specific "
13190                    + "resource id.");
13191        }
13192
13193        setKeyedTag(key, tag);
13194    }
13195
13196    /**
13197     * Variation of {@link #setTag(int, Object)} that enforces the key to be a
13198     * framework id.
13199     *
13200     * @hide
13201     */
13202    public void setTagInternal(int key, Object tag) {
13203        if ((key >>> 24) != 0x1) {
13204            throw new IllegalArgumentException("The key must be a framework-specific "
13205                    + "resource id.");
13206        }
13207
13208        setKeyedTag(key, tag);
13209    }
13210
13211    private void setKeyedTag(int key, Object tag) {
13212        if (mKeyedTags == null) {
13213            mKeyedTags = new SparseArray<Object>();
13214        }
13215
13216        mKeyedTags.put(key, tag);
13217    }
13218
13219    /**
13220     * @param consistency The type of consistency. See ViewDebug for more information.
13221     *
13222     * @hide
13223     */
13224    protected boolean dispatchConsistencyCheck(int consistency) {
13225        return onConsistencyCheck(consistency);
13226    }
13227
13228    /**
13229     * Method that subclasses should implement to check their consistency. The type of
13230     * consistency check is indicated by the bit field passed as a parameter.
13231     *
13232     * @param consistency The type of consistency. See ViewDebug for more information.
13233     *
13234     * @throws IllegalStateException if the view is in an inconsistent state.
13235     *
13236     * @hide
13237     */
13238    protected boolean onConsistencyCheck(int consistency) {
13239        boolean result = true;
13240
13241        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
13242        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
13243
13244        if (checkLayout) {
13245            if (getParent() == null) {
13246                result = false;
13247                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13248                        "View " + this + " does not have a parent.");
13249            }
13250
13251            if (mAttachInfo == null) {
13252                result = false;
13253                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13254                        "View " + this + " is not attached to a window.");
13255            }
13256        }
13257
13258        if (checkDrawing) {
13259            // Do not check the DIRTY/DRAWN flags because views can call invalidate()
13260            // from their draw() method
13261
13262            if ((mPrivateFlags & DRAWN) != DRAWN &&
13263                    (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
13264                result = false;
13265                android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
13266                        "View " + this + " was invalidated but its drawing cache is valid.");
13267            }
13268        }
13269
13270        return result;
13271    }
13272
13273    /**
13274     * Prints information about this view in the log output, with the tag
13275     * {@link #VIEW_LOG_TAG}.
13276     *
13277     * @hide
13278     */
13279    public void debug() {
13280        debug(0);
13281    }
13282
13283    /**
13284     * Prints information about this view in the log output, with the tag
13285     * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
13286     * indentation defined by the <code>depth</code>.
13287     *
13288     * @param depth the indentation level
13289     *
13290     * @hide
13291     */
13292    protected void debug(int depth) {
13293        String output = debugIndent(depth - 1);
13294
13295        output += "+ " + this;
13296        int id = getId();
13297        if (id != -1) {
13298            output += " (id=" + id + ")";
13299        }
13300        Object tag = getTag();
13301        if (tag != null) {
13302            output += " (tag=" + tag + ")";
13303        }
13304        Log.d(VIEW_LOG_TAG, output);
13305
13306        if ((mPrivateFlags & FOCUSED) != 0) {
13307            output = debugIndent(depth) + " FOCUSED";
13308            Log.d(VIEW_LOG_TAG, output);
13309        }
13310
13311        output = debugIndent(depth);
13312        output += "frame={" + mLeft + ", " + mTop + ", " + mRight
13313                + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
13314                + "} ";
13315        Log.d(VIEW_LOG_TAG, output);
13316
13317        if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
13318                || mPaddingBottom != 0) {
13319            output = debugIndent(depth);
13320            output += "padding={" + mPaddingLeft + ", " + mPaddingTop
13321                    + ", " + mPaddingRight + ", " + mPaddingBottom + "}";
13322            Log.d(VIEW_LOG_TAG, output);
13323        }
13324
13325        output = debugIndent(depth);
13326        output += "mMeasureWidth=" + mMeasuredWidth +
13327                " mMeasureHeight=" + mMeasuredHeight;
13328        Log.d(VIEW_LOG_TAG, output);
13329
13330        output = debugIndent(depth);
13331        if (mLayoutParams == null) {
13332            output += "BAD! no layout params";
13333        } else {
13334            output = mLayoutParams.debug(output);
13335        }
13336        Log.d(VIEW_LOG_TAG, output);
13337
13338        output = debugIndent(depth);
13339        output += "flags={";
13340        output += View.printFlags(mViewFlags);
13341        output += "}";
13342        Log.d(VIEW_LOG_TAG, output);
13343
13344        output = debugIndent(depth);
13345        output += "privateFlags={";
13346        output += View.printPrivateFlags(mPrivateFlags);
13347        output += "}";
13348        Log.d(VIEW_LOG_TAG, output);
13349    }
13350
13351    /**
13352     * Creates a string of whitespaces used for indentation.
13353     *
13354     * @param depth the indentation level
13355     * @return a String containing (depth * 2 + 3) * 2 white spaces
13356     *
13357     * @hide
13358     */
13359    protected static String debugIndent(int depth) {
13360        StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
13361        for (int i = 0; i < (depth * 2) + 3; i++) {
13362            spaces.append(' ').append(' ');
13363        }
13364        return spaces.toString();
13365    }
13366
13367    /**
13368     * <p>Return the offset of the widget's text baseline from the widget's top
13369     * boundary. If this widget does not support baseline alignment, this
13370     * method returns -1. </p>
13371     *
13372     * @return the offset of the baseline within the widget's bounds or -1
13373     *         if baseline alignment is not supported
13374     */
13375    @ViewDebug.ExportedProperty(category = "layout")
13376    public int getBaseline() {
13377        return -1;
13378    }
13379
13380    /**
13381     * Call this when something has changed which has invalidated the
13382     * layout of this view. This will schedule a layout pass of the view
13383     * tree.
13384     */
13385    public void requestLayout() {
13386        if (ViewDebug.TRACE_HIERARCHY) {
13387            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
13388        }
13389
13390        mPrivateFlags |= FORCE_LAYOUT;
13391        mPrivateFlags |= INVALIDATED;
13392
13393        if (mParent != null) {
13394            if (mLayoutParams != null) {
13395                mLayoutParams.onResolveLayoutDirection(getResolvedLayoutDirection());
13396            }
13397            if (!mParent.isLayoutRequested()) {
13398                mParent.requestLayout();
13399            }
13400        }
13401    }
13402
13403    /**
13404     * Forces this view to be laid out during the next layout pass.
13405     * This method does not call requestLayout() or forceLayout()
13406     * on the parent.
13407     */
13408    public void forceLayout() {
13409        mPrivateFlags |= FORCE_LAYOUT;
13410        mPrivateFlags |= INVALIDATED;
13411    }
13412
13413    /**
13414     * <p>
13415     * This is called to find out how big a view should be. The parent
13416     * supplies constraint information in the width and height parameters.
13417     * </p>
13418     *
13419     * <p>
13420     * The actual measurement work of a view is performed in
13421     * {@link #onMeasure(int, int)}, called by this method. Therefore, only
13422     * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
13423     * </p>
13424     *
13425     *
13426     * @param widthMeasureSpec Horizontal space requirements as imposed by the
13427     *        parent
13428     * @param heightMeasureSpec Vertical space requirements as imposed by the
13429     *        parent
13430     *
13431     * @see #onMeasure(int, int)
13432     */
13433    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
13434        if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
13435                widthMeasureSpec != mOldWidthMeasureSpec ||
13436                heightMeasureSpec != mOldHeightMeasureSpec) {
13437
13438            // first clears the measured dimension flag
13439            mPrivateFlags &= ~MEASURED_DIMENSION_SET;
13440
13441            if (ViewDebug.TRACE_HIERARCHY) {
13442                ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
13443            }
13444
13445            // measure ourselves, this should set the measured dimension flag back
13446            onMeasure(widthMeasureSpec, heightMeasureSpec);
13447
13448            // flag not set, setMeasuredDimension() was not invoked, we raise
13449            // an exception to warn the developer
13450            if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
13451                throw new IllegalStateException("onMeasure() did not set the"
13452                        + " measured dimension by calling"
13453                        + " setMeasuredDimension()");
13454            }
13455
13456            mPrivateFlags |= LAYOUT_REQUIRED;
13457        }
13458
13459        mOldWidthMeasureSpec = widthMeasureSpec;
13460        mOldHeightMeasureSpec = heightMeasureSpec;
13461    }
13462
13463    /**
13464     * <p>
13465     * Measure the view and its content to determine the measured width and the
13466     * measured height. This method is invoked by {@link #measure(int, int)} and
13467     * should be overriden by subclasses to provide accurate and efficient
13468     * measurement of their contents.
13469     * </p>
13470     *
13471     * <p>
13472     * <strong>CONTRACT:</strong> When overriding this method, you
13473     * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13474     * measured width and height of this view. Failure to do so will trigger an
13475     * <code>IllegalStateException</code>, thrown by
13476     * {@link #measure(int, int)}. Calling the superclass'
13477     * {@link #onMeasure(int, int)} is a valid use.
13478     * </p>
13479     *
13480     * <p>
13481     * The base class implementation of measure defaults to the background size,
13482     * unless a larger size is allowed by the MeasureSpec. Subclasses should
13483     * override {@link #onMeasure(int, int)} to provide better measurements of
13484     * their content.
13485     * </p>
13486     *
13487     * <p>
13488     * If this method is overridden, it is the subclass's responsibility to make
13489     * sure the measured height and width are at least the view's minimum height
13490     * and width ({@link #getSuggestedMinimumHeight()} and
13491     * {@link #getSuggestedMinimumWidth()}).
13492     * </p>
13493     *
13494     * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
13495     *                         The requirements are encoded with
13496     *                         {@link android.view.View.MeasureSpec}.
13497     * @param heightMeasureSpec vertical space requirements as imposed by the parent.
13498     *                         The requirements are encoded with
13499     *                         {@link android.view.View.MeasureSpec}.
13500     *
13501     * @see #getMeasuredWidth()
13502     * @see #getMeasuredHeight()
13503     * @see #setMeasuredDimension(int, int)
13504     * @see #getSuggestedMinimumHeight()
13505     * @see #getSuggestedMinimumWidth()
13506     * @see android.view.View.MeasureSpec#getMode(int)
13507     * @see android.view.View.MeasureSpec#getSize(int)
13508     */
13509    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
13510        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
13511                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
13512    }
13513
13514    /**
13515     * <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
13516     * measured width and measured height. Failing to do so will trigger an
13517     * exception at measurement time.</p>
13518     *
13519     * @param measuredWidth The measured width of this view.  May be a complex
13520     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13521     * {@link #MEASURED_STATE_TOO_SMALL}.
13522     * @param measuredHeight The measured height of this view.  May be a complex
13523     * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
13524     * {@link #MEASURED_STATE_TOO_SMALL}.
13525     */
13526    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
13527        mMeasuredWidth = measuredWidth;
13528        mMeasuredHeight = measuredHeight;
13529
13530        mPrivateFlags |= MEASURED_DIMENSION_SET;
13531    }
13532
13533    /**
13534     * Merge two states as returned by {@link #getMeasuredState()}.
13535     * @param curState The current state as returned from a view or the result
13536     * of combining multiple views.
13537     * @param newState The new view state to combine.
13538     * @return Returns a new integer reflecting the combination of the two
13539     * states.
13540     */
13541    public static int combineMeasuredStates(int curState, int newState) {
13542        return curState | newState;
13543    }
13544
13545    /**
13546     * Version of {@link #resolveSizeAndState(int, int, int)}
13547     * returning only the {@link #MEASURED_SIZE_MASK} bits of the result.
13548     */
13549    public static int resolveSize(int size, int measureSpec) {
13550        return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK;
13551    }
13552
13553    /**
13554     * Utility to reconcile a desired size and state, with constraints imposed
13555     * by a MeasureSpec.  Will take the desired size, unless a different size
13556     * is imposed by the constraints.  The returned value is a compound integer,
13557     * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
13558     * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting
13559     * size is smaller than the size the view wants to be.
13560     *
13561     * @param size How big the view wants to be
13562     * @param measureSpec Constraints imposed by the parent
13563     * @return Size information bit mask as defined by
13564     * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.
13565     */
13566    public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
13567        int result = size;
13568        int specMode = MeasureSpec.getMode(measureSpec);
13569        int specSize =  MeasureSpec.getSize(measureSpec);
13570        switch (specMode) {
13571        case MeasureSpec.UNSPECIFIED:
13572            result = size;
13573            break;
13574        case MeasureSpec.AT_MOST:
13575            if (specSize < size) {
13576                result = specSize | MEASURED_STATE_TOO_SMALL;
13577            } else {
13578                result = size;
13579            }
13580            break;
13581        case MeasureSpec.EXACTLY:
13582            result = specSize;
13583            break;
13584        }
13585        return result | (childMeasuredState&MEASURED_STATE_MASK);
13586    }
13587
13588    /**
13589     * Utility to return a default size. Uses the supplied size if the
13590     * MeasureSpec imposed no constraints. Will get larger if allowed
13591     * by the MeasureSpec.
13592     *
13593     * @param size Default size for this view
13594     * @param measureSpec Constraints imposed by the parent
13595     * @return The size this view should be.
13596     */
13597    public static int getDefaultSize(int size, int measureSpec) {
13598        int result = size;
13599        int specMode = MeasureSpec.getMode(measureSpec);
13600        int specSize = MeasureSpec.getSize(measureSpec);
13601
13602        switch (specMode) {
13603        case MeasureSpec.UNSPECIFIED:
13604            result = size;
13605            break;
13606        case MeasureSpec.AT_MOST:
13607        case MeasureSpec.EXACTLY:
13608            result = specSize;
13609            break;
13610        }
13611        return result;
13612    }
13613
13614    /**
13615     * Returns the suggested minimum height that the view should use. This
13616     * returns the maximum of the view's minimum height
13617     * and the background's minimum height
13618     * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
13619     * <p>
13620     * When being used in {@link #onMeasure(int, int)}, the caller should still
13621     * ensure the returned height is within the requirements of the parent.
13622     *
13623     * @return The suggested minimum height of the view.
13624     */
13625    protected int getSuggestedMinimumHeight() {
13626        int suggestedMinHeight = mMinHeight;
13627
13628        if (mBGDrawable != null) {
13629            final int bgMinHeight = mBGDrawable.getMinimumHeight();
13630            if (suggestedMinHeight < bgMinHeight) {
13631                suggestedMinHeight = bgMinHeight;
13632            }
13633        }
13634
13635        return suggestedMinHeight;
13636    }
13637
13638    /**
13639     * Returns the suggested minimum width that the view should use. This
13640     * returns the maximum of the view's minimum width)
13641     * and the background's minimum width
13642     *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
13643     * <p>
13644     * When being used in {@link #onMeasure(int, int)}, the caller should still
13645     * ensure the returned width is within the requirements of the parent.
13646     *
13647     * @return The suggested minimum width of the view.
13648     */
13649    protected int getSuggestedMinimumWidth() {
13650        int suggestedMinWidth = mMinWidth;
13651
13652        if (mBGDrawable != null) {
13653            final int bgMinWidth = mBGDrawable.getMinimumWidth();
13654            if (suggestedMinWidth < bgMinWidth) {
13655                suggestedMinWidth = bgMinWidth;
13656            }
13657        }
13658
13659        return suggestedMinWidth;
13660    }
13661
13662    /**
13663     * Sets the minimum height of the view. It is not guaranteed the view will
13664     * be able to achieve this minimum height (for example, if its parent layout
13665     * constrains it with less available height).
13666     *
13667     * @param minHeight The minimum height the view will try to be.
13668     */
13669    public void setMinimumHeight(int minHeight) {
13670        mMinHeight = minHeight;
13671    }
13672
13673    /**
13674     * Sets the minimum width of the view. It is not guaranteed the view will
13675     * be able to achieve this minimum width (for example, if its parent layout
13676     * constrains it with less available width).
13677     *
13678     * @param minWidth The minimum width the view will try to be.
13679     */
13680    public void setMinimumWidth(int minWidth) {
13681        mMinWidth = minWidth;
13682    }
13683
13684    /**
13685     * Get the animation currently associated with this view.
13686     *
13687     * @return The animation that is currently playing or
13688     *         scheduled to play for this view.
13689     */
13690    public Animation getAnimation() {
13691        return mCurrentAnimation;
13692    }
13693
13694    /**
13695     * Start the specified animation now.
13696     *
13697     * @param animation the animation to start now
13698     */
13699    public void startAnimation(Animation animation) {
13700        animation.setStartTime(Animation.START_ON_FIRST_FRAME);
13701        setAnimation(animation);
13702        invalidateParentCaches();
13703        invalidate(true);
13704    }
13705
13706    /**
13707     * Cancels any animations for this view.
13708     */
13709    public void clearAnimation() {
13710        if (mCurrentAnimation != null) {
13711            mCurrentAnimation.detach();
13712        }
13713        mCurrentAnimation = null;
13714        invalidateParentIfNeeded();
13715    }
13716
13717    /**
13718     * Sets the next animation to play for this view.
13719     * If you want the animation to play immediately, use
13720     * startAnimation. This method provides allows fine-grained
13721     * control over the start time and invalidation, but you
13722     * must make sure that 1) the animation has a start time set, and
13723     * 2) the view will be invalidated when the animation is supposed to
13724     * start.
13725     *
13726     * @param animation The next animation, or null.
13727     */
13728    public void setAnimation(Animation animation) {
13729        mCurrentAnimation = animation;
13730        if (animation != null) {
13731            animation.reset();
13732        }
13733    }
13734
13735    /**
13736     * Invoked by a parent ViewGroup to notify the start of the animation
13737     * currently associated with this view. If you override this method,
13738     * always call super.onAnimationStart();
13739     *
13740     * @see #setAnimation(android.view.animation.Animation)
13741     * @see #getAnimation()
13742     */
13743    protected void onAnimationStart() {
13744        mPrivateFlags |= ANIMATION_STARTED;
13745    }
13746
13747    /**
13748     * Invoked by a parent ViewGroup to notify the end of the animation
13749     * currently associated with this view. If you override this method,
13750     * always call super.onAnimationEnd();
13751     *
13752     * @see #setAnimation(android.view.animation.Animation)
13753     * @see #getAnimation()
13754     */
13755    protected void onAnimationEnd() {
13756        mPrivateFlags &= ~ANIMATION_STARTED;
13757    }
13758
13759    /**
13760     * Invoked if there is a Transform that involves alpha. Subclass that can
13761     * draw themselves with the specified alpha should return true, and then
13762     * respect that alpha when their onDraw() is called. If this returns false
13763     * then the view may be redirected to draw into an offscreen buffer to
13764     * fulfill the request, which will look fine, but may be slower than if the
13765     * subclass handles it internally. The default implementation returns false.
13766     *
13767     * @param alpha The alpha (0..255) to apply to the view's drawing
13768     * @return true if the view can draw with the specified alpha.
13769     */
13770    protected boolean onSetAlpha(int alpha) {
13771        return false;
13772    }
13773
13774    /**
13775     * This is used by the RootView to perform an optimization when
13776     * the view hierarchy contains one or several SurfaceView.
13777     * SurfaceView is always considered transparent, but its children are not,
13778     * therefore all View objects remove themselves from the global transparent
13779     * region (passed as a parameter to this function).
13780     *
13781     * @param region The transparent region for this ViewAncestor (window).
13782     *
13783     * @return Returns true if the effective visibility of the view at this
13784     * point is opaque, regardless of the transparent region; returns false
13785     * if it is possible for underlying windows to be seen behind the view.
13786     *
13787     * {@hide}
13788     */
13789    public boolean gatherTransparentRegion(Region region) {
13790        final AttachInfo attachInfo = mAttachInfo;
13791        if (region != null && attachInfo != null) {
13792            final int pflags = mPrivateFlags;
13793            if ((pflags & SKIP_DRAW) == 0) {
13794                // The SKIP_DRAW flag IS NOT set, so this view draws. We need to
13795                // remove it from the transparent region.
13796                final int[] location = attachInfo.mTransparentLocation;
13797                getLocationInWindow(location);
13798                region.op(location[0], location[1], location[0] + mRight - mLeft,
13799                        location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
13800            } else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
13801                // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
13802                // exists, so we remove the background drawable's non-transparent
13803                // parts from this transparent region.
13804                applyDrawableToTransparentRegion(mBGDrawable, region);
13805            }
13806        }
13807        return true;
13808    }
13809
13810    /**
13811     * Play a sound effect for this view.
13812     *
13813     * <p>The framework will play sound effects for some built in actions, such as
13814     * clicking, but you may wish to play these effects in your widget,
13815     * for instance, for internal navigation.
13816     *
13817     * <p>The sound effect will only be played if sound effects are enabled by the user, and
13818     * {@link #isSoundEffectsEnabled()} is true.
13819     *
13820     * @param soundConstant One of the constants defined in {@link SoundEffectConstants}
13821     */
13822    public void playSoundEffect(int soundConstant) {
13823        if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
13824            return;
13825        }
13826        mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
13827    }
13828
13829    /**
13830     * BZZZTT!!1!
13831     *
13832     * <p>Provide haptic feedback to the user for this view.
13833     *
13834     * <p>The framework will provide haptic feedback for some built in actions,
13835     * such as long presses, but you may wish to provide feedback for your
13836     * own widget.
13837     *
13838     * <p>The feedback will only be performed if
13839     * {@link #isHapticFeedbackEnabled()} is true.
13840     *
13841     * @param feedbackConstant One of the constants defined in
13842     * {@link HapticFeedbackConstants}
13843     */
13844    public boolean performHapticFeedback(int feedbackConstant) {
13845        return performHapticFeedback(feedbackConstant, 0);
13846    }
13847
13848    /**
13849     * BZZZTT!!1!
13850     *
13851     * <p>Like {@link #performHapticFeedback(int)}, with additional options.
13852     *
13853     * @param feedbackConstant One of the constants defined in
13854     * {@link HapticFeedbackConstants}
13855     * @param flags Additional flags as per {@link HapticFeedbackConstants}.
13856     */
13857    public boolean performHapticFeedback(int feedbackConstant, int flags) {
13858        if (mAttachInfo == null) {
13859            return false;
13860        }
13861        //noinspection SimplifiableIfStatement
13862        if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
13863                && !isHapticFeedbackEnabled()) {
13864            return false;
13865        }
13866        return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant,
13867                (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
13868    }
13869
13870    /**
13871     * Request that the visibility of the status bar be changed.
13872     * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13873     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13874     */
13875    public void setSystemUiVisibility(int visibility) {
13876        if (visibility != mSystemUiVisibility) {
13877            mSystemUiVisibility = visibility;
13878            if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13879                mParent.recomputeViewAttributes(this);
13880            }
13881        }
13882    }
13883
13884    /**
13885     * Returns the status bar visibility that this view has requested.
13886     * @return  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
13887     * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.
13888     */
13889    public int getSystemUiVisibility() {
13890        return mSystemUiVisibility;
13891    }
13892
13893    /**
13894     * Set a listener to receive callbacks when the visibility of the system bar changes.
13895     * @param l  The {@link OnSystemUiVisibilityChangeListener} to receive callbacks.
13896     */
13897    public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) {
13898        getListenerInfo().mOnSystemUiVisibilityChangeListener = l;
13899        if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
13900            mParent.recomputeViewAttributes(this);
13901        }
13902    }
13903
13904    /**
13905     * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down
13906     * the view hierarchy.
13907     */
13908    public void dispatchSystemUiVisibilityChanged(int visibility) {
13909        ListenerInfo li = mListenerInfo;
13910        if (li != null && li.mOnSystemUiVisibilityChangeListener != null) {
13911            li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange(
13912                    visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK);
13913        }
13914    }
13915
13916    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
13917        int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges);
13918        if (val != mSystemUiVisibility) {
13919            setSystemUiVisibility(val);
13920        }
13921    }
13922
13923    /**
13924     * Creates an image that the system displays during the drag and drop
13925     * operation. This is called a &quot;drag shadow&quot;. The default implementation
13926     * for a DragShadowBuilder based on a View returns an image that has exactly the same
13927     * appearance as the given View. The default also positions the center of the drag shadow
13928     * directly under the touch point. If no View is provided (the constructor with no parameters
13929     * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and
13930     * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the
13931     * default is an invisible drag shadow.
13932     * <p>
13933     * You are not required to use the View you provide to the constructor as the basis of the
13934     * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw
13935     * anything you want as the drag shadow.
13936     * </p>
13937     * <p>
13938     *  You pass a DragShadowBuilder object to the system when you start the drag. The system
13939     *  calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the
13940     *  size and position of the drag shadow. It uses this data to construct a
13941     *  {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()}
13942     *  so that your application can draw the shadow image in the Canvas.
13943     * </p>
13944     *
13945     * <div class="special reference">
13946     * <h3>Developer Guides</h3>
13947     * <p>For a guide to implementing drag and drop features, read the
13948     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
13949     * </div>
13950     */
13951    public static class DragShadowBuilder {
13952        private final WeakReference<View> mView;
13953
13954        /**
13955         * Constructs a shadow image builder based on a View. By default, the resulting drag
13956         * shadow will have the same appearance and dimensions as the View, with the touch point
13957         * over the center of the View.
13958         * @param view A View. Any View in scope can be used.
13959         */
13960        public DragShadowBuilder(View view) {
13961            mView = new WeakReference<View>(view);
13962        }
13963
13964        /**
13965         * Construct a shadow builder object with no associated View.  This
13966         * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)}
13967         * and {@link #onDrawShadow(Canvas)} methods are also overridden in order
13968         * to supply the drag shadow's dimensions and appearance without
13969         * reference to any View object. If they are not overridden, then the result is an
13970         * invisible drag shadow.
13971         */
13972        public DragShadowBuilder() {
13973            mView = new WeakReference<View>(null);
13974        }
13975
13976        /**
13977         * Returns the View object that had been passed to the
13978         * {@link #View.DragShadowBuilder(View)}
13979         * constructor.  If that View parameter was {@code null} or if the
13980         * {@link #View.DragShadowBuilder()}
13981         * constructor was used to instantiate the builder object, this method will return
13982         * null.
13983         *
13984         * @return The View object associate with this builder object.
13985         */
13986        @SuppressWarnings({"JavadocReference"})
13987        final public View getView() {
13988            return mView.get();
13989        }
13990
13991        /**
13992         * Provides the metrics for the shadow image. These include the dimensions of
13993         * the shadow image, and the point within that shadow that should
13994         * be centered under the touch location while dragging.
13995         * <p>
13996         * The default implementation sets the dimensions of the shadow to be the
13997         * same as the dimensions of the View itself and centers the shadow under
13998         * the touch point.
13999         * </p>
14000         *
14001         * @param shadowSize A {@link android.graphics.Point} containing the width and height
14002         * of the shadow image. Your application must set {@link android.graphics.Point#x} to the
14003         * desired width and must set {@link android.graphics.Point#y} to the desired height of the
14004         * image.
14005         *
14006         * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the
14007         * shadow image that should be underneath the touch point during the drag and drop
14008         * operation. Your application must set {@link android.graphics.Point#x} to the
14009         * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position.
14010         */
14011        public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
14012            final View view = mView.get();
14013            if (view != null) {
14014                shadowSize.set(view.getWidth(), view.getHeight());
14015                shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
14016            } else {
14017                Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
14018            }
14019        }
14020
14021        /**
14022         * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object
14023         * based on the dimensions it received from the
14024         * {@link #onProvideShadowMetrics(Point, Point)} callback.
14025         *
14026         * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image.
14027         */
14028        public void onDrawShadow(Canvas canvas) {
14029            final View view = mView.get();
14030            if (view != null) {
14031                view.draw(canvas);
14032            } else {
14033                Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
14034            }
14035        }
14036    }
14037
14038    /**
14039     * Starts a drag and drop operation. When your application calls this method, it passes a
14040     * {@link android.view.View.DragShadowBuilder} object to the system. The
14041     * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)}
14042     * to get metrics for the drag shadow, and then calls the object's
14043     * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself.
14044     * <p>
14045     *  Once the system has the drag shadow, it begins the drag and drop operation by sending
14046     *  drag events to all the View objects in your application that are currently visible. It does
14047     *  this either by calling the View object's drag listener (an implementation of
14048     *  {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the
14049     *  View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method.
14050     *  Both are passed a {@link android.view.DragEvent} object that has a
14051     *  {@link android.view.DragEvent#getAction()} value of
14052     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED}.
14053     * </p>
14054     * <p>
14055     * Your application can invoke startDrag() on any attached View object. The View object does not
14056     * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to
14057     * be related to the View the user selected for dragging.
14058     * </p>
14059     * @param data A {@link android.content.ClipData} object pointing to the data to be
14060     * transferred by the drag and drop operation.
14061     * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the
14062     * drag shadow.
14063     * @param myLocalState An {@link java.lang.Object} containing local data about the drag and
14064     * drop operation. This Object is put into every DragEvent object sent by the system during the
14065     * current drag.
14066     * <p>
14067     * myLocalState is a lightweight mechanism for the sending information from the dragged View
14068     * to the target Views. For example, it can contain flags that differentiate between a
14069     * a copy operation and a move operation.
14070     * </p>
14071     * @param flags Flags that control the drag and drop operation. No flags are currently defined,
14072     * so the parameter should be set to 0.
14073     * @return {@code true} if the method completes successfully, or
14074     * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to
14075     * do a drag, and so no drag operation is in progress.
14076     */
14077    public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
14078            Object myLocalState, int flags) {
14079        if (ViewDebug.DEBUG_DRAG) {
14080            Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags);
14081        }
14082        boolean okay = false;
14083
14084        Point shadowSize = new Point();
14085        Point shadowTouchPoint = new Point();
14086        shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
14087
14088        if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
14089                (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
14090            throw new IllegalStateException("Drag shadow dimensions must not be negative");
14091        }
14092
14093        if (ViewDebug.DEBUG_DRAG) {
14094            Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
14095                    + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
14096        }
14097        Surface surface = new Surface();
14098        try {
14099            IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
14100                    flags, shadowSize.x, shadowSize.y, surface);
14101            if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
14102                    + " surface=" + surface);
14103            if (token != null) {
14104                Canvas canvas = surface.lockCanvas(null);
14105                try {
14106                    canvas.drawColor(0, PorterDuff.Mode.CLEAR);
14107                    shadowBuilder.onDrawShadow(canvas);
14108                } finally {
14109                    surface.unlockCanvasAndPost(canvas);
14110                }
14111
14112                final ViewRootImpl root = getViewRootImpl();
14113
14114                // Cache the local state object for delivery with DragEvents
14115                root.setLocalDragState(myLocalState);
14116
14117                // repurpose 'shadowSize' for the last touch point
14118                root.getLastTouchPoint(shadowSize);
14119
14120                okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
14121                        shadowSize.x, shadowSize.y,
14122                        shadowTouchPoint.x, shadowTouchPoint.y, data);
14123                if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
14124
14125                // Off and running!  Release our local surface instance; the drag
14126                // shadow surface is now managed by the system process.
14127                surface.release();
14128            }
14129        } catch (Exception e) {
14130            Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e);
14131            surface.destroy();
14132        }
14133
14134        return okay;
14135    }
14136
14137    /**
14138     * Handles drag events sent by the system following a call to
14139     * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}.
14140     *<p>
14141     * When the system calls this method, it passes a
14142     * {@link android.view.DragEvent} object. A call to
14143     * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined
14144     * in DragEvent. The method uses these to determine what is happening in the drag and drop
14145     * operation.
14146     * @param event The {@link android.view.DragEvent} sent by the system.
14147     * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined
14148     * in DragEvent, indicating the type of drag event represented by this object.
14149     * @return {@code true} if the method was successful, otherwise {@code false}.
14150     * <p>
14151     *  The method should return {@code true} in response to an action type of
14152     *  {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current
14153     *  operation.
14154     * </p>
14155     * <p>
14156     *  The method should also return {@code true} in response to an action type of
14157     *  {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or
14158     *  {@code false} if it didn't.
14159     * </p>
14160     */
14161    public boolean onDragEvent(DragEvent event) {
14162        return false;
14163    }
14164
14165    /**
14166     * Detects if this View is enabled and has a drag event listener.
14167     * If both are true, then it calls the drag event listener with the
14168     * {@link android.view.DragEvent} it received. If the drag event listener returns
14169     * {@code true}, then dispatchDragEvent() returns {@code true}.
14170     * <p>
14171     * For all other cases, the method calls the
14172     * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler
14173     * method and returns its result.
14174     * </p>
14175     * <p>
14176     * This ensures that a drag event is always consumed, even if the View does not have a drag
14177     * event listener. However, if the View has a listener and the listener returns true, then
14178     * onDragEvent() is not called.
14179     * </p>
14180     */
14181    public boolean dispatchDragEvent(DragEvent event) {
14182        //noinspection SimplifiableIfStatement
14183        ListenerInfo li = mListenerInfo;
14184        if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
14185                && li.mOnDragListener.onDrag(this, event)) {
14186            return true;
14187        }
14188        return onDragEvent(event);
14189    }
14190
14191    boolean canAcceptDrag() {
14192        return (mPrivateFlags2 & DRAG_CAN_ACCEPT) != 0;
14193    }
14194
14195    /**
14196     * This needs to be a better API (NOT ON VIEW) before it is exposed.  If
14197     * it is ever exposed at all.
14198     * @hide
14199     */
14200    public void onCloseSystemDialogs(String reason) {
14201    }
14202
14203    /**
14204     * Given a Drawable whose bounds have been set to draw into this view,
14205     * update a Region being computed for
14206     * {@link #gatherTransparentRegion(android.graphics.Region)} so
14207     * that any non-transparent parts of the Drawable are removed from the
14208     * given transparent region.
14209     *
14210     * @param dr The Drawable whose transparency is to be applied to the region.
14211     * @param region A Region holding the current transparency information,
14212     * where any parts of the region that are set are considered to be
14213     * transparent.  On return, this region will be modified to have the
14214     * transparency information reduced by the corresponding parts of the
14215     * Drawable that are not transparent.
14216     * {@hide}
14217     */
14218    public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
14219        if (DBG) {
14220            Log.i("View", "Getting transparent region for: " + this);
14221        }
14222        final Region r = dr.getTransparentRegion();
14223        final Rect db = dr.getBounds();
14224        final AttachInfo attachInfo = mAttachInfo;
14225        if (r != null && attachInfo != null) {
14226            final int w = getRight()-getLeft();
14227            final int h = getBottom()-getTop();
14228            if (db.left > 0) {
14229                //Log.i("VIEW", "Drawable left " + db.left + " > view 0");
14230                r.op(0, 0, db.left, h, Region.Op.UNION);
14231            }
14232            if (db.right < w) {
14233                //Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
14234                r.op(db.right, 0, w, h, Region.Op.UNION);
14235            }
14236            if (db.top > 0) {
14237                //Log.i("VIEW", "Drawable top " + db.top + " > view 0");
14238                r.op(0, 0, w, db.top, Region.Op.UNION);
14239            }
14240            if (db.bottom < h) {
14241                //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
14242                r.op(0, db.bottom, w, h, Region.Op.UNION);
14243            }
14244            final int[] location = attachInfo.mTransparentLocation;
14245            getLocationInWindow(location);
14246            r.translate(location[0], location[1]);
14247            region.op(r, Region.Op.INTERSECT);
14248        } else {
14249            region.op(db, Region.Op.DIFFERENCE);
14250        }
14251    }
14252
14253    private void checkForLongClick(int delayOffset) {
14254        if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
14255            mHasPerformedLongPress = false;
14256
14257            if (mPendingCheckForLongPress == null) {
14258                mPendingCheckForLongPress = new CheckForLongPress();
14259            }
14260            mPendingCheckForLongPress.rememberWindowAttachCount();
14261            postDelayed(mPendingCheckForLongPress,
14262                    ViewConfiguration.getLongPressTimeout() - delayOffset);
14263        }
14264    }
14265
14266    /**
14267     * Inflate a view from an XML resource.  This convenience method wraps the {@link
14268     * LayoutInflater} class, which provides a full range of options for view inflation.
14269     *
14270     * @param context The Context object for your activity or application.
14271     * @param resource The resource ID to inflate
14272     * @param root A view group that will be the parent.  Used to properly inflate the
14273     * layout_* parameters.
14274     * @see LayoutInflater
14275     */
14276    public static View inflate(Context context, int resource, ViewGroup root) {
14277        LayoutInflater factory = LayoutInflater.from(context);
14278        return factory.inflate(resource, root);
14279    }
14280
14281    /**
14282     * Scroll the view with standard behavior for scrolling beyond the normal
14283     * content boundaries. Views that call this method should override
14284     * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the
14285     * results of an over-scroll operation.
14286     *
14287     * Views can use this method to handle any touch or fling-based scrolling.
14288     *
14289     * @param deltaX Change in X in pixels
14290     * @param deltaY Change in Y in pixels
14291     * @param scrollX Current X scroll value in pixels before applying deltaX
14292     * @param scrollY Current Y scroll value in pixels before applying deltaY
14293     * @param scrollRangeX Maximum content scroll range along the X axis
14294     * @param scrollRangeY Maximum content scroll range along the Y axis
14295     * @param maxOverScrollX Number of pixels to overscroll by in either direction
14296     *          along the X axis.
14297     * @param maxOverScrollY Number of pixels to overscroll by in either direction
14298     *          along the Y axis.
14299     * @param isTouchEvent true if this scroll operation is the result of a touch event.
14300     * @return true if scrolling was clamped to an over-scroll boundary along either
14301     *          axis, false otherwise.
14302     */
14303    @SuppressWarnings({"UnusedParameters"})
14304    protected boolean overScrollBy(int deltaX, int deltaY,
14305            int scrollX, int scrollY,
14306            int scrollRangeX, int scrollRangeY,
14307            int maxOverScrollX, int maxOverScrollY,
14308            boolean isTouchEvent) {
14309        final int overScrollMode = mOverScrollMode;
14310        final boolean canScrollHorizontal =
14311                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
14312        final boolean canScrollVertical =
14313                computeVerticalScrollRange() > computeVerticalScrollExtent();
14314        final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
14315                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
14316        final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
14317                (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
14318
14319        int newScrollX = scrollX + deltaX;
14320        if (!overScrollHorizontal) {
14321            maxOverScrollX = 0;
14322        }
14323
14324        int newScrollY = scrollY + deltaY;
14325        if (!overScrollVertical) {
14326            maxOverScrollY = 0;
14327        }
14328
14329        // Clamp values if at the limits and record
14330        final int left = -maxOverScrollX;
14331        final int right = maxOverScrollX + scrollRangeX;
14332        final int top = -maxOverScrollY;
14333        final int bottom = maxOverScrollY + scrollRangeY;
14334
14335        boolean clampedX = false;
14336        if (newScrollX > right) {
14337            newScrollX = right;
14338            clampedX = true;
14339        } else if (newScrollX < left) {
14340            newScrollX = left;
14341            clampedX = true;
14342        }
14343
14344        boolean clampedY = false;
14345        if (newScrollY > bottom) {
14346            newScrollY = bottom;
14347            clampedY = true;
14348        } else if (newScrollY < top) {
14349            newScrollY = top;
14350            clampedY = true;
14351        }
14352
14353        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
14354
14355        return clampedX || clampedY;
14356    }
14357
14358    /**
14359     * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to
14360     * respond to the results of an over-scroll operation.
14361     *
14362     * @param scrollX New X scroll value in pixels
14363     * @param scrollY New Y scroll value in pixels
14364     * @param clampedX True if scrollX was clamped to an over-scroll boundary
14365     * @param clampedY True if scrollY was clamped to an over-scroll boundary
14366     */
14367    protected void onOverScrolled(int scrollX, int scrollY,
14368            boolean clampedX, boolean clampedY) {
14369        // Intentionally empty.
14370    }
14371
14372    /**
14373     * Returns the over-scroll mode for this view. The result will be
14374     * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14375     * (allow over-scrolling only if the view content is larger than the container),
14376     * or {@link #OVER_SCROLL_NEVER}.
14377     *
14378     * @return This view's over-scroll mode.
14379     */
14380    public int getOverScrollMode() {
14381        return mOverScrollMode;
14382    }
14383
14384    /**
14385     * Set the over-scroll mode for this view. Valid over-scroll modes are
14386     * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}
14387     * (allow over-scrolling only if the view content is larger than the container),
14388     * or {@link #OVER_SCROLL_NEVER}.
14389     *
14390     * Setting the over-scroll mode of a view will have an effect only if the
14391     * view is capable of scrolling.
14392     *
14393     * @param overScrollMode The new over-scroll mode for this view.
14394     */
14395    public void setOverScrollMode(int overScrollMode) {
14396        if (overScrollMode != OVER_SCROLL_ALWAYS &&
14397                overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS &&
14398                overScrollMode != OVER_SCROLL_NEVER) {
14399            throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode);
14400        }
14401        mOverScrollMode = overScrollMode;
14402    }
14403
14404    /**
14405     * Gets a scale factor that determines the distance the view should scroll
14406     * vertically in response to {@link MotionEvent#ACTION_SCROLL}.
14407     * @return The vertical scroll scale factor.
14408     * @hide
14409     */
14410    protected float getVerticalScrollFactor() {
14411        if (mVerticalScrollFactor == 0) {
14412            TypedValue outValue = new TypedValue();
14413            if (!mContext.getTheme().resolveAttribute(
14414                    com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) {
14415                throw new IllegalStateException(
14416                        "Expected theme to define listPreferredItemHeight.");
14417            }
14418            mVerticalScrollFactor = outValue.getDimension(
14419                    mContext.getResources().getDisplayMetrics());
14420        }
14421        return mVerticalScrollFactor;
14422    }
14423
14424    /**
14425     * Gets a scale factor that determines the distance the view should scroll
14426     * horizontally in response to {@link MotionEvent#ACTION_SCROLL}.
14427     * @return The horizontal scroll scale factor.
14428     * @hide
14429     */
14430    protected float getHorizontalScrollFactor() {
14431        // TODO: Should use something else.
14432        return getVerticalScrollFactor();
14433    }
14434
14435    /**
14436     * Return the value specifying the text direction or policy that was set with
14437     * {@link #setTextDirection(int)}.
14438     *
14439     * @return the defined text direction. It can be one of:
14440     *
14441     * {@link #TEXT_DIRECTION_INHERIT},
14442     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14443     * {@link #TEXT_DIRECTION_ANY_RTL},
14444     * {@link #TEXT_DIRECTION_LTR},
14445     * {@link #TEXT_DIRECTION_RTL},
14446     * {@link #TEXT_DIRECTION_LOCALE},
14447     */
14448    public int getTextDirection() {
14449        return mTextDirection;
14450    }
14451
14452    /**
14453     * Set the text direction.
14454     *
14455     * @param textDirection the direction to set. Should be one of:
14456     *
14457     * {@link #TEXT_DIRECTION_INHERIT},
14458     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14459     * {@link #TEXT_DIRECTION_ANY_RTL},
14460     * {@link #TEXT_DIRECTION_LTR},
14461     * {@link #TEXT_DIRECTION_RTL},
14462     * {@link #TEXT_DIRECTION_LOCALE},
14463     */
14464    public void setTextDirection(int textDirection) {
14465        if (textDirection != mTextDirection) {
14466            mTextDirection = textDirection;
14467            resetResolvedTextDirection();
14468            requestLayout();
14469        }
14470    }
14471
14472    /**
14473     * Return the resolved text direction.
14474     *
14475     * @return the resolved text direction. Return one of:
14476     *
14477     * {@link #TEXT_DIRECTION_FIRST_STRONG}
14478     * {@link #TEXT_DIRECTION_ANY_RTL},
14479     * {@link #TEXT_DIRECTION_LTR},
14480     * {@link #TEXT_DIRECTION_RTL},
14481     * {@link #TEXT_DIRECTION_LOCALE},
14482     */
14483    public int getResolvedTextDirection() {
14484        if (mResolvedTextDirection == TEXT_DIRECTION_INHERIT) {
14485            resolveTextDirection();
14486        }
14487        return mResolvedTextDirection;
14488    }
14489
14490    /**
14491     * Resolve the text direction. Will call {@link View#onResolvedTextDirectionChanged} when
14492     * resolution is done.
14493     */
14494    public void resolveTextDirection() {
14495        if (mResolvedTextDirection != TEXT_DIRECTION_INHERIT) {
14496            // Resolution has already been done.
14497            return;
14498        }
14499        if (mTextDirection != TEXT_DIRECTION_INHERIT) {
14500            mResolvedTextDirection = mTextDirection;
14501        } else if (mParent != null && mParent instanceof ViewGroup) {
14502            mResolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection();
14503        } else {
14504            mResolvedTextDirection = TEXT_DIRECTION_FIRST_STRONG;
14505        }
14506        onResolvedTextDirectionChanged();
14507    }
14508
14509    /**
14510     * Called when text direction has been resolved. Subclasses that care about text direction
14511     * resolution should override this method.
14512     *
14513     * The default implementation does nothing.
14514     */
14515    public void onResolvedTextDirectionChanged() {
14516    }
14517
14518    /**
14519     * Reset resolved text direction. Text direction can be resolved with a call to
14520     * getResolvedTextDirection(). Will call {@link View#onResolvedTextDirectionReset} when
14521     * reset is done.
14522     */
14523    public void resetResolvedTextDirection() {
14524        mResolvedTextDirection = TEXT_DIRECTION_INHERIT;
14525        onResolvedTextDirectionReset();
14526    }
14527
14528    /**
14529     * Called when text direction is reset. Subclasses that care about text direction reset should
14530     * override this method and do a reset of the text direction of their children. The default
14531     * implementation does nothing.
14532     */
14533    public void onResolvedTextDirectionReset() {
14534    }
14535
14536    //
14537    // Properties
14538    //
14539    /**
14540     * A Property wrapper around the <code>alpha</code> functionality handled by the
14541     * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods.
14542     */
14543    public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") {
14544        @Override
14545        public void setValue(View object, float value) {
14546            object.setAlpha(value);
14547        }
14548
14549        @Override
14550        public Float get(View object) {
14551            return object.getAlpha();
14552        }
14553    };
14554
14555    /**
14556     * A Property wrapper around the <code>translationX</code> functionality handled by the
14557     * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods.
14558     */
14559    public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") {
14560        @Override
14561        public void setValue(View object, float value) {
14562            object.setTranslationX(value);
14563        }
14564
14565                @Override
14566        public Float get(View object) {
14567            return object.getTranslationX();
14568        }
14569    };
14570
14571    /**
14572     * A Property wrapper around the <code>translationY</code> functionality handled by the
14573     * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods.
14574     */
14575    public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") {
14576        @Override
14577        public void setValue(View object, float value) {
14578            object.setTranslationY(value);
14579        }
14580
14581        @Override
14582        public Float get(View object) {
14583            return object.getTranslationY();
14584        }
14585    };
14586
14587    /**
14588     * A Property wrapper around the <code>x</code> functionality handled by the
14589     * {@link View#setX(float)} and {@link View#getX()} methods.
14590     */
14591    public static final Property<View, Float> X = new FloatProperty<View>("x") {
14592        @Override
14593        public void setValue(View object, float value) {
14594            object.setX(value);
14595        }
14596
14597        @Override
14598        public Float get(View object) {
14599            return object.getX();
14600        }
14601    };
14602
14603    /**
14604     * A Property wrapper around the <code>y</code> functionality handled by the
14605     * {@link View#setY(float)} and {@link View#getY()} methods.
14606     */
14607    public static final Property<View, Float> Y = new FloatProperty<View>("y") {
14608        @Override
14609        public void setValue(View object, float value) {
14610            object.setY(value);
14611        }
14612
14613        @Override
14614        public Float get(View object) {
14615            return object.getY();
14616        }
14617    };
14618
14619    /**
14620     * A Property wrapper around the <code>rotation</code> functionality handled by the
14621     * {@link View#setRotation(float)} and {@link View#getRotation()} methods.
14622     */
14623    public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") {
14624        @Override
14625        public void setValue(View object, float value) {
14626            object.setRotation(value);
14627        }
14628
14629        @Override
14630        public Float get(View object) {
14631            return object.getRotation();
14632        }
14633    };
14634
14635    /**
14636     * A Property wrapper around the <code>rotationX</code> functionality handled by the
14637     * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods.
14638     */
14639    public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") {
14640        @Override
14641        public void setValue(View object, float value) {
14642            object.setRotationX(value);
14643        }
14644
14645        @Override
14646        public Float get(View object) {
14647            return object.getRotationX();
14648        }
14649    };
14650
14651    /**
14652     * A Property wrapper around the <code>rotationY</code> functionality handled by the
14653     * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods.
14654     */
14655    public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") {
14656        @Override
14657        public void setValue(View object, float value) {
14658            object.setRotationY(value);
14659        }
14660
14661        @Override
14662        public Float get(View object) {
14663            return object.getRotationY();
14664        }
14665    };
14666
14667    /**
14668     * A Property wrapper around the <code>scaleX</code> functionality handled by the
14669     * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods.
14670     */
14671    public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") {
14672        @Override
14673        public void setValue(View object, float value) {
14674            object.setScaleX(value);
14675        }
14676
14677        @Override
14678        public Float get(View object) {
14679            return object.getScaleX();
14680        }
14681    };
14682
14683    /**
14684     * A Property wrapper around the <code>scaleY</code> functionality handled by the
14685     * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods.
14686     */
14687    public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") {
14688        @Override
14689        public void setValue(View object, float value) {
14690            object.setScaleY(value);
14691        }
14692
14693        @Override
14694        public Float get(View object) {
14695            return object.getScaleY();
14696        }
14697    };
14698
14699    /**
14700     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
14701     * Each MeasureSpec represents a requirement for either the width or the height.
14702     * A MeasureSpec is comprised of a size and a mode. There are three possible
14703     * modes:
14704     * <dl>
14705     * <dt>UNSPECIFIED</dt>
14706     * <dd>
14707     * The parent has not imposed any constraint on the child. It can be whatever size
14708     * it wants.
14709     * </dd>
14710     *
14711     * <dt>EXACTLY</dt>
14712     * <dd>
14713     * The parent has determined an exact size for the child. The child is going to be
14714     * given those bounds regardless of how big it wants to be.
14715     * </dd>
14716     *
14717     * <dt>AT_MOST</dt>
14718     * <dd>
14719     * The child can be as large as it wants up to the specified size.
14720     * </dd>
14721     * </dl>
14722     *
14723     * MeasureSpecs are implemented as ints to reduce object allocation. This class
14724     * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
14725     */
14726    public static class MeasureSpec {
14727        private static final int MODE_SHIFT = 30;
14728        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
14729
14730        /**
14731         * Measure specification mode: The parent has not imposed any constraint
14732         * on the child. It can be whatever size it wants.
14733         */
14734        public static final int UNSPECIFIED = 0 << MODE_SHIFT;
14735
14736        /**
14737         * Measure specification mode: The parent has determined an exact size
14738         * for the child. The child is going to be given those bounds regardless
14739         * of how big it wants to be.
14740         */
14741        public static final int EXACTLY     = 1 << MODE_SHIFT;
14742
14743        /**
14744         * Measure specification mode: The child can be as large as it wants up
14745         * to the specified size.
14746         */
14747        public static final int AT_MOST     = 2 << MODE_SHIFT;
14748
14749        /**
14750         * Creates a measure specification based on the supplied size and mode.
14751         *
14752         * The mode must always be one of the following:
14753         * <ul>
14754         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
14755         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
14756         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
14757         * </ul>
14758         *
14759         * @param size the size of the measure specification
14760         * @param mode the mode of the measure specification
14761         * @return the measure specification based on size and mode
14762         */
14763        public static int makeMeasureSpec(int size, int mode) {
14764            return size + mode;
14765        }
14766
14767        /**
14768         * Extracts the mode from the supplied measure specification.
14769         *
14770         * @param measureSpec the measure specification to extract the mode from
14771         * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
14772         *         {@link android.view.View.MeasureSpec#AT_MOST} or
14773         *         {@link android.view.View.MeasureSpec#EXACTLY}
14774         */
14775        public static int getMode(int measureSpec) {
14776            return (measureSpec & MODE_MASK);
14777        }
14778
14779        /**
14780         * Extracts the size from the supplied measure specification.
14781         *
14782         * @param measureSpec the measure specification to extract the size from
14783         * @return the size in pixels defined in the supplied measure specification
14784         */
14785        public static int getSize(int measureSpec) {
14786            return (measureSpec & ~MODE_MASK);
14787        }
14788
14789        /**
14790         * Returns a String representation of the specified measure
14791         * specification.
14792         *
14793         * @param measureSpec the measure specification to convert to a String
14794         * @return a String with the following format: "MeasureSpec: MODE SIZE"
14795         */
14796        public static String toString(int measureSpec) {
14797            int mode = getMode(measureSpec);
14798            int size = getSize(measureSpec);
14799
14800            StringBuilder sb = new StringBuilder("MeasureSpec: ");
14801
14802            if (mode == UNSPECIFIED)
14803                sb.append("UNSPECIFIED ");
14804            else if (mode == EXACTLY)
14805                sb.append("EXACTLY ");
14806            else if (mode == AT_MOST)
14807                sb.append("AT_MOST ");
14808            else
14809                sb.append(mode).append(" ");
14810
14811            sb.append(size);
14812            return sb.toString();
14813        }
14814    }
14815
14816    class CheckForLongPress implements Runnable {
14817
14818        private int mOriginalWindowAttachCount;
14819
14820        public void run() {
14821            if (isPressed() && (mParent != null)
14822                    && mOriginalWindowAttachCount == mWindowAttachCount) {
14823                if (performLongClick()) {
14824                    mHasPerformedLongPress = true;
14825                }
14826            }
14827        }
14828
14829        public void rememberWindowAttachCount() {
14830            mOriginalWindowAttachCount = mWindowAttachCount;
14831        }
14832    }
14833
14834    private final class CheckForTap implements Runnable {
14835        public void run() {
14836            mPrivateFlags &= ~PREPRESSED;
14837            setPressed(true);
14838            checkForLongClick(ViewConfiguration.getTapTimeout());
14839        }
14840    }
14841
14842    private final class PerformClick implements Runnable {
14843        public void run() {
14844            performClick();
14845        }
14846    }
14847
14848    /** @hide */
14849    public void hackTurnOffWindowResizeAnim(boolean off) {
14850        mAttachInfo.mTurnOffWindowResizeAnim = off;
14851    }
14852
14853    /**
14854     * This method returns a ViewPropertyAnimator object, which can be used to animate
14855     * specific properties on this View.
14856     *
14857     * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View.
14858     */
14859    public ViewPropertyAnimator animate() {
14860        if (mAnimator == null) {
14861            mAnimator = new ViewPropertyAnimator(this);
14862        }
14863        return mAnimator;
14864    }
14865
14866    /**
14867     * Interface definition for a callback to be invoked when a key event is
14868     * dispatched to this view. The callback will be invoked before the key
14869     * event is given to the view.
14870     */
14871    public interface OnKeyListener {
14872        /**
14873         * Called when a key is dispatched to a view. This allows listeners to
14874         * get a chance to respond before the target view.
14875         *
14876         * @param v The view the key has been dispatched to.
14877         * @param keyCode The code for the physical key that was pressed
14878         * @param event The KeyEvent object containing full information about
14879         *        the event.
14880         * @return True if the listener has consumed the event, false otherwise.
14881         */
14882        boolean onKey(View v, int keyCode, KeyEvent event);
14883    }
14884
14885    /**
14886     * Interface definition for a callback to be invoked when a touch event is
14887     * dispatched to this view. The callback will be invoked before the touch
14888     * event is given to the view.
14889     */
14890    public interface OnTouchListener {
14891        /**
14892         * Called when a touch event is dispatched to a view. This allows listeners to
14893         * get a chance to respond before the target view.
14894         *
14895         * @param v The view the touch event has been dispatched to.
14896         * @param event The MotionEvent object containing full information about
14897         *        the event.
14898         * @return True if the listener has consumed the event, false otherwise.
14899         */
14900        boolean onTouch(View v, MotionEvent event);
14901    }
14902
14903    /**
14904     * Interface definition for a callback to be invoked when a hover event is
14905     * dispatched to this view. The callback will be invoked before the hover
14906     * event is given to the view.
14907     */
14908    public interface OnHoverListener {
14909        /**
14910         * Called when a hover event is dispatched to a view. This allows listeners to
14911         * get a chance to respond before the target view.
14912         *
14913         * @param v The view the hover event has been dispatched to.
14914         * @param event The MotionEvent object containing full information about
14915         *        the event.
14916         * @return True if the listener has consumed the event, false otherwise.
14917         */
14918        boolean onHover(View v, MotionEvent event);
14919    }
14920
14921    /**
14922     * Interface definition for a callback to be invoked when a generic motion event is
14923     * dispatched to this view. The callback will be invoked before the generic motion
14924     * event is given to the view.
14925     */
14926    public interface OnGenericMotionListener {
14927        /**
14928         * Called when a generic motion event is dispatched to a view. This allows listeners to
14929         * get a chance to respond before the target view.
14930         *
14931         * @param v The view the generic motion event has been dispatched to.
14932         * @param event The MotionEvent object containing full information about
14933         *        the event.
14934         * @return True if the listener has consumed the event, false otherwise.
14935         */
14936        boolean onGenericMotion(View v, MotionEvent event);
14937    }
14938
14939    /**
14940     * Interface definition for a callback to be invoked when a view has been clicked and held.
14941     */
14942    public interface OnLongClickListener {
14943        /**
14944         * Called when a view has been clicked and held.
14945         *
14946         * @param v The view that was clicked and held.
14947         *
14948         * @return true if the callback consumed the long click, false otherwise.
14949         */
14950        boolean onLongClick(View v);
14951    }
14952
14953    /**
14954     * Interface definition for a callback to be invoked when a drag is being dispatched
14955     * to this view.  The callback will be invoked before the hosting view's own
14956     * onDrag(event) method.  If the listener wants to fall back to the hosting view's
14957     * onDrag(event) behavior, it should return 'false' from this callback.
14958     *
14959     * <div class="special reference">
14960     * <h3>Developer Guides</h3>
14961     * <p>For a guide to implementing drag and drop features, read the
14962     * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
14963     * </div>
14964     */
14965    public interface OnDragListener {
14966        /**
14967         * Called when a drag event is dispatched to a view. This allows listeners
14968         * to get a chance to override base View behavior.
14969         *
14970         * @param v The View that received the drag event.
14971         * @param event The {@link android.view.DragEvent} object for the drag event.
14972         * @return {@code true} if the drag event was handled successfully, or {@code false}
14973         * if the drag event was not handled. Note that {@code false} will trigger the View
14974         * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler.
14975         */
14976        boolean onDrag(View v, DragEvent event);
14977    }
14978
14979    /**
14980     * Interface definition for a callback to be invoked when the focus state of
14981     * a view changed.
14982     */
14983    public interface OnFocusChangeListener {
14984        /**
14985         * Called when the focus state of a view has changed.
14986         *
14987         * @param v The view whose state has changed.
14988         * @param hasFocus The new focus state of v.
14989         */
14990        void onFocusChange(View v, boolean hasFocus);
14991    }
14992
14993    /**
14994     * Interface definition for a callback to be invoked when a view is clicked.
14995     */
14996    public interface OnClickListener {
14997        /**
14998         * Called when a view has been clicked.
14999         *
15000         * @param v The view that was clicked.
15001         */
15002        void onClick(View v);
15003    }
15004
15005    /**
15006     * Interface definition for a callback to be invoked when the context menu
15007     * for this view is being built.
15008     */
15009    public interface OnCreateContextMenuListener {
15010        /**
15011         * Called when the context menu for this view is being built. It is not
15012         * safe to hold onto the menu after this method returns.
15013         *
15014         * @param menu The context menu that is being built
15015         * @param v The view for which the context menu is being built
15016         * @param menuInfo Extra information about the item for which the
15017         *            context menu should be shown. This information will vary
15018         *            depending on the class of v.
15019         */
15020        void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
15021    }
15022
15023    /**
15024     * Interface definition for a callback to be invoked when the status bar changes
15025     * visibility.  This reports <strong>global</strong> changes to the system UI
15026     * state, not just what the application is requesting.
15027     *
15028     * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener)
15029     */
15030    public interface OnSystemUiVisibilityChangeListener {
15031        /**
15032         * Called when the status bar changes visibility because of a call to
15033         * {@link View#setSystemUiVisibility(int)}.
15034         *
15035         * @param visibility  Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE} or
15036         * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}.  This tells you the
15037         * <strong>global</strong> state of the UI visibility flags, not what your
15038         * app is currently applying.
15039         */
15040        public void onSystemUiVisibilityChange(int visibility);
15041    }
15042
15043    /**
15044     * Interface definition for a callback to be invoked when this view is attached
15045     * or detached from its window.
15046     */
15047    public interface OnAttachStateChangeListener {
15048        /**
15049         * Called when the view is attached to a window.
15050         * @param v The view that was attached
15051         */
15052        public void onViewAttachedToWindow(View v);
15053        /**
15054         * Called when the view is detached from a window.
15055         * @param v The view that was detached
15056         */
15057        public void onViewDetachedFromWindow(View v);
15058    }
15059
15060    private final class UnsetPressedState implements Runnable {
15061        public void run() {
15062            setPressed(false);
15063        }
15064    }
15065
15066    /**
15067     * Base class for derived classes that want to save and restore their own
15068     * state in {@link android.view.View#onSaveInstanceState()}.
15069     */
15070    public static class BaseSavedState extends AbsSavedState {
15071        /**
15072         * Constructor used when reading from a parcel. Reads the state of the superclass.
15073         *
15074         * @param source
15075         */
15076        public BaseSavedState(Parcel source) {
15077            super(source);
15078        }
15079
15080        /**
15081         * Constructor called by derived classes when creating their SavedState objects
15082         *
15083         * @param superState The state of the superclass of this view
15084         */
15085        public BaseSavedState(Parcelable superState) {
15086            super(superState);
15087        }
15088
15089        public static final Parcelable.Creator<BaseSavedState> CREATOR =
15090                new Parcelable.Creator<BaseSavedState>() {
15091            public BaseSavedState createFromParcel(Parcel in) {
15092                return new BaseSavedState(in);
15093            }
15094
15095            public BaseSavedState[] newArray(int size) {
15096                return new BaseSavedState[size];
15097            }
15098        };
15099    }
15100
15101    /**
15102     * A set of information given to a view when it is attached to its parent
15103     * window.
15104     */
15105    static class AttachInfo {
15106        interface Callbacks {
15107            void playSoundEffect(int effectId);
15108            boolean performHapticFeedback(int effectId, boolean always);
15109        }
15110
15111        /**
15112         * InvalidateInfo is used to post invalidate(int, int, int, int) messages
15113         * to a Handler. This class contains the target (View) to invalidate and
15114         * the coordinates of the dirty rectangle.
15115         *
15116         * For performance purposes, this class also implements a pool of up to
15117         * POOL_LIMIT objects that get reused. This reduces memory allocations
15118         * whenever possible.
15119         */
15120        static class InvalidateInfo implements Poolable<InvalidateInfo> {
15121            private static final int POOL_LIMIT = 10;
15122            private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
15123                    Pools.finitePool(new PoolableManager<InvalidateInfo>() {
15124                        public InvalidateInfo newInstance() {
15125                            return new InvalidateInfo();
15126                        }
15127
15128                        public void onAcquired(InvalidateInfo element) {
15129                        }
15130
15131                        public void onReleased(InvalidateInfo element) {
15132                            element.target = null;
15133                        }
15134                    }, POOL_LIMIT)
15135            );
15136
15137            private InvalidateInfo mNext;
15138            private boolean mIsPooled;
15139
15140            View target;
15141
15142            int left;
15143            int top;
15144            int right;
15145            int bottom;
15146
15147            public void setNextPoolable(InvalidateInfo element) {
15148                mNext = element;
15149            }
15150
15151            public InvalidateInfo getNextPoolable() {
15152                return mNext;
15153            }
15154
15155            static InvalidateInfo acquire() {
15156                return sPool.acquire();
15157            }
15158
15159            void release() {
15160                sPool.release(this);
15161            }
15162
15163            public boolean isPooled() {
15164                return mIsPooled;
15165            }
15166
15167            public void setPooled(boolean isPooled) {
15168                mIsPooled = isPooled;
15169            }
15170        }
15171
15172        final IWindowSession mSession;
15173
15174        final IWindow mWindow;
15175
15176        final IBinder mWindowToken;
15177
15178        final Callbacks mRootCallbacks;
15179
15180        HardwareCanvas mHardwareCanvas;
15181
15182        /**
15183         * The top view of the hierarchy.
15184         */
15185        View mRootView;
15186
15187        IBinder mPanelParentWindowToken;
15188        Surface mSurface;
15189
15190        boolean mHardwareAccelerated;
15191        boolean mHardwareAccelerationRequested;
15192        HardwareRenderer mHardwareRenderer;
15193
15194        boolean mScreenOn;
15195
15196        /**
15197         * Scale factor used by the compatibility mode
15198         */
15199        float mApplicationScale;
15200
15201        /**
15202         * Indicates whether the application is in compatibility mode
15203         */
15204        boolean mScalingRequired;
15205
15206        /**
15207         * If set, ViewAncestor doesn't use its lame animation for when the window resizes.
15208         */
15209        boolean mTurnOffWindowResizeAnim;
15210
15211        /**
15212         * Left position of this view's window
15213         */
15214        int mWindowLeft;
15215
15216        /**
15217         * Top position of this view's window
15218         */
15219        int mWindowTop;
15220
15221        /**
15222         * Indicates whether views need to use 32-bit drawing caches
15223         */
15224        boolean mUse32BitDrawingCache;
15225
15226        /**
15227         * For windows that are full-screen but using insets to layout inside
15228         * of the screen decorations, these are the current insets for the
15229         * content of the window.
15230         */
15231        final Rect mContentInsets = new Rect();
15232
15233        /**
15234         * For windows that are full-screen but using insets to layout inside
15235         * of the screen decorations, these are the current insets for the
15236         * actual visible parts of the window.
15237         */
15238        final Rect mVisibleInsets = new Rect();
15239
15240        /**
15241         * The internal insets given by this window.  This value is
15242         * supplied by the client (through
15243         * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
15244         * be given to the window manager when changed to be used in laying
15245         * out windows behind it.
15246         */
15247        final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
15248                = new ViewTreeObserver.InternalInsetsInfo();
15249
15250        /**
15251         * All views in the window's hierarchy that serve as scroll containers,
15252         * used to determine if the window can be resized or must be panned
15253         * to adjust for a soft input area.
15254         */
15255        final ArrayList<View> mScrollContainers = new ArrayList<View>();
15256
15257        final KeyEvent.DispatcherState mKeyDispatchState
15258                = new KeyEvent.DispatcherState();
15259
15260        /**
15261         * Indicates whether the view's window currently has the focus.
15262         */
15263        boolean mHasWindowFocus;
15264
15265        /**
15266         * The current visibility of the window.
15267         */
15268        int mWindowVisibility;
15269
15270        /**
15271         * Indicates the time at which drawing started to occur.
15272         */
15273        long mDrawingTime;
15274
15275        /**
15276         * Indicates whether or not ignoring the DIRTY_MASK flags.
15277         */
15278        boolean mIgnoreDirtyState;
15279
15280        /**
15281         * This flag tracks when the mIgnoreDirtyState flag is set during draw(),
15282         * to avoid clearing that flag prematurely.
15283         */
15284        boolean mSetIgnoreDirtyState = false;
15285
15286        /**
15287         * Indicates whether the view's window is currently in touch mode.
15288         */
15289        boolean mInTouchMode;
15290
15291        /**
15292         * Indicates that ViewAncestor should trigger a global layout change
15293         * the next time it performs a traversal
15294         */
15295        boolean mRecomputeGlobalAttributes;
15296
15297        /**
15298         * Always report new attributes at next traversal.
15299         */
15300        boolean mForceReportNewAttributes;
15301
15302        /**
15303         * Set during a traveral if any views want to keep the screen on.
15304         */
15305        boolean mKeepScreenOn;
15306
15307        /**
15308         * Bitwise-or of all of the values that views have passed to setSystemUiVisibility().
15309         */
15310        int mSystemUiVisibility;
15311
15312        /**
15313         * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener
15314         * attached.
15315         */
15316        boolean mHasSystemUiListeners;
15317
15318        /**
15319         * Set if the visibility of any views has changed.
15320         */
15321        boolean mViewVisibilityChanged;
15322
15323        /**
15324         * Set to true if a view has been scrolled.
15325         */
15326        boolean mViewScrollChanged;
15327
15328        /**
15329         * Global to the view hierarchy used as a temporary for dealing with
15330         * x/y points in the transparent region computations.
15331         */
15332        final int[] mTransparentLocation = new int[2];
15333
15334        /**
15335         * Global to the view hierarchy used as a temporary for dealing with
15336         * x/y points in the ViewGroup.invalidateChild implementation.
15337         */
15338        final int[] mInvalidateChildLocation = new int[2];
15339
15340
15341        /**
15342         * Global to the view hierarchy used as a temporary for dealing with
15343         * x/y location when view is transformed.
15344         */
15345        final float[] mTmpTransformLocation = new float[2];
15346
15347        /**
15348         * The view tree observer used to dispatch global events like
15349         * layout, pre-draw, touch mode change, etc.
15350         */
15351        final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
15352
15353        /**
15354         * A Canvas used by the view hierarchy to perform bitmap caching.
15355         */
15356        Canvas mCanvas;
15357
15358        /**
15359         * The view root impl.
15360         */
15361        final ViewRootImpl mViewRootImpl;
15362
15363        /**
15364         * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
15365         * handler can be used to pump events in the UI events queue.
15366         */
15367        final Handler mHandler;
15368
15369        /**
15370         * Temporary for use in computing invalidate rectangles while
15371         * calling up the hierarchy.
15372         */
15373        final Rect mTmpInvalRect = new Rect();
15374
15375        /**
15376         * Temporary for use in computing hit areas with transformed views
15377         */
15378        final RectF mTmpTransformRect = new RectF();
15379
15380        /**
15381         * Temporary list for use in collecting focusable descendents of a view.
15382         */
15383        final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
15384
15385        /**
15386         * The id of the window for accessibility purposes.
15387         */
15388        int mAccessibilityWindowId = View.NO_ID;
15389
15390        /**
15391         * Creates a new set of attachment information with the specified
15392         * events handler and thread.
15393         *
15394         * @param handler the events handler the view must use
15395         */
15396        AttachInfo(IWindowSession session, IWindow window,
15397                ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) {
15398            mSession = session;
15399            mWindow = window;
15400            mWindowToken = window.asBinder();
15401            mViewRootImpl = viewRootImpl;
15402            mHandler = handler;
15403            mRootCallbacks = effectPlayer;
15404        }
15405    }
15406
15407    /**
15408     * <p>ScrollabilityCache holds various fields used by a View when scrolling
15409     * is supported. This avoids keeping too many unused fields in most
15410     * instances of View.</p>
15411     */
15412    private static class ScrollabilityCache implements Runnable {
15413
15414        /**
15415         * Scrollbars are not visible
15416         */
15417        public static final int OFF = 0;
15418
15419        /**
15420         * Scrollbars are visible
15421         */
15422        public static final int ON = 1;
15423
15424        /**
15425         * Scrollbars are fading away
15426         */
15427        public static final int FADING = 2;
15428
15429        public boolean fadeScrollBars;
15430
15431        public int fadingEdgeLength;
15432        public int scrollBarDefaultDelayBeforeFade;
15433        public int scrollBarFadeDuration;
15434
15435        public int scrollBarSize;
15436        public ScrollBarDrawable scrollBar;
15437        public float[] interpolatorValues;
15438        public View host;
15439
15440        public final Paint paint;
15441        public final Matrix matrix;
15442        public Shader shader;
15443
15444        public final Interpolator scrollBarInterpolator = new Interpolator(1, 2);
15445
15446        private static final float[] OPAQUE = { 255 };
15447        private static final float[] TRANSPARENT = { 0.0f };
15448
15449        /**
15450         * When fading should start. This time moves into the future every time
15451         * a new scroll happens. Measured based on SystemClock.uptimeMillis()
15452         */
15453        public long fadeStartTime;
15454
15455
15456        /**
15457         * The current state of the scrollbars: ON, OFF, or FADING
15458         */
15459        public int state = OFF;
15460
15461        private int mLastColor;
15462
15463        public ScrollabilityCache(ViewConfiguration configuration, View host) {
15464            fadingEdgeLength = configuration.getScaledFadingEdgeLength();
15465            scrollBarSize = configuration.getScaledScrollBarSize();
15466            scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay();
15467            scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration();
15468
15469            paint = new Paint();
15470            matrix = new Matrix();
15471            // use use a height of 1, and then wack the matrix each time we
15472            // actually use it.
15473            shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
15474
15475            paint.setShader(shader);
15476            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
15477            this.host = host;
15478        }
15479
15480        public void setFadeColor(int color) {
15481            if (color != 0 && color != mLastColor) {
15482                mLastColor = color;
15483                color |= 0xFF000000;
15484
15485                shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000,
15486                        color & 0x00FFFFFF, Shader.TileMode.CLAMP);
15487
15488                paint.setShader(shader);
15489                // Restore the default transfer mode (src_over)
15490                paint.setXfermode(null);
15491            }
15492        }
15493
15494        public void run() {
15495            long now = AnimationUtils.currentAnimationTimeMillis();
15496            if (now >= fadeStartTime) {
15497
15498                // the animation fades the scrollbars out by changing
15499                // the opacity (alpha) from fully opaque to fully
15500                // transparent
15501                int nextFrame = (int) now;
15502                int framesCount = 0;
15503
15504                Interpolator interpolator = scrollBarInterpolator;
15505
15506                // Start opaque
15507                interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE);
15508
15509                // End transparent
15510                nextFrame += scrollBarFadeDuration;
15511                interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT);
15512
15513                state = FADING;
15514
15515                // Kick off the fade animation
15516                host.invalidate(true);
15517            }
15518        }
15519    }
15520
15521    /**
15522     * Resuable callback for sending
15523     * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event.
15524     */
15525    private class SendViewScrolledAccessibilityEvent implements Runnable {
15526        public volatile boolean mIsPending;
15527
15528        public void run() {
15529            sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED);
15530            mIsPending = false;
15531        }
15532    }
15533
15534    /**
15535     * <p>
15536     * This class represents a delegate that can be registered in a {@link View}
15537     * to enhance accessibility support via composition rather via inheritance.
15538     * It is specifically targeted to widget developers that extend basic View
15539     * classes i.e. classes in package android.view, that would like their
15540     * applications to be backwards compatible.
15541     * </p>
15542     * <p>
15543     * A scenario in which a developer would like to use an accessibility delegate
15544     * is overriding a method introduced in a later API version then the minimal API
15545     * version supported by the application. For example, the method
15546     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available
15547     * in API version 4 when the accessibility APIs were first introduced. If a
15548     * developer would like his application to run on API version 4 devices (assuming
15549     * all other APIs used by the application are version 4 or lower) and take advantage
15550     * of this method, instead of overriding the method which would break the application's
15551     * backwards compatibility, he can override the corresponding method in this
15552     * delegate and register the delegate in the target View if the API version of
15553     * the system is high enough i.e. the API version is same or higher to the API
15554     * version that introduced
15555     * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}.
15556     * </p>
15557     * <p>
15558     * Here is an example implementation:
15559     * </p>
15560     * <code><pre><p>
15561     * if (Build.VERSION.SDK_INT >= 14) {
15562     *     // If the API version is equal of higher than the version in
15563     *     // which onInitializeAccessibilityNodeInfo was introduced we
15564     *     // register a delegate with a customized implementation.
15565     *     View view = findViewById(R.id.view_id);
15566     *     view.setAccessibilityDelegate(new AccessibilityDelegate() {
15567     *         public void onInitializeAccessibilityNodeInfo(View host,
15568     *                 AccessibilityNodeInfo info) {
15569     *             // Let the default implementation populate the info.
15570     *             super.onInitializeAccessibilityNodeInfo(host, info);
15571     *             // Set some other information.
15572     *             info.setEnabled(host.isEnabled());
15573     *         }
15574     *     });
15575     * }
15576     * </code></pre></p>
15577     * <p>
15578     * This delegate contains methods that correspond to the accessibility methods
15579     * in View. If a delegate has been specified the implementation in View hands
15580     * off handling to the corresponding method in this delegate. The default
15581     * implementation the delegate methods behaves exactly as the corresponding
15582     * method in View for the case of no accessibility delegate been set. Hence,
15583     * to customize the behavior of a View method, clients can override only the
15584     * corresponding delegate method without altering the behavior of the rest
15585     * accessibility related methods of the host view.
15586     * </p>
15587     */
15588    public static class AccessibilityDelegate {
15589
15590        /**
15591         * Sends an accessibility event of the given type. If accessibility is not
15592         * enabled this method has no effect.
15593         * <p>
15594         * The default implementation behaves as {@link View#sendAccessibilityEvent(int)
15595         *  View#sendAccessibilityEvent(int)} for the case of no accessibility delegate
15596         * been set.
15597         * </p>
15598         *
15599         * @param host The View hosting the delegate.
15600         * @param eventType The type of the event to send.
15601         *
15602         * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int)
15603         */
15604        public void sendAccessibilityEvent(View host, int eventType) {
15605            host.sendAccessibilityEventInternal(eventType);
15606        }
15607
15608        /**
15609         * Sends an accessibility event. This method behaves exactly as
15610         * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an
15611         * empty {@link AccessibilityEvent} and does not perform a check whether
15612         * accessibility is enabled.
15613         * <p>
15614         * The default implementation behaves as
15615         * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15616         *  View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for
15617         * the case of no accessibility delegate been set.
15618         * </p>
15619         *
15620         * @param host The View hosting the delegate.
15621         * @param event The event to send.
15622         *
15623         * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15624         *      View#sendAccessibilityEventUnchecked(AccessibilityEvent)
15625         */
15626        public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) {
15627            host.sendAccessibilityEventUncheckedInternal(event);
15628        }
15629
15630        /**
15631         * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then
15632         * to its children for adding their text content to the event.
15633         * <p>
15634         * The default implementation behaves as
15635         * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15636         *  View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for
15637         * the case of no accessibility delegate been set.
15638         * </p>
15639         *
15640         * @param host The View hosting the delegate.
15641         * @param event The event.
15642         * @return True if the event population was completed.
15643         *
15644         * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15645         *      View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)
15646         */
15647        public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15648            return host.dispatchPopulateAccessibilityEventInternal(event);
15649        }
15650
15651        /**
15652         * Gives a chance to the host View to populate the accessibility event with its
15653         * text content.
15654         * <p>
15655         * The default implementation behaves as
15656         * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent)
15657         *  View#onPopulateAccessibilityEvent(AccessibilityEvent)} for
15658         * the case of no accessibility delegate been set.
15659         * </p>
15660         *
15661         * @param host The View hosting the delegate.
15662         * @param event The accessibility event which to populate.
15663         *
15664         * @see View#onPopulateAccessibilityEvent(AccessibilityEvent)
15665         *      View#onPopulateAccessibilityEvent(AccessibilityEvent)
15666         */
15667        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
15668            host.onPopulateAccessibilityEventInternal(event);
15669        }
15670
15671        /**
15672         * Initializes an {@link AccessibilityEvent} with information about the
15673         * the host View which is the event source.
15674         * <p>
15675         * The default implementation behaves as
15676         * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent)
15677         *  View#onInitializeAccessibilityEvent(AccessibilityEvent)} for
15678         * the case of no accessibility delegate been set.
15679         * </p>
15680         *
15681         * @param host The View hosting the delegate.
15682         * @param event The event to initialize.
15683         *
15684         * @see View#onInitializeAccessibilityEvent(AccessibilityEvent)
15685         *      View#onInitializeAccessibilityEvent(AccessibilityEvent)
15686         */
15687        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
15688            host.onInitializeAccessibilityEventInternal(event);
15689        }
15690
15691        /**
15692         * Initializes an {@link AccessibilityNodeInfo} with information about the host view.
15693         * <p>
15694         * The default implementation behaves as
15695         * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15696         *  View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for
15697         * the case of no accessibility delegate been set.
15698         * </p>
15699         *
15700         * @param host The View hosting the delegate.
15701         * @param info The instance to initialize.
15702         *
15703         * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15704         *      View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)
15705         */
15706        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) {
15707            host.onInitializeAccessibilityNodeInfoInternal(info);
15708        }
15709
15710        /**
15711         * Called when a child of the host View has requested sending an
15712         * {@link AccessibilityEvent} and gives an opportunity to the parent (the host)
15713         * to augment the event.
15714         * <p>
15715         * The default implementation behaves as
15716         * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15717         *  ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for
15718         * the case of no accessibility delegate been set.
15719         * </p>
15720         *
15721         * @param host The View hosting the delegate.
15722         * @param child The child which requests sending the event.
15723         * @param event The event to be sent.
15724         * @return True if the event should be sent
15725         *
15726         * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15727         *      ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)
15728         */
15729        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
15730                AccessibilityEvent event) {
15731            return host.onRequestSendAccessibilityEventInternal(child, event);
15732        }
15733
15734        /**
15735         * Gets the provider for managing a virtual view hierarchy rooted at this View
15736         * and reported to {@link android.accessibilityservice.AccessibilityService}s
15737         * that explore the window content.
15738         * <p>
15739         * The default implementation behaves as
15740         * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for
15741         * the case of no accessibility delegate been set.
15742         * </p>
15743         *
15744         * @return The provider.
15745         *
15746         * @see AccessibilityNodeProvider
15747         */
15748        public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) {
15749            return null;
15750        }
15751    }
15752}
15753